Skip to main content

euv_core/render/command/
impl.rs

1use super::*;
2
3/// Default empty per-frame arena initialized with FNV-1a digest seeds.
4impl Default for DisplayListFrameArena {
5    /// Creates an empty `DisplayListFrameArena`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Ready display list frame arena.
10    fn default() -> Self {
11        Self {
12            string_pool: Vec::new(),
13            portals_scratch: Vec::new(),
14            z_sort_scratch: Vec::new(),
15            portal_ancestors_scratch: Vec::new(),
16            base_layer_version: 0,
17            prev_base_digest: 0,
18            cur_base_digest: FNV1A_OFFSET_BASIS,
19            running_fast_hash: FNV1A_OFFSET_BASIS,
20            base_layer_finalized: false,
21        }
22    }
23}
24
25/// Non-allocating `Clone` preserving digest/version metadata while keeping cloned scratch buffers empty.
26impl Clone for DisplayListFrameArena {
27    /// Clones digest and version metadata without copying transient scratch buffers.
28    ///
29    /// # Arguments
30    ///
31    /// - `&Self` - Source frame arena.
32    ///
33    /// # Returns
34    ///
35    /// - `Self` - Cloned metadata with empty scratch buffers.
36    fn clone(&self) -> Self {
37        let Self {
38            base_layer_version,
39            prev_base_digest,
40            cur_base_digest,
41            running_fast_hash,
42            base_layer_finalized,
43            ..
44        } = self;
45        Self {
46            string_pool: Vec::new(),
47            portals_scratch: Vec::new(),
48            z_sort_scratch: Vec::new(),
49            portal_ancestors_scratch: Vec::new(),
50            base_layer_version: *base_layer_version,
51            prev_base_digest: *prev_base_digest,
52            cur_base_digest: *cur_base_digest,
53            running_fast_hash: *running_fast_hash,
54            base_layer_finalized: *base_layer_finalized,
55        }
56    }
57}
58
59/// Scratch-oblivious equality so internal pool/version state never perturbs logical `DisplayList` equality.
60impl PartialEq for DisplayListFrameArena {
61    /// Treats all frame arenas as equal for logical `DisplayList` comparisons.
62    ///
63    /// # Arguments
64    ///
65    /// - `&Self` - First frame arena.
66    /// - `&Self` - Second frame arena.
67    ///
68    /// # Returns
69    ///
70    /// - `bool` - Always `true`.
71    fn eq(&self, _other: &Self) -> bool {
72        true
73    }
74}
75
76/// Command emission helpers for `DisplayList`.
77impl DisplayList {
78    /// Pre-reserves persistent command and string-pool storage so steady-state frames incur zero container reallocations.
79    ///
80    /// # Arguments
81    ///
82    /// - `&Self` - Mutable display list.
83    pub(crate) fn reserve_steady_state(&mut self) {
84        let Self {
85            commands, arena, ..
86        } = self;
87        if commands.capacity() < 512 {
88            commands.reserve(512 - commands.len());
89        }
90        if arena.string_pool.capacity() < DISPLAY_LIST_STRING_POOL_CAP {
91            arena
92                .string_pool
93                .reserve(DISPLAY_LIST_STRING_POOL_CAP - arena.string_pool.len());
94        }
95    }
96
97    /// Pre-populates spare pooled string buffers for scrollable scenes whose visible text count varies slightly across scroll positions.
98    ///
99    /// # Arguments
100    ///
101    /// - `&Self` - Mutable display list.
102    /// - `usize` - Number of spare 128-byte pooled string slots to append up to `DISPLAY_LIST_STRING_POOL_CAP`.
103    pub(crate) fn prewarm_scroll_string_pool(&mut self, spare_count: usize) {
104        let Self { arena, .. } = self;
105        let target: usize = arena
106            .string_pool
107            .len()
108            .saturating_add(spare_count)
109            .min(DISPLAY_LIST_STRING_POOL_CAP);
110        if arena.string_pool.capacity() < DISPLAY_LIST_STRING_POOL_CAP {
111            arena
112                .string_pool
113                .reserve(DISPLAY_LIST_STRING_POOL_CAP - arena.string_pool.len());
114        }
115        while arena.string_pool.len() < target {
116            arena.string_pool.push(String::with_capacity(128));
117        }
118    }
119
120    /// Clears all commands while recycling backing `String` buffers into the per-frame string pool.
121    ///
122    /// # Arguments
123    ///
124    /// - `&Self` - Mutable display list.
125    /// - `Size` - Target logical viewport size.
126    /// - `f32` - Active DPI scale factor.
127    pub fn reset(&mut self, viewport: Size, scale_factor: f32) {
128        let safe_scale: f32 = scale_factor.max(0.5);
129        let Self {
130            commands,
131            viewport: vp,
132            scale_factor: sf,
133            portal_split_index,
134            arena,
135        } = self;
136        if arena.string_pool.capacity() < DISPLAY_LIST_STRING_POOL_CAP {
137            arena
138                .string_pool
139                .reserve(DISPLAY_LIST_STRING_POOL_CAP - arena.string_pool.len());
140        }
141        let pool_start: usize = arena.string_pool.len();
142        for cmd in commands.drain(..) {
143            match cmd {
144                DrawCommand::TextRun { mut text, .. } | DrawCommand::TextCaret { mut text, .. }
145                    if text.capacity() > 0
146                        && arena.string_pool.len() < DISPLAY_LIST_STRING_POOL_CAP =>
147                {
148                    text.clear();
149                    arena.string_pool.push(text);
150                }
151                _ => {}
152            }
153        }
154        if arena.string_pool.len() > pool_start + 1 {
155            arena.string_pool[pool_start..].reverse();
156        }
157        *vp = viewport;
158        *sf = safe_scale;
159        *portal_split_index = 0;
160        let mut seed: u64 = FNV1A_OFFSET_BASIS;
161        Self::mix_hash(&mut seed, viewport.get_width().to_bits() as u64);
162        Self::mix_hash(&mut seed, viewport.get_height().to_bits() as u64);
163        Self::mix_hash(&mut seed, safe_scale.to_bits() as u64);
164        arena.prev_base_digest = arena.cur_base_digest;
165        arena.cur_base_digest = seed;
166        arena.running_fast_hash = seed;
167        arena.base_layer_finalized = false;
168    }
169
170    /// Allocates or reuses a pooled `String` filled with `src` so steady-state text emission performs zero heap allocations.
171    ///
172    /// # Arguments
173    ///
174    /// - `&Self` - Mutable display list owning the string pool.
175    /// - `&str` - Source UTF-8 text slice.
176    ///
177    /// # Returns
178    ///
179    /// - `String` - Reused or newly allocated string equal to `src`.
180    #[inline]
181    #[must_use]
182    pub(crate) fn alloc_text(&mut self, src: &str) -> String {
183        if src.is_empty() {
184            return String::new();
185        }
186        let Self { arena, .. } = self;
187        let pool: &mut Vec<String> = &mut arena.string_pool;
188        let len: usize = pool.len();
189        if len > 0 {
190            let need: usize = src.len();
191            if pool[len - 1].capacity() >= need
192                && let Some(mut reused) = pool.pop()
193            {
194                reused.clear();
195                reused.push_str(src);
196                return reused;
197            }
198            for idx in (0..len.saturating_sub(1)).rev() {
199                if pool[idx].capacity() >= need {
200                    let mut reused: String = pool.swap_remove(idx);
201                    reused.clear();
202                    reused.push_str(src);
203                    return reused;
204                }
205            }
206            if let Some(mut reused) = pool.pop() {
207                reused.clear();
208                reused.push_str(src);
209                return reused;
210            }
211        }
212        let mut fresh: String = String::with_capacity(src.len().max(128));
213        fresh.push_str(src);
214        fresh
215    }
216
217    /// Appends a single `DrawCommand` to the list and updates O(1) streaming digests incrementally.
218    ///
219    /// # Arguments
220    ///
221    /// - `&Self` - Mutable display list.
222    /// - `DrawCommand` - Command to push.
223    pub fn push(&mut self, command: DrawCommand) {
224        let Self {
225            commands, arena, ..
226        } = self;
227        Self::fold_command_fast(&mut arena.running_fast_hash, &command);
228        if !arena.base_layer_finalized {
229            Self::fold_command_full(&mut arena.cur_base_digest, &command);
230        }
231        commands.push(command);
232    }
233
234    /// Captures the current streaming digest pair before a speculative clip push so empty-clip rollback stays exact.
235    ///
236    /// # Arguments
237    ///
238    /// - `&Self` - Display list reference.
239    ///
240    /// # Returns
241    ///
242    /// - `(u64, u64)` - Tuple `(running_fast_hash, cur_base_digest)`.
243    #[inline]
244    #[must_use]
245    pub(crate) fn snapshot_digest_state(&self) -> (u64, u64) {
246        let Self { arena, .. } = self;
247        (arena.running_fast_hash, arena.cur_base_digest)
248    }
249
250    /// Pops an empty speculative clip command and restores streaming digests to `saved`.
251    ///
252    /// # Arguments
253    ///
254    /// - `&Self` - Mutable display list.
255    /// - `(u64, u64)` - Saved `(running_fast_hash, cur_base_digest)` prior to the clip push.
256    #[inline]
257    pub(crate) fn pop_empty_clip(&mut self, saved: (u64, u64)) {
258        let Self {
259            commands, arena, ..
260        } = self;
261        let _: Option<DrawCommand> = commands.pop();
262        arena.running_fast_hash = saved.0;
263        arena.cur_base_digest = saved.1;
264    }
265
266    /// Locks the base-layer split index and bumps the monotonic `base_layer_version` only if base commands changed.
267    ///
268    /// # Arguments
269    ///
270    /// - `&Self` - Mutable display list.
271    /// - `usize` - Command index separating base-scene commands from top-layer portals.
272    #[inline]
273    pub(crate) fn finalize_base_layer(&mut self, split_index: usize) {
274        let Self {
275            portal_split_index,
276            arena,
277            ..
278        } = self;
279        *portal_split_index = split_index;
280        Self::mix_hash(&mut arena.cur_base_digest, split_index as u64);
281        if arena.base_layer_version == 0 || arena.cur_base_digest != arena.prev_base_digest {
282            arena.base_layer_version = arena.base_layer_version.wrapping_add(1).max(1);
283        }
284        arena.base_layer_finalized = true;
285    }
286
287    /// Returns the O(1) monotonic base-layer version counter (`0` before the first finalized paint).
288    ///
289    /// # Arguments
290    ///
291    /// - `&Self` - Display list reference.
292    ///
293    /// # Returns
294    ///
295    /// - `u64` - Monotonic base-layer version incremented only when base commands change.
296    #[inline]
297    #[must_use]
298    pub fn base_layer_version(&self) -> u64 {
299        let Self { arena, .. } = self;
300        arena.base_layer_version
301    }
302
303    /// Returns total emitted command count.
304    ///
305    /// # Arguments
306    ///
307    /// - `&Self` - Display list reference.
308    ///
309    /// # Returns
310    ///
311    /// - `usize` - Number of commands.
312    #[must_use]
313    pub fn len(&self) -> usize {
314        self.get_commands().len()
315    }
316
317    /// Returns true when the display list contains zero commands.
318    ///
319    /// # Arguments
320    ///
321    /// - `&Self` - Display list reference.
322    ///
323    /// # Returns
324    ///
325    /// - `bool` - True if empty.
326    #[must_use]
327    pub fn is_empty(&self) -> bool {
328        self.get_commands().is_empty()
329    }
330
331    /// Folds a 64-bit value into an FNV-1a accumulator.
332    ///
333    /// # Arguments
334    ///
335    /// - `&mut u64` - Mutable hash accumulator.
336    /// - `u64` - Value to fold into the digest.
337    #[inline(always)]
338    fn mix_hash(hash: &mut u64, value: u64) {
339        *hash ^= value;
340        *hash = hash.wrapping_mul(FNV1A_PRIME);
341    }
342
343    /// Folds a single `DrawCommand` into the lightweight O(1)-per-push fast frame digest.
344    ///
345    /// # Arguments
346    ///
347    /// - `&mut u64` - Running FNV-1a accumulator.
348    /// - `&DrawCommand` - Command to fold.
349    #[inline]
350    fn fold_command_fast(hash: &mut u64, cmd: &DrawCommand) {
351        match cmd {
352            DrawCommand::Clear(c) => {
353                Self::mix_hash(hash, 1);
354                Self::mix_hash(hash, u32::from_le_bytes(c.to_rgba_bytes()) as u64);
355            }
356            DrawCommand::FillRoundedRect {
357                rect,
358                color,
359                border,
360                ..
361            } => {
362                Self::mix_hash(hash, 2);
363                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
364                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
365                Self::mix_hash(hash, rect.get_width().to_bits() as u64);
366                Self::mix_hash(hash, rect.get_height().to_bits() as u64);
367                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
368                Self::mix_hash(hash, border.get_width().to_bits() as u64);
369            }
370            DrawCommand::LinearGradientRect { rect, gradient, .. } => {
371                Self::mix_hash(hash, 3);
372                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
373                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
374                Self::mix_hash(
375                    hash,
376                    u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64,
377                );
378            }
379            DrawCommand::BoxShadow { rect, shadow, .. } => {
380                Self::mix_hash(hash, 4);
381                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
382                Self::mix_hash(hash, shadow.get_blur_radius().to_bits() as u64);
383            }
384            DrawCommand::BackdropBlur {
385                rect, blur_radius, ..
386            } => {
387                Self::mix_hash(hash, 15);
388                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
389                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
390                Self::mix_hash(hash, blur_radius.to_bits() as u64);
391            }
392            DrawCommand::TextRun { rect, text, style } => {
393                Self::mix_hash(hash, 5);
394                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
395                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
396                Self::mix_hash(hash, text.len() as u64);
397                let bytes: &[u8] = text.as_bytes();
398                let prefix_len: usize = bytes.len().min(16);
399                for &byte in bytes[..prefix_len].iter() {
400                    Self::mix_hash(hash, byte as u64);
401                }
402                Self::mix_hash(
403                    hash,
404                    u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64,
405                );
406            }
407            DrawCommand::TextCaret {
408                text_rect,
409                text,
410                color,
411                ..
412            } => {
413                Self::mix_hash(hash, 13);
414                Self::mix_hash(hash, text_rect.get_x().to_bits() as u64);
415                Self::mix_hash(hash, text_rect.get_y().to_bits() as u64);
416                Self::mix_hash(hash, text.len() as u64);
417                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
418            }
419            DrawCommand::Image { rect, buffer, .. } => {
420                Self::mix_hash(hash, 6);
421                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
422                Self::mix_hash(hash, buffer.get_width() as u64);
423                Self::mix_hash(hash, buffer.get_height() as u64);
424            }
425            DrawCommand::SharedImage {
426                rect,
427                width,
428                height,
429                ..
430            } => {
431                Self::mix_hash(hash, 6);
432                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
433                Self::mix_hash(hash, *width as u64);
434                Self::mix_hash(hash, *height as u64);
435            }
436            DrawCommand::Line {
437                from,
438                to,
439                color,
440                width,
441            } => {
442                Self::mix_hash(hash, 7);
443                Self::mix_hash(hash, from.get_x().to_bits() as u64);
444                Self::mix_hash(hash, to.get_y().to_bits() as u64);
445                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
446                Self::mix_hash(hash, width.to_bits() as u64);
447            }
448            DrawCommand::Circle {
449                center,
450                radius,
451                color,
452            } => {
453                Self::mix_hash(hash, 8);
454                Self::mix_hash(hash, center.get_x().to_bits() as u64);
455                Self::mix_hash(hash, center.get_y().to_bits() as u64);
456                Self::mix_hash(hash, radius.to_bits() as u64);
457                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
458            }
459            DrawCommand::Triangle { p0, p1, p2, color } => {
460                Self::mix_hash(hash, 9);
461                Self::mix_hash(hash, p0.get_x().to_bits() as u64);
462                Self::mix_hash(hash, p1.get_y().to_bits() as u64);
463                Self::mix_hash(hash, p2.get_x().to_bits() as u64);
464                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
465            }
466            DrawCommand::SpriteRegion {
467                rect,
468                src_rect,
469                tint,
470                ..
471            } => {
472                Self::mix_hash(hash, 10);
473                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
474                Self::mix_hash(hash, src_rect.get_x().to_bits() as u64);
475                Self::mix_hash(hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
476            }
477            DrawCommand::PushClip(r) => {
478                Self::mix_hash(hash, 11);
479                Self::mix_hash(hash, r.get_x().to_bits() as u64);
480                Self::mix_hash(hash, r.get_y().to_bits() as u64);
481            }
482            DrawCommand::PushRoundedClip { rect, radius } => {
483                Self::mix_hash(hash, 14);
484                Self::mix_hash(hash, rect.get_x().to_bits() as u64);
485                Self::mix_hash(hash, rect.get_y().to_bits() as u64);
486                Self::mix_hash(hash, radius.max_radius().to_bits() as u64);
487            }
488            DrawCommand::PopClip => {
489                Self::mix_hash(hash, 12);
490            }
491        }
492    }
493
494    /// Folds a byte slice into an FNV-1a accumulator 8 bytes at a time for fast base-layer digesting.
495    ///
496    /// # Arguments
497    ///
498    /// - `&mut u64` - Running hash accumulator.
499    /// - `&[u8]` - UTF-8 text byte slice.
500    #[inline]
501    fn fold_bytes_wordwise(hash: &mut u64, bytes: &[u8]) {
502        Self::mix_hash(hash, bytes.len() as u64);
503        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
504        for chunk in chunks.iter() {
505            Self::mix_hash(hash, u64::from_ne_bytes(*chunk));
506        }
507        if !rem.is_empty() {
508            let mut tail: u64 = 0;
509            for (idx, &b) in rem.iter().enumerate() {
510                tail |= (b as u64) << (idx * 8);
511            }
512            Self::mix_hash(hash, tail);
513        }
514    }
515
516    /// Folds a single `DrawCommand` with full visual fidelity into a running base-layer or canvas digest.
517    ///
518    /// # Arguments
519    ///
520    /// - `&mut u64` - Running FNV-1a accumulator.
521    /// - `&DrawCommand` - Command to fold.
522    #[inline]
523    pub(crate) fn fold_command_full(hash: &mut u64, cmd: &DrawCommand) {
524        match cmd {
525            DrawCommand::Clear(c) => {
526                Self::mix_hash(hash, 1);
527                Self::mix_hash(hash, u32::from_le_bytes(c.to_rgba_bytes()) as u64);
528            }
529            DrawCommand::FillRoundedRect {
530                rect,
531                color,
532                radius,
533                border,
534            } => {
535                Self::mix_hash(hash, 2);
536                Self::mix_hash(
537                    hash,
538                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
539                );
540                Self::mix_hash(
541                    hash,
542                    ((rect.get_width().to_bits() as u64) << 32)
543                        | (rect.get_height().to_bits() as u64),
544                );
545                Self::mix_hash(
546                    hash,
547                    ((u32::from_le_bytes(color.to_rgba_bytes()) as u64) << 32)
548                        | (u32::from_le_bytes(border.get_color().to_rgba_bytes()) as u64),
549                );
550                Self::mix_hash(
551                    hash,
552                    ((radius.get_top_left().to_bits() as u64) << 32)
553                        | (radius.get_top_right().to_bits() as u64),
554                );
555                Self::mix_hash(
556                    hash,
557                    ((radius.get_bottom_right().to_bits() as u64) << 32)
558                        | (radius.get_bottom_left().to_bits() as u64),
559                );
560                Self::mix_hash(hash, border.get_width().to_bits() as u64);
561            }
562            DrawCommand::LinearGradientRect {
563                rect,
564                gradient,
565                radius,
566            } => {
567                Self::mix_hash(hash, 3);
568                Self::mix_hash(
569                    hash,
570                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
571                );
572                Self::mix_hash(
573                    hash,
574                    ((rect.get_width().to_bits() as u64) << 32)
575                        | (rect.get_height().to_bits() as u64),
576                );
577                Self::mix_hash(
578                    hash,
579                    ((u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64) << 32)
580                        | (u32::from_le_bytes(gradient.get_end_color().to_rgba_bytes()) as u64),
581                );
582                Self::mix_hash(
583                    hash,
584                    ((gradient.get_angle_deg().to_bits() as u64) << 32)
585                        | (radius.max_radius().to_bits() as u64),
586                );
587            }
588            DrawCommand::BoxShadow {
589                rect,
590                radius,
591                shadow,
592            } => {
593                Self::mix_hash(hash, 4);
594                Self::mix_hash(
595                    hash,
596                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
597                );
598                Self::mix_hash(
599                    hash,
600                    ((rect.get_width().to_bits() as u64) << 32)
601                        | (rect.get_height().to_bits() as u64),
602                );
603                Self::mix_hash(
604                    hash,
605                    ((shadow.get_offset_x().to_bits() as u64) << 32)
606                        | (shadow.get_offset_y().to_bits() as u64),
607                );
608                Self::mix_hash(
609                    hash,
610                    ((shadow.get_blur_radius().to_bits() as u64) << 32)
611                        | (shadow.get_spread_radius().to_bits() as u64),
612                );
613                Self::mix_hash(
614                    hash,
615                    ((radius.max_radius().to_bits() as u64) << 32)
616                        | (u32::from_le_bytes(shadow.get_color().to_rgba_bytes()) as u64),
617                );
618            }
619            DrawCommand::BackdropBlur {
620                rect,
621                radius,
622                blur_radius,
623            } => {
624                Self::mix_hash(hash, 15);
625                Self::mix_hash(
626                    hash,
627                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
628                );
629                Self::mix_hash(
630                    hash,
631                    ((rect.get_width().to_bits() as u64) << 32)
632                        | (rect.get_height().to_bits() as u64),
633                );
634                Self::mix_hash(
635                    hash,
636                    ((radius.max_radius().to_bits() as u64) << 32) | (blur_radius.to_bits() as u64),
637                );
638            }
639            DrawCommand::TextRun { rect, text, style } => {
640                Self::mix_hash(hash, 5);
641                Self::mix_hash(
642                    hash,
643                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
644                );
645                Self::mix_hash(
646                    hash,
647                    ((rect.get_width().to_bits() as u64) << 32)
648                        | (rect.get_height().to_bits() as u64),
649                );
650                let style_flags: u64 = (style.get_family() as u64)
651                    | ((style.get_weight() as u64) << 8)
652                    | ((style.get_align() as u64) << 16)
653                    | (u64::from(style.get_italic()) << 24)
654                    | ((u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64) << 32);
655                Self::mix_hash(hash, style_flags);
656                Self::mix_hash(hash, style.get_font_size().to_bits() as u64);
657                Self::fold_bytes_wordwise(hash, text.as_bytes());
658            }
659            DrawCommand::TextCaret {
660                text_rect,
661                content_rect,
662                text,
663                style,
664                caret_height,
665                color,
666                multiline,
667            } => {
668                Self::mix_hash(hash, 13);
669                Self::mix_hash(
670                    hash,
671                    ((text_rect.get_x().to_bits() as u64) << 32)
672                        | (text_rect.get_y().to_bits() as u64),
673                );
674                Self::mix_hash(
675                    hash,
676                    ((content_rect.get_width().to_bits() as u64) << 32)
677                        | (caret_height.to_bits() as u64),
678                );
679                Self::mix_hash(
680                    hash,
681                    ((style.get_font_size().to_bits() as u64) << 32)
682                        | (u32::from_le_bytes(color.to_rgba_bytes()) as u64)
683                            ^ u64::from(*multiline),
684                );
685                Self::fold_bytes_wordwise(hash, text.as_bytes());
686            }
687            DrawCommand::Image {
688                rect,
689                buffer,
690                radius,
691            } => {
692                Self::mix_hash(hash, 6);
693                Self::mix_hash(
694                    hash,
695                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
696                );
697                Self::mix_hash(
698                    hash,
699                    ((rect.get_width().to_bits() as u64) << 32)
700                        | (rect.get_height().to_bits() as u64),
701                );
702                Self::mix_hash(
703                    hash,
704                    ((buffer.get_width() as u64) << 32) | (buffer.get_height() as u64),
705                );
706                Self::mix_hash(hash, buffer.get_pixels().as_ptr() as usize as u64);
707                Self::mix_hash(hash, radius.max_radius().to_bits() as u64);
708            }
709            DrawCommand::SharedImage {
710                rect,
711                width,
712                height,
713                pixels,
714                radius,
715            } => {
716                Self::mix_hash(hash, 6);
717                Self::mix_hash(
718                    hash,
719                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
720                );
721                Self::mix_hash(
722                    hash,
723                    ((rect.get_width().to_bits() as u64) << 32)
724                        | (rect.get_height().to_bits() as u64),
725                );
726                Self::mix_hash(hash, ((*width as u64) << 32) | (*height as u64));
727                Self::mix_hash(hash, pixels.as_ptr() as usize as u64);
728                Self::mix_hash(hash, radius.max_radius().to_bits() as u64);
729            }
730            DrawCommand::Line {
731                from,
732                to,
733                color,
734                width,
735            } => {
736                Self::mix_hash(hash, 7);
737                Self::mix_hash(
738                    hash,
739                    ((from.get_x().to_bits() as u64) << 32) | (from.get_y().to_bits() as u64),
740                );
741                Self::mix_hash(
742                    hash,
743                    ((to.get_x().to_bits() as u64) << 32) | (to.get_y().to_bits() as u64),
744                );
745                Self::mix_hash(
746                    hash,
747                    ((u32::from_le_bytes(color.to_rgba_bytes()) as u64) << 32)
748                        | (width.to_bits() as u64),
749                );
750            }
751            DrawCommand::Circle {
752                center,
753                radius,
754                color,
755            } => {
756                Self::mix_hash(hash, 8);
757                Self::mix_hash(
758                    hash,
759                    ((center.get_x().to_bits() as u64) << 32) | (center.get_y().to_bits() as u64),
760                );
761                Self::mix_hash(
762                    hash,
763                    ((radius.to_bits() as u64) << 32)
764                        | (u32::from_le_bytes(color.to_rgba_bytes()) as u64),
765                );
766            }
767            DrawCommand::Triangle { p0, p1, p2, color } => {
768                Self::mix_hash(hash, 9);
769                Self::mix_hash(
770                    hash,
771                    ((p0.get_x().to_bits() as u64) << 32) | (p0.get_y().to_bits() as u64),
772                );
773                Self::mix_hash(
774                    hash,
775                    ((p1.get_x().to_bits() as u64) << 32) | (p1.get_y().to_bits() as u64),
776                );
777                Self::mix_hash(
778                    hash,
779                    ((p2.get_x().to_bits() as u64) << 32) | (p2.get_y().to_bits() as u64),
780                );
781                Self::mix_hash(hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
782            }
783            DrawCommand::SpriteRegion {
784                rect,
785                buffer,
786                src_rect,
787                tint,
788            } => {
789                Self::mix_hash(hash, 10);
790                Self::mix_hash(
791                    hash,
792                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
793                );
794                Self::mix_hash(
795                    hash,
796                    ((rect.get_width().to_bits() as u64) << 32)
797                        | (rect.get_height().to_bits() as u64),
798                );
799                Self::mix_hash(hash, buffer.get_pixels().as_ptr() as usize as u64);
800                Self::mix_hash(
801                    hash,
802                    ((src_rect.get_x().to_bits() as u64) << 32)
803                        | (src_rect.get_y().to_bits() as u64),
804                );
805                Self::mix_hash(hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
806            }
807            DrawCommand::PushClip(r) => {
808                Self::mix_hash(hash, 11);
809                Self::mix_hash(
810                    hash,
811                    ((r.get_x().to_bits() as u64) << 32) | (r.get_y().to_bits() as u64),
812                );
813                Self::mix_hash(
814                    hash,
815                    ((r.get_width().to_bits() as u64) << 32) | (r.get_height().to_bits() as u64),
816                );
817            }
818            DrawCommand::PushRoundedClip { rect, radius } => {
819                Self::mix_hash(hash, 14);
820                Self::mix_hash(
821                    hash,
822                    ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64),
823                );
824                Self::mix_hash(
825                    hash,
826                    ((rect.get_width().to_bits() as u64) << 32)
827                        | (rect.get_height().to_bits() as u64),
828                );
829                Self::mix_hash(
830                    hash,
831                    ((radius.get_top_left().to_bits() as u64) << 32)
832                        | (radius.get_top_right().to_bits() as u64),
833                );
834                Self::mix_hash(
835                    hash,
836                    ((radius.get_bottom_right().to_bits() as u64) << 32)
837                        | (radius.get_bottom_left().to_bits() as u64),
838                );
839            }
840            DrawCommand::PopClip => {
841                Self::mix_hash(hash, 12);
842            }
843        }
844    }
845
846    /// Returns the O(1) incrementally maintained 64-bit FNV-1a digest over the display list.
847    ///
848    /// # Arguments
849    ///
850    /// - `&Self` - Display list reference.
851    ///
852    /// # Returns
853    ///
854    /// - `u64` - Deterministic command-stream digest.
855    #[inline]
856    #[must_use]
857    pub fn fast_hash(&self) -> u64 {
858        let Self {
859            commands, arena, ..
860        } = self;
861        let mut hash: u64 = arena.running_fast_hash;
862        Self::mix_hash(&mut hash, commands.len() as u64);
863        hash
864    }
865
866    /// Returns an O(1) monotonic base-layer cache token for lossless portal backdrop reuse without re-hashing command bytes.
867    ///
868    /// # Arguments
869    ///
870    /// - `&Self` - Display list reference.
871    ///
872    /// # Returns
873    ///
874    /// - `u64` - Non-zero O(1) base-layer version or streaming digest.
875    #[inline]
876    #[must_use]
877    pub fn base_layer_hash(&self) -> u64 {
878        let Self {
879            commands, arena, ..
880        } = self;
881        if arena.base_layer_finalized {
882            return arena.base_layer_version.max(1);
883        }
884        let mut hash: u64 = arena.cur_base_digest;
885        Self::mix_hash(&mut hash, commands.len() as u64);
886        if hash == 0 { 1 } else { hash }
887    }
888}
889
890/// Telemetry and invalidation helpers for `PaintFragmentCache`.
891impl PaintFragmentCache {
892    /// Clears cached whole-list signature, canvas stability records, and all retained subtree fragments.
893    ///
894    /// # Arguments
895    ///
896    /// - `&Self` - Mutable fragment cache reference.
897    pub fn clear(&mut self) {
898        let Self {
899            has_last_scene,
900            last_has_canvas,
901            slots,
902            cmd_slab,
903            text_slab,
904            canvas_stability,
905            ..
906        } = self;
907        *has_last_scene = false;
908        *last_has_canvas = false;
909        slots.fill(RetainedPaintFragment::default());
910        cmd_slab.clear();
911        text_slab.clear();
912        for entry in canvas_stability.iter_mut() {
913            *entry = CanvasStabilityEntry::default();
914        }
915    }
916
917    /// Returns cumulative retention telemetry `(whole_list_hits, fragment_hits, fragment_misses, fragment_evictions)`.
918    ///
919    /// # Arguments
920    ///
921    /// - `&Self` - Fragment cache reference.
922    ///
923    /// # Returns
924    ///
925    /// - `(u64, u64, u64, u64)` - Tuple of whole-list hits, fragment hits, misses, and evictions.
926    #[must_use]
927    pub fn stats(&self) -> (u64, u64, u64, u64) {
928        (
929            self.get_whole_list_hits(),
930            self.get_fragment_hits(),
931            self.get_fragment_misses(),
932            self.get_fragment_evictions(),
933        )
934    }
935
936    /// Ensures the bounded direct-mapped slot table and flat command/text slabs are pre-allocated once for zero steady-state allocations.
937    ///
938    /// # Arguments
939    ///
940    /// - `&Self` - Mutable fragment cache reference.
941    #[inline]
942    fn ensure_slots(&mut self) {
943        let Self {
944            slots,
945            cmd_slab,
946            text_slab,
947            ..
948        } = self;
949        if slots.len() != PAINT_FRAGMENT_CACHE_SLOTS {
950            slots.resize(PAINT_FRAGMENT_CACHE_SLOTS, RetainedPaintFragment::default());
951        }
952        if cmd_slab.capacity() < PAINT_FRAGMENT_CMD_SLAB_CAP {
953            cmd_slab.reserve_exact(PAINT_FRAGMENT_CMD_SLAB_CAP - cmd_slab.len());
954        }
955        if text_slab.capacity() < PAINT_FRAGMENT_TEXT_SLAB_CAP {
956            text_slab.reserve_exact(PAINT_FRAGMENT_TEXT_SLAB_CAP - text_slab.len());
957        }
958    }
959
960    /// Converts one `DrawCommand` into a slab-backed `CachedDrawCommand`, writing any text bytes into `text_dst` at `*text_cursor`.
961    ///
962    /// # Arguments
963    ///
964    /// - `&DrawCommand` - Source display-list draw command.
965    /// - `&mut [u8]` - Destination UTF-8 byte buffer slice (either in-place slot or freshly extended tail).
966    /// - `&mut usize` - Running write cursor within `text_dst`.
967    /// - `usize` - Absolute base byte offset of `text_dst` inside `text_slab`.
968    ///
969    /// # Returns
970    ///
971    /// - `CachedDrawCommand` - Zero-String slab-backed draw command.
972    #[inline]
973    fn encode_cached_command(
974        cmd: &DrawCommand,
975        text_dst: &mut [u8],
976        text_cursor: &mut usize,
977        text_base: usize,
978    ) -> CachedDrawCommand {
979        match cmd {
980            DrawCommand::Clear(c) => CachedDrawCommand::Clear(*c),
981            DrawCommand::FillRoundedRect {
982                rect,
983                color,
984                radius,
985                border,
986            } => CachedDrawCommand::FillRoundedRect {
987                rect: *rect,
988                color: *color,
989                radius: *radius,
990                border: *border,
991            },
992            DrawCommand::LinearGradientRect {
993                rect,
994                gradient,
995                radius,
996            } => CachedDrawCommand::LinearGradientRect {
997                rect: *rect,
998                gradient: *gradient,
999                radius: *radius,
1000            },
1001            DrawCommand::BoxShadow {
1002                rect,
1003                radius,
1004                shadow,
1005            } => CachedDrawCommand::BoxShadow {
1006                rect: *rect,
1007                radius: *radius,
1008                shadow: *shadow,
1009            },
1010            DrawCommand::BackdropBlur {
1011                rect,
1012                radius,
1013                blur_radius,
1014            } => CachedDrawCommand::BackdropBlur {
1015                rect: *rect,
1016                radius: *radius,
1017                blur_radius: *blur_radius,
1018            },
1019            DrawCommand::TextRun { rect, text, style } => {
1020                let bytes: &[u8] = text.as_bytes();
1021                let start_rel: usize = *text_cursor;
1022                let end_rel: usize = start_rel.saturating_add(bytes.len());
1023                text_dst[start_rel..end_rel].copy_from_slice(bytes);
1024                *text_cursor = end_rel;
1025                CachedDrawCommand::TextRun {
1026                    rect: *rect,
1027                    text_start: (text_base.saturating_add(start_rel)) as u32,
1028                    text_len: bytes.len() as u32,
1029                    style: *style,
1030                }
1031            }
1032            DrawCommand::TextCaret {
1033                text_rect,
1034                content_rect,
1035                text,
1036                style,
1037                caret_height,
1038                color,
1039                multiline,
1040            } => {
1041                let bytes: &[u8] = text.as_bytes();
1042                let start_rel: usize = *text_cursor;
1043                let end_rel: usize = start_rel.saturating_add(bytes.len());
1044                text_dst[start_rel..end_rel].copy_from_slice(bytes);
1045                *text_cursor = end_rel;
1046                CachedDrawCommand::TextCaret {
1047                    text_rect: *text_rect,
1048                    content_rect: *content_rect,
1049                    text_start: (text_base.saturating_add(start_rel)) as u32,
1050                    text_len: bytes.len() as u32,
1051                    style: *style,
1052                    caret_height: *caret_height,
1053                    color: *color,
1054                    multiline: *multiline,
1055                }
1056            }
1057            DrawCommand::Image {
1058                rect,
1059                buffer,
1060                radius,
1061            } => CachedDrawCommand::Image {
1062                rect: *rect,
1063                buffer: buffer.clone(),
1064                radius: *radius,
1065            },
1066            DrawCommand::SharedImage {
1067                rect,
1068                width,
1069                height,
1070                pixels,
1071                radius,
1072            } => CachedDrawCommand::SharedImage {
1073                rect: *rect,
1074                width: *width,
1075                height: *height,
1076                pixels: Arc::clone(pixels),
1077                radius: *radius,
1078            },
1079            DrawCommand::Line {
1080                from,
1081                to,
1082                color,
1083                width,
1084            } => CachedDrawCommand::Line {
1085                from: *from,
1086                to: *to,
1087                color: *color,
1088                width: *width,
1089            },
1090            DrawCommand::Circle {
1091                center,
1092                radius,
1093                color,
1094            } => CachedDrawCommand::Circle {
1095                center: *center,
1096                radius: *radius,
1097                color: *color,
1098            },
1099            DrawCommand::Triangle { p0, p1, p2, color } => CachedDrawCommand::Triangle {
1100                p0: *p0,
1101                p1: *p1,
1102                p2: *p2,
1103                color: *color,
1104            },
1105            DrawCommand::SpriteRegion {
1106                rect,
1107                buffer,
1108                src_rect,
1109                tint,
1110            } => CachedDrawCommand::SpriteRegion {
1111                rect: *rect,
1112                buffer: buffer.clone(),
1113                src_rect: *src_rect,
1114                tint: *tint,
1115            },
1116            DrawCommand::PushClip(rect) => CachedDrawCommand::PushClip(*rect),
1117            DrawCommand::PushRoundedClip { rect, radius } => CachedDrawCommand::PushRoundedClip {
1118                rect: *rect,
1119                radius: *radius,
1120            },
1121            DrawCommand::PopClip => CachedDrawCommand::PopClip,
1122        }
1123    }
1124
1125    /// Captures `cmd_slice` into `slot_idx` inside the pre-allocated flat command and text slabs with zero heap allocations.
1126    ///
1127    /// # Arguments
1128    ///
1129    /// - `&Self` - Mutable fragment cache reference.
1130    /// - `usize` - Direct-mapped slot index in `0..PAINT_FRAGMENT_CACHE_SLOTS`.
1131    /// - `(NodeId, u32, u32, Point, u64, u64)` - Metadata `(node_id, phys_scale_milli, opacity_bits, offset_phys, geom_hash, style_text_hash)`.
1132    /// - `&[DrawCommand]` - Commands emitted for this subtree.
1133    fn capture_fragment(
1134        &mut self,
1135        slot_idx: usize,
1136        meta: (NodeId, u32, u32, Point, u64, u64),
1137        cmd_slice: &[DrawCommand],
1138    ) {
1139        let (node_id, phys_scale_milli, opacity_bits, offset_phys, geom_hash, style_text_hash): (
1140            NodeId,
1141            u32,
1142            u32,
1143            Point,
1144            u64,
1145            u64,
1146        ) = meta;
1147        let Self {
1148            slots,
1149            cmd_slab,
1150            text_slab,
1151            fragment_misses,
1152            fragment_evictions,
1153            ..
1154        } = self;
1155        if slot_idx >= slots.len() {
1156            return;
1157        }
1158        *fragment_misses = fragment_misses.wrapping_add(1);
1159        let need_cmds: usize = cmd_slice.len();
1160        let mut need_text: usize = 0;
1161        for cmd in cmd_slice.iter() {
1162            match cmd {
1163                DrawCommand::TextRun { text, .. } | DrawCommand::TextCaret { text, .. } => {
1164                    need_text = need_text.saturating_add(text.len());
1165                }
1166                _ => {}
1167            }
1168        }
1169        if need_cmds > PAINT_FRAGMENT_CMD_SLAB_CAP || need_text > PAINT_FRAGMENT_TEXT_SLAB_CAP {
1170            return;
1171        }
1172        let existing: RetainedPaintFragment = slots[slot_idx];
1173        if existing.occupied && existing.node_id != node_id {
1174            *fragment_evictions = fragment_evictions.wrapping_add(1);
1175        }
1176        if existing.occupied
1177            && need_cmds <= (existing.cmd_cap as usize)
1178            && need_text <= (existing.text_cap as usize)
1179        {
1180            let cmd_base: usize = existing.cmd_start as usize;
1181            let text_base: usize = existing.text_start as usize;
1182            let text_end: usize = text_base.saturating_add(need_text);
1183            let mut text_cursor: usize = 0;
1184            let text_dst: &mut [u8] = &mut text_slab[text_base..text_end];
1185            for (i, cmd) in cmd_slice.iter().enumerate() {
1186                cmd_slab[cmd_base + i] =
1187                    Self::encode_cached_command(cmd, text_dst, &mut text_cursor, text_base);
1188            }
1189            slots[slot_idx] = RetainedPaintFragment {
1190                occupied: true,
1191                node_id,
1192                phys_scale_milli,
1193                opacity_bits,
1194                offset_phys,
1195                geom_hash,
1196                style_text_hash,
1197                cmd_start: existing.cmd_start,
1198                cmd_len: need_cmds as u32,
1199                cmd_cap: existing.cmd_cap,
1200                text_start: existing.text_start,
1201                text_cap: existing.text_cap,
1202            };
1203            return;
1204        }
1205        if cmd_slab.len().saturating_add(need_cmds) > PAINT_FRAGMENT_CMD_SLAB_CAP
1206            || text_slab.len().saturating_add(need_text) > PAINT_FRAGMENT_TEXT_SLAB_CAP
1207        {
1208            let mut evicted: u64 = 0;
1209            for s in slots.iter_mut() {
1210                if s.occupied {
1211                    evicted = evicted.saturating_add(1);
1212                    *s = RetainedPaintFragment::default();
1213                }
1214            }
1215            *fragment_evictions = fragment_evictions.wrapping_add(evicted);
1216            cmd_slab.clear();
1217            text_slab.clear();
1218        }
1219        let cmd_start: usize = cmd_slab.len();
1220        let text_base: usize = text_slab.len();
1221        let text_end: usize = text_base.saturating_add(need_text);
1222        text_slab.resize(text_end, 0);
1223        let mut text_cursor: usize = 0;
1224        let text_dst: &mut [u8] = &mut text_slab[text_base..text_end];
1225        for cmd in cmd_slice.iter() {
1226            cmd_slab.push(Self::encode_cached_command(
1227                cmd,
1228                text_dst,
1229                &mut text_cursor,
1230                text_base,
1231            ));
1232        }
1233        slots[slot_idx] = RetainedPaintFragment {
1234            occupied: true,
1235            node_id,
1236            phys_scale_milli,
1237            opacity_bits,
1238            offset_phys,
1239            geom_hash,
1240            style_text_hash,
1241            cmd_start: cmd_start as u32,
1242            cmd_len: need_cmds as u32,
1243            cmd_cap: need_cmds as u32,
1244            text_start: text_base as u32,
1245            text_cap: need_text as u32,
1246        };
1247    }
1248
1249    /// Records the commands emitted by one `NodeKind::Canvas` and returns `true` only if the canvas is dynamic or unverified.
1250    ///
1251    /// # Arguments
1252    ///
1253    /// - `&Self` - Mutable fragment cache reference.
1254    /// - `NodeId` - Canvas node handle.
1255    /// - `u32` - Quantized physical scale (`(scale * 1000.0).round() as u32`).
1256    /// - `Rect` - Canvas logical bounds.
1257    /// - `u64` - Active `SceneTree::revision`.
1258    /// - `&[DrawCommand]` - Commands emitted by the canvas callback on this frame.
1259    ///
1260    /// # Returns
1261    ///
1262    /// - `bool` - `true` when the canvas must disable whole-list retention; `false` when proven static pure-vector.
1263    #[inline]
1264    fn record_canvas_output(
1265        &mut self,
1266        node_id: NodeId,
1267        phys_scale_milli: u32,
1268        bounds: Rect,
1269        tree_revision: u64,
1270        cmds: &[DrawCommand],
1271    ) -> bool {
1272        let slot_idx: usize = (node_id.get_index() as usize) & (CANVAS_STABILITY_SLOTS - 1);
1273        let Self {
1274            canvas_stability, ..
1275        } = self;
1276        let slot: &mut CanvasStabilityEntry = &mut canvas_stability[slot_idx];
1277        let mut has_raster: bool = false;
1278        let mut cmd_hash: u64 = FNV1A_OFFSET_BASIS;
1279        for cmd in cmds.iter() {
1280            if matches!(
1281                cmd,
1282                DrawCommand::Image { .. }
1283                    | DrawCommand::SharedImage { .. }
1284                    | DrawCommand::SpriteRegion { .. }
1285            ) {
1286                has_raster = true;
1287                break;
1288            }
1289            DisplayList::fold_command_full(&mut cmd_hash, cmd);
1290        }
1291        if has_raster {
1292            *slot = CanvasStabilityEntry {
1293                node_id,
1294                phys_scale_milli,
1295                bounds,
1296                tree_revision,
1297                cmd_hash: 0,
1298                stable_hits: 0,
1299                proven_dynamic: true,
1300                occupied: true,
1301            };
1302            return true;
1303        }
1304        if slot.occupied
1305            && slot.node_id == node_id
1306            && slot.phys_scale_milli == phys_scale_milli
1307            && slot.bounds == bounds
1308        {
1309            if slot.proven_dynamic {
1310                return true;
1311            }
1312            if slot.cmd_hash == cmd_hash {
1313                slot.tree_revision = tree_revision;
1314                slot.stable_hits = slot.stable_hits.saturating_add(1);
1315                return slot.stable_hits < 2;
1316            }
1317            if slot.tree_revision == tree_revision {
1318                slot.proven_dynamic = true;
1319                return true;
1320            }
1321            slot.tree_revision = tree_revision;
1322            slot.cmd_hash = cmd_hash;
1323            slot.stable_hits = 1;
1324            return true;
1325        }
1326        *slot = CanvasStabilityEntry {
1327            node_id,
1328            phys_scale_milli,
1329            bounds,
1330            tree_revision,
1331            cmd_hash,
1332            stable_hits: 1,
1333            proven_dynamic: false,
1334            occupied: true,
1335        };
1336        true
1337    }
1338}
1339
1340/// Scene-to-display-list compilation pass.
1341impl PaintPass {
1342    /// Computes a deterministic 64-bit signature of the active text selection state.
1343    ///
1344    /// # Arguments
1345    ///
1346    /// - `&SceneTree` - Retained scene tree.
1347    ///
1348    /// # Returns
1349    ///
1350    /// - `u64` - Selection digest (`0` when no text selection is active).
1351    #[inline]
1352    #[must_use]
1353    fn text_selection_sig(tree: &SceneTree) -> u64 {
1354        let Some(sel) = tree.text_selection() else {
1355            return 0;
1356        };
1357        if sel.is_empty() {
1358            return 0;
1359        }
1360        let anchor_id: NodeId = sel.get_anchor_node();
1361        let focus_id: NodeId = sel.get_focus_node();
1362        let mut h: u64 =
1363            ((anchor_id.get_index() as u64) << 32) | (anchor_id.get_generation() as u64);
1364        h = (h ^ (sel.get_anchor_char() as u64)).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
1365        let focus_bits: u64 =
1366            ((focus_id.get_index() as u64) << 32) | (focus_id.get_generation() as u64);
1367        h = (h ^ focus_bits).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
1368        h = (h ^ (sel.get_focus_char() as u64)).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
1369        if h == 0 { 1 } else { h }
1370    }
1371
1372    /// Folds one `u64` word into a running FxHash accumulator.
1373    ///
1374    /// # Arguments
1375    ///
1376    /// - `&mut u64` - Running hash accumulator.
1377    /// - `u64` - Word to fold.
1378    #[inline(always)]
1379    fn fx_fold(hash: &mut u64, word: u64) {
1380        *hash = (*hash ^ word).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
1381    }
1382
1383    /// Folds a `Rect`'s exact IEEE-754 bit pattern into `hash`.
1384    ///
1385    /// # Arguments
1386    ///
1387    /// - `&mut u64` - Running hash accumulator.
1388    /// - `Rect` - Rectangle to hash.
1389    #[inline(always)]
1390    fn fx_fold_rect(hash: &mut u64, rect: Rect) {
1391        let lo: u64 = ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64);
1392        let hi: u64 =
1393            ((rect.get_width().to_bits() as u64) << 32) | (rect.get_height().to_bits() as u64);
1394        Self::fx_fold(hash, lo);
1395        Self::fx_fold(hash, hi);
1396    }
1397
1398    /// Folds a `PaintStyle`'s visual fields into `hash`.
1399    ///
1400    /// # Arguments
1401    ///
1402    /// - `&mut u64` - Running hash accumulator.
1403    /// - `&PaintStyle` - Paint style reference.
1404    #[inline]
1405    fn fx_fold_paint(hash: &mut u64, paint: &PaintStyle) {
1406        let bg_bits: u64 = paint
1407            .background_color()
1408            .map(|c: Color| u32::from_le_bytes(c.to_rgba_bytes()) as u64 | (1_u64 << 32))
1409            .unwrap_or(0);
1410        Self::fx_fold(hash, bg_bits);
1411        if let Some(grad) = paint.background_gradient() {
1412            let g0: u64 = u32::from_le_bytes(grad.get_start_color().to_rgba_bytes()) as u64;
1413            let g1: u64 = u32::from_le_bytes(grad.get_end_color().to_rgba_bytes()) as u64;
1414            Self::fx_fold(hash, (g0 << 32) | g1);
1415            Self::fx_fold(hash, grad.get_angle_deg().to_bits() as u64 | (1_u64 << 33));
1416        }
1417        let border: Border = paint.get_border();
1418        let b_word: u64 = ((border.get_width().to_bits() as u64) << 32)
1419            | (u32::from_le_bytes(border.get_color().to_rgba_bytes()) as u64);
1420        Self::fx_fold(hash, b_word);
1421        let r: CornerRadius = paint.get_radius();
1422        let r0: u64 =
1423            ((r.get_top_left().to_bits() as u64) << 32) | (r.get_top_right().to_bits() as u64);
1424        let r1: u64 = ((r.get_bottom_right().to_bits() as u64) << 32)
1425            | (r.get_bottom_left().to_bits() as u64);
1426        Self::fx_fold(hash, r0);
1427        Self::fx_fold(hash, r1);
1428        Self::fx_fold(hash, paint.get_opacity().to_bits() as u64);
1429        if let Some(sh) = paint.box_shadow() {
1430            let s0: u64 =
1431                ((sh.get_offset_x().to_bits() as u64) << 32) | (sh.get_offset_y().to_bits() as u64);
1432            let s1: u64 = ((sh.get_blur_radius().to_bits() as u64) << 32)
1433                | (sh.get_spread_radius().to_bits() as u64);
1434            Self::fx_fold(hash, s0);
1435            Self::fx_fold(hash, s1);
1436            Self::fx_fold(
1437                hash,
1438                u32::from_le_bytes(sh.get_color().to_rgba_bytes()) as u64 | (1_u64 << 34),
1439            );
1440        }
1441    }
1442
1443    /// Folds a `TextStyle` and UTF-8 string bytes into `hash`.
1444    ///
1445    /// # Arguments
1446    ///
1447    /// - `&mut u64` - Running hash accumulator.
1448    /// - `&TextStyle` - Typography style reference.
1449    /// - `&str` - Text content slice.
1450    #[inline]
1451    fn fx_fold_text(hash: &mut u64, text_style: &TextStyle, text: &str) {
1452        let m0: u64 = ((text_style.get_font_size().to_bits() as u64) << 32)
1453            | (text_style.get_line_height().to_bits() as u64);
1454        let m1: u64 = ((text_style.get_letter_spacing().to_bits() as u64) << 32)
1455            | (u32::from_le_bytes(text_style.get_color().to_rgba_bytes()) as u64);
1456        let flags: u64 = (text_style.get_family() as u64)
1457            | ((text_style.get_weight() as u64) << 8)
1458            | ((text_style.get_align() as u64) << 16)
1459            | ((text_style.get_overflow() as u64) << 24)
1460            | (u64::from(text_style.get_italic()) << 32);
1461        Self::fx_fold(hash, m0);
1462        Self::fx_fold(hash, m1);
1463        Self::fx_fold(hash, flags);
1464        let bytes: &[u8] = text.as_bytes();
1465        Self::fx_fold(hash, bytes.len() as u64);
1466        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
1467        for chunk in chunks.iter() {
1468            Self::fx_fold(hash, u64::from_ne_bytes(*chunk));
1469        }
1470        if !rem.is_empty() {
1471            let mut tail: u64 = 0;
1472            for (idx, &b) in rem.iter().enumerate() {
1473                tail |= (b as u64) << (idx * 8);
1474            }
1475            Self::fx_fold(hash, tail);
1476        }
1477    }
1478
1479    /// Quantizes a DPI scale factor into integer milli-units (`1.25 -> 1250`, `2.625 -> 2625`, `3.0 -> 3000`).
1480    ///
1481    /// # Arguments
1482    ///
1483    /// - `f32` - Active DPI scale factor.
1484    ///
1485    /// # Returns
1486    ///
1487    /// - `u32` - Quantized physical scale key in milli-units.
1488    #[inline(always)]
1489    #[must_use]
1490    fn quantize_scale_milli(scale: f32) -> u32 {
1491        (scale.max(0.5) * 1000.0).round() as u32
1492    }
1493
1494    /// Recursively fingerprints children of a cacheable container up to bounded depth and node count.
1495    ///
1496    /// # Arguments
1497    ///
1498    /// - `&SceneTree` - Retained scene tree.
1499    /// - `NodeId` - Parent container node handle whose children are fingerprinted.
1500    /// - `usize` - Current nesting depth (`1..=PAINT_FRAGMENT_MAX_DEPTH`).
1501    /// - `Option<(Point, Rect, f32, f32)>` - Optional `(offset_phys, cull_rect, scale, inv_scale)` when ancestor overflow is unclipped.
1502    /// - `(Option<NodeId>, bool)` - Active `(hover_target, has_text_selection)` state.
1503    /// - `&mut (usize, u64, u64)` - Mutable `(nodes_visited, geom_hash, style_text_hash)` accumulator.
1504    ///
1505    /// # Returns
1506    ///
1507    /// - `bool` - `true` when all descendants are pure, clean, and eligible for retained fragment caching.
1508    #[inline]
1509    #[must_use]
1510    fn fingerprint_subtree_children(
1511        tree: &SceneTree,
1512        parent: NodeId,
1513        depth: usize,
1514        unclipped_cull: Option<(Point, Rect, f32, f32)>,
1515        focus_pair: (Option<NodeId>, bool),
1516        acc: &mut (usize, u64, u64),
1517    ) -> bool {
1518        let child_count: usize = tree.child_count(parent);
1519        if depth > PAINT_FRAGMENT_MAX_DEPTH || child_count > PAINT_FRAGMENT_MAX_CHILDREN {
1520            return false;
1521        }
1522        let (active_hover_target, has_text_sel): (Option<NodeId>, bool) = focus_pair;
1523        Self::fx_fold(&mut acc.1, child_count as u64);
1524        for cid in tree.children_iter(parent) {
1525            if acc.0 >= PAINT_FRAGMENT_MAX_NODES
1526                || active_hover_target == Some(cid)
1527                || (has_text_sel && tree.text_selection_range_for(cid).is_some())
1528                || tree.backdrop_blur_radius(cid) > 0.0
1529            {
1530                return false;
1531            }
1532            let Some(child) = tree.get_node(cid) else {
1533                return false;
1534            };
1535            acc.0 += 1;
1536            let c_inter: InteractionState = child.get_interaction();
1537            let c_active: bool = c_inter.get_hovered() || c_inter.get_pressed();
1538            if c_active || c_inter.get_focused() {
1539                return false;
1540            }
1541            let c_style: &Style = child.style_ref();
1542            if c_style.layout.get_position() == Position::Fixed {
1543                return false;
1544            }
1545            let c_tag: u64 = match child.get_kind() {
1546                NodeKind::View | NodeKind::Fragment => 1,
1547                NodeKind::Text(text) => {
1548                    Self::fx_fold_text(&mut acc.2, &c_style.text, text.as_str());
1549                    Self::fx_fold_rect(&mut acc.1, child.layout_box.get_content_bounds());
1550                    2
1551                }
1552                NodeKind::Image(buf) => {
1553                    Self::fx_fold(&mut acc.2, tree.node_paint_epoch(cid) as u64);
1554                    Self::fx_fold(
1555                        &mut acc.2,
1556                        ((buf.get_width() as u64) << 32) | (buf.get_height() as u64),
1557                    );
1558                    Self::fx_fold(&mut acc.2, buf.get_pixels().as_ptr() as usize as u64);
1559                    3
1560                }
1561                NodeKind::Canvas(CanvasCaching::RetainedStatic) => {
1562                    Self::fx_fold(&mut acc.2, tree.node_paint_epoch(cid) as u64);
1563                    if let Some(cb) = child.canvas_callback() {
1564                        let cb_addr: u64 = (Rc::as_ptr(&cb) as *const ()) as usize as u64;
1565                        Self::fx_fold(&mut acc.2, cb_addr);
1566                    }
1567                    4
1568                }
1569                NodeKind::Portal
1570                | NodeKind::Canvas(CanvasCaching::DynamicPerFrame)
1571                | NodeKind::Input(_)
1572                | NodeKind::ScrollView => {
1573                    return false;
1574                }
1575            };
1576            let c_id_bits: u64 = ((cid.get_index() as u64) << 32) | (cid.get_generation() as u64);
1577            Self::fx_fold(&mut acc.1, c_id_bits);
1578            let raw_b: Rect = child.layout_box.get_bounds();
1579            Self::fx_fold_rect(&mut acc.1, raw_b);
1580            let ct: Transform2D = c_style.paint.get_transform();
1581            Self::fx_fold(
1582                &mut acc.1,
1583                ((ct.get_translate_x().to_bits() as u64) << 32)
1584                    | (ct.get_translate_y().to_bits() as u64),
1585            );
1586            Self::fx_fold(
1587                &mut acc.1,
1588                ((ct.get_scale_x().to_bits() as u64) << 32) | (ct.get_scale_y().to_bits() as u64),
1589            );
1590            let c_lay_bits: u64 = (c_tag << 40)
1591                | ((c_style.layout.get_display() as u64) << 32)
1592                | ((c_style.layout.get_overflow() as u64) << 24)
1593                | ((c_style.layout.get_z_index() as u32) as u64);
1594            Self::fx_fold(&mut acc.2, c_lay_bits);
1595            Self::fx_fold_paint(&mut acc.2, &c_style.paint);
1596            let mut next_cull_check: Option<(Point, Rect, f32, f32)> = None;
1597            if let Some((off_phys, cull_rect, scale, inv_scale)) = unclipped_cull {
1598                let tx_phys: f32 = (ct.get_translate_x() * scale).round();
1599                let ty_phys: f32 = (ct.get_translate_y() * scale).round();
1600                let tot_x: f32 = off_phys.get_x() + tx_phys;
1601                let tot_y: f32 = off_phys.get_y() + ty_phys;
1602                let rx0: f32 = (raw_b.get_x() * scale).round();
1603                let ry0: f32 = (raw_b.get_y() * scale).round();
1604                let rx1: f32 = (raw_b.right() * scale).round();
1605                let ry1: f32 = (raw_b.bottom() * scale).round();
1606                let sw: f32 = ((rx1 - rx0).max(0.0) * ct.get_scale_x()).round().max(0.0);
1607                let sh: f32 = ((ry1 - ry0).max(0.0) * ct.get_scale_y()).round().max(0.0);
1608                let sdx: f32 = (((rx1 - rx0).max(0.0) - sw) * 0.5).round();
1609                let sdy: f32 = (((ry1 - ry0).max(0.0) - sh) * 0.5).round();
1610                let c_bounds: Rect = Rect::new(
1611                    (rx0 + tot_x + sdx) * inv_scale,
1612                    (ry0 + tot_y + sdy) * inv_scale,
1613                    sw * inv_scale,
1614                    sh * inv_scale,
1615                );
1616                let c_vis: Rect = Self::conservative_self_vis_rect(
1617                    child,
1618                    c_bounds,
1619                    &c_style.paint,
1620                    false,
1621                    (tot_x, tot_y),
1622                    scale,
1623                    inv_scale,
1624                );
1625                let c_in_x: bool =
1626                    c_vis.get_x() >= cull_rect.get_x() && c_vis.right() <= cull_rect.right();
1627                let c_in_y: bool =
1628                    c_vis.get_y() >= cull_rect.get_y() && c_vis.bottom() <= cull_rect.bottom();
1629                if !c_in_x || !c_in_y {
1630                    return false;
1631                }
1632                if c_style.layout.get_overflow() != Overflow::Hidden {
1633                    let c_scroll: Point = child.layout_box.get_scroll_offset();
1634                    let next_off: Point = Point::new(
1635                        tot_x - (c_scroll.get_x() * scale).round(),
1636                        tot_y - (c_scroll.get_y() * scale).round(),
1637                    );
1638                    next_cull_check = Some((next_off, cull_rect, scale, inv_scale));
1639                }
1640            }
1641            if tree.has_children(cid)
1642                && !Self::fingerprint_subtree_children(
1643                    tree,
1644                    cid,
1645                    depth + 1,
1646                    next_cull_check,
1647                    focus_pair,
1648                    acc,
1649                )
1650            {
1651                return false;
1652            }
1653        }
1654        true
1655    }
1656
1657    /// Computes `(geom_hash, style_text_hash)` for an eligible nested container subtree, or `None` if uncacheable.
1658    ///
1659    /// # Arguments
1660    ///
1661    /// - `&SceneTree` - Retained scene tree.
1662    /// - `NodeId` - Candidate container node handle.
1663    /// - `&SceneNode` - Candidate container node reference.
1664    /// - `Option<(Point, Rect, f32, f32)>` - Optional child cull-verification context when container overflow is unclipped.
1665    /// - `(Option<NodeId>, bool)` - Active `(hover_target, has_text_selection)` state.
1666    ///
1667    /// # Returns
1668    ///
1669    /// - `Option<(u64, u64)>` - Tuple `(geom_hash, style_text_hash)` when the subtree is pure and cache-eligible.
1670    #[inline]
1671    #[must_use]
1672    fn fingerprint_subtree(
1673        tree: &SceneTree,
1674        node_id: NodeId,
1675        node: &SceneNode,
1676        unclipped_cull: Option<(Point, Rect, f32, f32)>,
1677        focus_pair: (Option<NodeId>, bool),
1678    ) -> Option<(u64, u64)> {
1679        let child_count: usize = tree.child_count(node_id);
1680        if child_count == 0
1681            || child_count > PAINT_FRAGMENT_MAX_CHILDREN
1682            || tree.backdrop_blur_radius(node_id) > 0.0
1683        {
1684            return None;
1685        }
1686        let style: &Style = node.style_ref();
1687        let transform: Transform2D = style.paint.get_transform();
1688        let scroll: Point = node.layout_box.get_scroll_offset();
1689        let mut geom_h: u64 = child_count as u64;
1690        Self::fx_fold_rect(&mut geom_h, node.layout_box.get_bounds());
1691        Self::fx_fold(
1692            &mut geom_h,
1693            ((transform.get_translate_x().to_bits() as u64) << 32)
1694                | (transform.get_translate_y().to_bits() as u64),
1695        );
1696        Self::fx_fold(
1697            &mut geom_h,
1698            ((transform.get_scale_x().to_bits() as u64) << 32)
1699                | (transform.get_scale_y().to_bits() as u64),
1700        );
1701        Self::fx_fold(
1702            &mut geom_h,
1703            ((scroll.get_x().to_bits() as u64) << 32) | (scroll.get_y().to_bits() as u64),
1704        );
1705        let mut style_h: u64 =
1706            ((node_id.get_index() as u64) << 32) | (node_id.get_generation() as u64);
1707        Self::fx_fold_paint(&mut style_h, &style.paint);
1708        let mut acc: (usize, u64, u64) = (0, geom_h, style_h);
1709        if !Self::fingerprint_subtree_children(
1710            tree,
1711            node_id,
1712            1,
1713            unclipped_cull,
1714            focus_pair,
1715            &mut acc,
1716        ) {
1717            return None;
1718        }
1719        Some((acc.1, acc.2))
1720    }
1721
1722    /// Translates a single physical-pixel-snapped logical coordinate by `d_phys` without cumulative drift across fractional DPRs.
1723    ///
1724    /// # Arguments
1725    ///
1726    /// - `f32` - Cached logical coordinate.
1727    /// - `f32` - Integer physical-pixel displacement delta.
1728    /// - `f32` - Active DPI scale factor.
1729    /// - `f32` - Reciprocal of `scale`.
1730    /// - `bool` - True when `scale` is an exact power-of-two (`1.0`, `2.0`, `4.0`).
1731    ///
1732    /// # Returns
1733    ///
1734    /// - `f32` - Bit-exact translated logical coordinate.
1735    #[inline(always)]
1736    #[must_use]
1737    fn translate_coord(v: f32, d_phys: f32, scale: f32, inv_scale: f32, dyadic: bool) -> f32 {
1738        if d_phys == 0.0 {
1739            return v;
1740        }
1741        if dyadic {
1742            return v + d_phys * inv_scale;
1743        }
1744        ((v * scale).round() + d_phys) * inv_scale
1745    }
1746
1747    /// Translates a cached logical `Rect` origin by `(dx_phys, dy_phys)` preserving exact physical-pixel snapping across all DPRs.
1748    ///
1749    /// # Arguments
1750    ///
1751    /// - `Rect` - Cached logical rectangle.
1752    /// - `f32` - Physical X displacement delta.
1753    /// - `f32` - Physical Y displacement delta.
1754    /// - `f32` - Active DPI scale factor.
1755    /// - `f32` - Reciprocal of `scale`.
1756    /// - `bool` - True when `scale` is dyadic (`1.0`, `2.0`, `4.0`).
1757    ///
1758    /// # Returns
1759    ///
1760    /// - `Rect` - Translated logical rectangle with invariant width and height.
1761    #[inline(always)]
1762    #[must_use]
1763    fn translate_rect(
1764        rect: Rect,
1765        dx_phys: f32,
1766        dy_phys: f32,
1767        scale: f32,
1768        inv_scale: f32,
1769        dyadic: bool,
1770    ) -> Rect {
1771        Rect::new(
1772            Self::translate_coord(rect.get_x(), dx_phys, scale, inv_scale, dyadic),
1773            Self::translate_coord(rect.get_y(), dy_phys, scale, inv_scale, dyadic),
1774            rect.get_width(),
1775            rect.get_height(),
1776        )
1777    }
1778
1779    /// Translates and emits one slab-backed `CachedDrawCommand` into `display_list` using the string pool for zero-alloc fragment reuse.
1780    ///
1781    /// # Arguments
1782    ///
1783    /// - `&CachedDrawCommand` - Cached draw command inside `PaintFragmentCache::cmd_slab`.
1784    /// - `&[u8]` - Backing UTF-8 byte slab (`PaintFragmentCache::text_slab`).
1785    /// - `(f32, f32)` - Physical pixel displacement `(dx_phys, dy_phys)`.
1786    /// - `(f32, f32, bool)` - Active `(scale, inv_scale, is_dyadic_scale)`.
1787    /// - `&mut DisplayList` - Output display list receiving the translated command.
1788    #[inline]
1789    fn push_translated_command(
1790        cmd: &CachedDrawCommand,
1791        text_slab: &[u8],
1792        delta_phys: (f32, f32),
1793        scale_info: (f32, f32, bool),
1794        display_list: &mut DisplayList,
1795    ) {
1796        let (dx_phys, dy_phys): (f32, f32) = delta_phys;
1797        let (scale, inv_scale, dyadic): (f32, f32, bool) = scale_info;
1798        let translated: DrawCommand = match cmd {
1799            CachedDrawCommand::Clear(c) => DrawCommand::Clear(*c),
1800            CachedDrawCommand::FillRoundedRect {
1801                rect,
1802                color,
1803                radius,
1804                border,
1805            } => DrawCommand::FillRoundedRect {
1806                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1807                color: *color,
1808                radius: *radius,
1809                border: *border,
1810            },
1811            CachedDrawCommand::LinearGradientRect {
1812                rect,
1813                gradient,
1814                radius,
1815            } => DrawCommand::LinearGradientRect {
1816                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1817                gradient: *gradient,
1818                radius: *radius,
1819            },
1820            CachedDrawCommand::BoxShadow {
1821                rect,
1822                radius,
1823                shadow,
1824            } => DrawCommand::BoxShadow {
1825                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1826                radius: *radius,
1827                shadow: *shadow,
1828            },
1829            CachedDrawCommand::BackdropBlur {
1830                rect,
1831                radius,
1832                blur_radius,
1833            } => DrawCommand::BackdropBlur {
1834                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1835                radius: *radius,
1836                blur_radius: *blur_radius,
1837            },
1838            CachedDrawCommand::TextRun {
1839                rect,
1840                text_start,
1841                text_len,
1842                style,
1843            } => {
1844                let s: usize = *text_start as usize;
1845                let e: usize = s.saturating_add(*text_len as usize);
1846                let src: &str = text_slab
1847                    .get(s..e)
1848                    .and_then(|b: &[u8]| from_utf8(b).ok())
1849                    .unwrap_or("");
1850                DrawCommand::TextRun {
1851                    rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1852                    text: display_list.alloc_text(src),
1853                    style: *style,
1854                }
1855            }
1856            CachedDrawCommand::TextCaret {
1857                text_rect,
1858                content_rect,
1859                text_start,
1860                text_len,
1861                style,
1862                caret_height,
1863                color,
1864                multiline,
1865            } => {
1866                let s: usize = *text_start as usize;
1867                let e: usize = s.saturating_add(*text_len as usize);
1868                let src: &str = text_slab
1869                    .get(s..e)
1870                    .and_then(|b: &[u8]| from_utf8(b).ok())
1871                    .unwrap_or("");
1872                DrawCommand::TextCaret {
1873                    text_rect: Self::translate_rect(
1874                        *text_rect, dx_phys, dy_phys, scale, inv_scale, dyadic,
1875                    ),
1876                    content_rect: Self::translate_rect(
1877                        *content_rect,
1878                        dx_phys,
1879                        dy_phys,
1880                        scale,
1881                        inv_scale,
1882                        dyadic,
1883                    ),
1884                    text: display_list.alloc_text(src),
1885                    style: *style,
1886                    caret_height: *caret_height,
1887                    color: *color,
1888                    multiline: *multiline,
1889                }
1890            }
1891            CachedDrawCommand::Image {
1892                rect,
1893                buffer,
1894                radius,
1895            } => DrawCommand::Image {
1896                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1897                buffer: buffer.clone(),
1898                radius: *radius,
1899            },
1900            CachedDrawCommand::SharedImage {
1901                rect,
1902                width,
1903                height,
1904                pixels,
1905                radius,
1906            } => DrawCommand::SharedImage {
1907                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1908                width: *width,
1909                height: *height,
1910                pixels: Arc::clone(pixels),
1911                radius: *radius,
1912            },
1913            CachedDrawCommand::Line {
1914                from,
1915                to,
1916                color,
1917                width,
1918            } => DrawCommand::Line {
1919                from: Point::new(
1920                    Self::translate_coord(from.get_x(), dx_phys, scale, inv_scale, dyadic),
1921                    Self::translate_coord(from.get_y(), dy_phys, scale, inv_scale, dyadic),
1922                ),
1923                to: Point::new(
1924                    Self::translate_coord(to.get_x(), dx_phys, scale, inv_scale, dyadic),
1925                    Self::translate_coord(to.get_y(), dy_phys, scale, inv_scale, dyadic),
1926                ),
1927                color: *color,
1928                width: *width,
1929            },
1930            CachedDrawCommand::Circle {
1931                center,
1932                radius,
1933                color,
1934            } => DrawCommand::Circle {
1935                center: Point::new(
1936                    Self::translate_coord(center.get_x(), dx_phys, scale, inv_scale, dyadic),
1937                    Self::translate_coord(center.get_y(), dy_phys, scale, inv_scale, dyadic),
1938                ),
1939                radius: *radius,
1940                color: *color,
1941            },
1942            CachedDrawCommand::Triangle { p0, p1, p2, color } => DrawCommand::Triangle {
1943                p0: Point::new(
1944                    Self::translate_coord(p0.get_x(), dx_phys, scale, inv_scale, dyadic),
1945                    Self::translate_coord(p0.get_y(), dy_phys, scale, inv_scale, dyadic),
1946                ),
1947                p1: Point::new(
1948                    Self::translate_coord(p1.get_x(), dx_phys, scale, inv_scale, dyadic),
1949                    Self::translate_coord(p1.get_y(), dy_phys, scale, inv_scale, dyadic),
1950                ),
1951                p2: Point::new(
1952                    Self::translate_coord(p2.get_x(), dx_phys, scale, inv_scale, dyadic),
1953                    Self::translate_coord(p2.get_y(), dy_phys, scale, inv_scale, dyadic),
1954                ),
1955                color: *color,
1956            },
1957            CachedDrawCommand::SpriteRegion {
1958                rect,
1959                buffer,
1960                src_rect,
1961                tint,
1962            } => DrawCommand::SpriteRegion {
1963                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1964                buffer: buffer.clone(),
1965                src_rect: *src_rect,
1966                tint: *tint,
1967            },
1968            CachedDrawCommand::PushClip(rect) => DrawCommand::PushClip(Self::translate_rect(
1969                *rect, dx_phys, dy_phys, scale, inv_scale, dyadic,
1970            )),
1971            CachedDrawCommand::PushRoundedClip { rect, radius } => DrawCommand::PushRoundedClip {
1972                rect: Self::translate_rect(*rect, dx_phys, dy_phys, scale, inv_scale, dyadic),
1973                radius: *radius,
1974            },
1975            CachedDrawCommand::PopClip => DrawCommand::PopClip,
1976        };
1977        display_list.push(translated);
1978    }
1979
1980    /// Compiles `tree` into `display_list`, culling offscreen nodes and honoring z-index stacking.
1981    ///
1982    /// # Arguments
1983    ///
1984    /// - `&SceneTree` - Laid-out scene tree.
1985    /// - `Size` - Logical viewport size.
1986    /// - `f32` - DPI scale factor.
1987    /// - `Color` - Surface clear background color.
1988    /// - `&mut DisplayList` - Output reusable display list.
1989    pub fn build(
1990        tree: &SceneTree,
1991        viewport: Size,
1992        scale_factor: f32,
1993        clear_color: Color,
1994        display_list: &mut DisplayList,
1995    ) {
1996        let mut saw_canvas: bool = false;
1997        Self::build_inner(
1998            tree,
1999            viewport,
2000            scale_factor,
2001            clear_color,
2002            display_list,
2003            None,
2004            &mut saw_canvas,
2005        );
2006    }
2007
2008    /// Packs an optional `NodeId` into a single `u64` (`u64::MAX` when `None`).
2009    ///
2010    /// # Arguments
2011    ///
2012    /// - `Option<NodeId>` - Optional node handle.
2013    ///
2014    /// # Returns
2015    ///
2016    /// - `u64` - Packed `(index << 32) | generation` or `u64::MAX`.
2017    #[inline(always)]
2018    #[must_use]
2019    fn pack_opt_node_id(node: Option<NodeId>) -> u64 {
2020        match node {
2021            Some(id) => ((id.get_index() as u64) << 32) | (id.get_generation() as u64),
2022            None => u64::MAX,
2023        }
2024    }
2025
2026    /// Compiles `tree` into `display_list` with cross-frame whole-list retention and subtree `DrawCommand` fragment caching.
2027    ///
2028    /// # Arguments
2029    ///
2030    /// - `&SceneTree` - Laid-out scene tree.
2031    /// - `Size` - Logical viewport size.
2032    /// - `f32` - DPI scale factor.
2033    /// - `Color` - Surface clear background color.
2034    /// - `bool` - Whether layout recomputed any node geometry on this frame.
2035    /// - `&mut DisplayList` - Output reusable display list.
2036    /// - `&mut PaintFragmentCache` - Persistent cross-frame fragment cache.
2037    pub fn build_retained(
2038        tree: &SceneTree,
2039        viewport: Size,
2040        scale_factor: f32,
2041        clear_color: Color,
2042        layout_changed: bool,
2043        display_list: &mut DisplayList,
2044        cache: &mut PaintFragmentCache,
2045    ) {
2046        let clamped_scale: f32 = scale_factor.max(0.5);
2047        let focus: FocusManager = tree.get_focus();
2048        let sig: PaintSceneSignature = PaintSceneSignature {
2049            tree_ptr: (tree as *const SceneTree) as usize,
2050            tree_revision: tree.get_revision(),
2051            viewport_w_bits: viewport.get_width().to_bits(),
2052            viewport_h_bits: viewport.get_height().to_bits(),
2053            scale_bits: clamped_scale.to_bits(),
2054            clear_rgba: u32::from_le_bytes(clear_color.to_rgba_bytes()),
2055            focused_packed: Self::pack_opt_node_id(focus.focused_node()),
2056            hovered_packed: Self::pack_opt_node_id(focus.hovered_node()),
2057            pressed_packed: Self::pack_opt_node_id(focus.pressed_node()),
2058            caret_visible: tree.get_caret_visible(),
2059            text_sel_sig: Self::text_selection_sig(tree),
2060        };
2061        if !layout_changed
2062            && !cache.last_has_canvas
2063            && !display_list.is_empty()
2064            && cache.has_last_scene
2065            && cache.last_scene_sig == sig
2066        {
2067            cache.whole_list_hits = cache.whole_list_hits.wrapping_add(1);
2068            return;
2069        }
2070        cache.ensure_slots();
2071        let mut saw_canvas: bool = false;
2072        Self::build_inner(
2073            tree,
2074            viewport,
2075            clamped_scale,
2076            clear_color,
2077            display_list,
2078            Some(cache),
2079            &mut saw_canvas,
2080        );
2081        cache.last_has_canvas = saw_canvas;
2082        cache.has_last_scene = true;
2083        cache.last_scene_sig = sig;
2084    }
2085
2086    /// Populates `out_ancestors` with deduplicated ancestor handles leading to every live `Portal` / `Position::Fixed` node.
2087    ///
2088    /// # Arguments
2089    ///
2090    /// - `&SceneTree` - Retained scene tree.
2091    /// - `&mut Vec<NodeId>` - Reusable output scratch buffer (cleared first).
2092    fn collect_portal_ancestors(tree: &SceneTree, out_ancestors: &mut Vec<NodeId>) {
2093        out_ancestors.clear();
2094        let portal_nodes: &[NodeId] = tree.portal_nodes();
2095        if portal_nodes.is_empty() {
2096            return;
2097        }
2098        for &pid in portal_nodes.iter() {
2099            let mut cur: Option<NodeId> = tree.get_node(pid).and_then(SceneNode::parent_id);
2100            while let Some(anc) = cur {
2101                if out_ancestors.contains(&anc) {
2102                    break;
2103                }
2104                out_ancestors.push(anc);
2105                cur = tree.get_node(anc).and_then(SceneNode::parent_id);
2106            }
2107        }
2108        if out_ancestors.len() > 16 {
2109            out_ancestors.sort_unstable_by_key(|id: &NodeId| {
2110                ((id.get_index() as u64) << 32) | (id.get_generation() as u64)
2111            });
2112        }
2113    }
2114
2115    /// Returns `true` when `node_id` lies on an ancestor chain above at least one live `Portal` or `Position::Fixed` node.
2116    ///
2117    /// # Arguments
2118    ///
2119    /// - `&[NodeId]` - Precomputed portal ancestor slice from `collect_portal_ancestors`.
2120    /// - `NodeId` - Candidate container node handle.
2121    ///
2122    /// # Returns
2123    ///
2124    /// - `bool` - True when a culled subtree rooted at `node_id` must still forward portal descendants.
2125    #[inline]
2126    #[must_use]
2127    fn is_portal_ancestor(ancestors: &[NodeId], node_id: NodeId) -> bool {
2128        if ancestors.is_empty() {
2129            return false;
2130        }
2131        if ancestors.len() <= 16 {
2132            return ancestors.contains(&node_id);
2133        }
2134        let target: u64 = ((node_id.get_index() as u64) << 32) | (node_id.get_generation() as u64);
2135        ancestors
2136            .binary_search_by_key(&target, |id: &NodeId| {
2137                ((id.get_index() as u64) << 32) | (id.get_generation() as u64)
2138            })
2139            .is_ok()
2140    }
2141
2142    /// Computes exact conservative logical paint bounds for `node`, accounting for directional `BoxShadow` spread/blur, focus rings, and text overhang.
2143    ///
2144    /// # Arguments
2145    ///
2146    /// - `&SceneNode` - Target scene node.
2147    /// - `Rect` - Transformed logical border-box bounds.
2148    /// - `&PaintStyle` - Active resolved paint style.
2149    /// - `bool` - Whether the node currently holds keyboard focus.
2150    /// - `(f32, f32)` - Accumulated physical pixel displacement `(total_off_x, total_off_y)`.
2151    /// - `f32` - Clamped DPI scale factor.
2152    /// - `f32` - Reciprocal of `scale`.
2153    ///
2154    /// # Returns
2155    ///
2156    /// - `Rect` - Conservative logical visual bounding rectangle matching software rasterization extents.
2157    #[inline]
2158    #[must_use]
2159    fn conservative_self_vis_rect(
2160        node: &SceneNode,
2161        bounds: Rect,
2162        paint: &PaintStyle,
2163        focused: bool,
2164        total_off_phys: (f32, f32),
2165        scale: f32,
2166        inv_scale: f32,
2167    ) -> Rect {
2168        let mut min_x: f32 = bounds.get_x() - 1.0;
2169        let mut min_y: f32 = bounds.get_y() - 1.0;
2170        let mut max_x: f32 = bounds.right() + 1.0;
2171        let mut max_y: f32 = bounds.bottom() + 1.0;
2172        if let Some(shadow) = paint.box_shadow()
2173            && shadow.get_color().get_a() > 0
2174        {
2175            let spread: f32 = shadow.get_spread_radius().max(0.0);
2176            let blur_phys: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
2177            let sigma_phys: f32 = (blur_phys * 0.5).max(0.75);
2178            let blur_pad: f32 = (sigma_phys * 3.0).ceil() * inv_scale + 2.0 * inv_scale;
2179            let pad: f32 = spread + blur_pad;
2180            let sx0: f32 = bounds.get_x() + shadow.get_offset_x() - pad;
2181            let sy0: f32 = bounds.get_y() + shadow.get_offset_y() - pad;
2182            let sx1: f32 = bounds.right() + shadow.get_offset_x() + pad;
2183            let sy1: f32 = bounds.bottom() + shadow.get_offset_y() + pad;
2184            min_x = min_x.min(sx0);
2185            min_y = min_y.min(sy0);
2186            max_x = max_x.max(sx1);
2187            max_y = max_y.max(sy1);
2188        }
2189        if focused && let Some(ring) = paint.focus_ring_border() {
2190            let rw: f32 = ring.get_width().max(0.0) + 1.0;
2191            min_x = min_x.min(bounds.get_x() - rw);
2192            min_y = min_y.min(bounds.get_y() - rw);
2193            max_x = max_x.max(bounds.right() + rw);
2194            max_y = max_y.max(bounds.bottom() + rw);
2195        }
2196        if matches!(node.get_kind(), NodeKind::Text(_)) {
2197            let content_b: Rect = node.layout_box.get_content_bounds();
2198            let cx0: f32 = ((content_b.get_x() * scale).round() + total_off_phys.0) * inv_scale;
2199            let cy0: f32 = ((content_b.get_y() * scale).round() + total_off_phys.1) * inv_scale;
2200            let pad: f32 = node.style_ref().text.get_font_size() * 0.5 + 2.0;
2201            min_x = min_x.min(cx0 - pad);
2202            min_y = min_y.min(cy0 - pad);
2203            max_x = max_x.max(cx0 + content_b.get_width() + pad);
2204            max_y = max_y.max(cy0 + content_b.get_height() + pad);
2205        }
2206        Rect::new(
2207            min_x,
2208            min_y,
2209            (max_x - min_x).max(0.0),
2210            (max_y - min_y).max(0.0),
2211        )
2212    }
2213
2214    /// Visits one child inside a clipped off-screen subtree solely to collect escaping `Portal` / `Position::Fixed` descendants in exact tree order.
2215    ///
2216    /// # Arguments
2217    ///
2218    /// - `&SceneTree` - Retained scene tree.
2219    /// - `NodeId` - Child node handle to inspect.
2220    /// - `f32` - Effective ancestor opacity.
2221    /// - `&mut PaintScratch<'_>` - Mutable portal queue and z-sort scratch buffers.
2222    fn visit_culled_portal_child(
2223        tree: &SceneTree,
2224        child_id: NodeId,
2225        parent_opacity: f32,
2226        scratch: &mut PaintScratch<'_>,
2227    ) {
2228        let Some(child) = tree.get_node(child_id) else {
2229            return;
2230        };
2231        let style: &Style = child.style_ref();
2232        let layout: &LayoutStyle = &style.layout;
2233        if layout.get_display() == Display::None {
2234            return;
2235        }
2236        let is_portal: bool = matches!(child.get_kind(), NodeKind::Portal)
2237            || layout.get_position() == Position::Fixed;
2238        if is_portal {
2239            if let Some(portal_queue) = scratch.portals.as_deref_mut() {
2240                portal_queue.push((layout.get_z_index(), portal_queue.len(), child_id));
2241            }
2242            return;
2243        }
2244        if !Self::is_portal_ancestor(scratch.portal_ancestors, child_id) {
2245            return;
2246        }
2247        let hovered: bool = child.get_interaction().get_hovered();
2248        let paint_opacity: f32 = if hovered {
2249            child
2250                .hover_paint()
2251                .map(|hp: PaintStyle| hp.get_opacity())
2252                .unwrap_or_else(|| style.paint.get_opacity())
2253        } else {
2254            style.paint.get_opacity()
2255        };
2256        let next_opacity: f32 = (parent_opacity * paint_opacity).clamp(0.0, 1.0);
2257        if next_opacity <= 0.0 {
2258            return;
2259        }
2260        Self::collect_portals_in_culled_subtree(tree, child_id, next_opacity, scratch);
2261    }
2262
2263    /// Walks only portal-ancestor branches below a culled clipped container so escaping `Portal` / `Position::Fixed` nodes preserve exact paint order with zero non-portal work.
2264    ///
2265    /// # Arguments
2266    ///
2267    /// - `&SceneTree` - Retained scene tree.
2268    /// - `NodeId` - Culled clipped ancestor node handle.
2269    /// - `f32` - Effective ancestor opacity.
2270    /// - `&mut PaintScratch<'_>` - Mutable portal queue and z-sort scratch buffers.
2271    fn collect_portals_in_culled_subtree(
2272        tree: &SceneTree,
2273        node_id: NodeId,
2274        parent_opacity: f32,
2275        scratch: &mut PaintScratch<'_>,
2276    ) {
2277        if tree.get_node(node_id).is_none() {
2278            return;
2279        }
2280        let child_count: usize = tree.child_count(node_id);
2281        if child_count == 0 {
2282            return;
2283        }
2284        let needs_z_sort: bool = child_count > 1 && tree.has_nonzero_z_child(node_id);
2285        if !needs_z_sort {
2286            for child_id in tree.children_iter(node_id) {
2287                Self::visit_culled_portal_child(tree, child_id, parent_opacity, scratch);
2288            }
2289        } else {
2290            let sort_start: usize = scratch.z_sort.len();
2291            for (idx, cid) in tree.children_iter(node_id).enumerate() {
2292                if let Some(c) = tree.get_node(cid) {
2293                    scratch
2294                        .z_sort
2295                        .push((c.style_ref().layout.get_z_index(), idx, cid));
2296                }
2297            }
2298            let sort_end: usize = scratch.z_sort.len();
2299            scratch.z_sort[sort_start..sort_end].sort_by(
2300                |a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
2301                    a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
2302                },
2303            );
2304            for slot_idx in sort_start..sort_end {
2305                let child_id: NodeId = scratch.z_sort[slot_idx].2;
2306                Self::visit_culled_portal_child(tree, child_id, parent_opacity, scratch);
2307            }
2308            scratch.z_sort.truncate(sort_start);
2309        }
2310    }
2311
2312    /// Shared internal scene-to-display-list builder supporting optional retained fragment caching.
2313    ///
2314    /// # Arguments
2315    ///
2316    /// - `&SceneTree` - Laid-out scene tree.
2317    /// - `Size` - Logical viewport size.
2318    /// - `f32` - DPI scale factor.
2319    /// - `Color` - Surface clear background color.
2320    /// - `&mut DisplayList` - Output reusable display list.
2321    /// - `Option<&mut PaintFragmentCache>` - Optional cross-frame fragment cache.
2322    /// - `&mut bool` - Output flag set when any `NodeKind::Canvas` is visited.
2323    fn build_inner(
2324        tree: &SceneTree,
2325        viewport: Size,
2326        scale_factor: f32,
2327        clear_color: Color,
2328        display_list: &mut DisplayList,
2329        mut fragments: Option<&mut PaintFragmentCache>,
2330        saw_canvas: &mut bool,
2331    ) {
2332        display_list.reset(viewport, scale_factor);
2333        display_list.push(DrawCommand::Clear(clear_color));
2334        let viewport_rect: Rect = Rect::new(0.0, 0.0, viewport.get_width(), viewport.get_height());
2335        let active_hover_target: Option<NodeId> = Self::resolve_active_hover_target(tree);
2336        let mut portals: Vec<(i32, usize, NodeId)> = take(&mut display_list.arena.portals_scratch);
2337        let mut z_sort: Vec<(i32, usize, NodeId)> = take(&mut display_list.arena.z_sort_scratch);
2338        let mut portal_ancestors: Vec<NodeId> =
2339            take(&mut display_list.arena.portal_ancestors_scratch);
2340        portals.clear();
2341        z_sort.clear();
2342        Self::collect_portal_ancestors(tree, &mut portal_ancestors);
2343        {
2344            let mut scratch: PaintScratch<'_> = PaintScratch {
2345                portals: Some(&mut portals),
2346                z_sort: &mut z_sort,
2347                portal_ancestors: portal_ancestors.as_slice(),
2348                fragments: fragments.as_deref_mut(),
2349                saw_canvas,
2350            };
2351            Self::emit_node(
2352                tree,
2353                tree.get_root(),
2354                (Point::new(0.0, 0.0), 1.0),
2355                viewport_rect,
2356                active_hover_target,
2357                &mut scratch,
2358                display_list,
2359            );
2360        }
2361        display_list.finalize_base_layer(display_list.len());
2362        if portals.len() > 1 {
2363            portals.sort_by(|a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
2364                a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
2365            });
2366        }
2367        {
2368            let mut portal_scratch: PaintScratch<'_> = PaintScratch {
2369                portals: None,
2370                z_sort: &mut z_sort,
2371                portal_ancestors: &[],
2372                fragments,
2373                saw_canvas,
2374            };
2375            for &(_, _, portal_id) in portals.iter() {
2376                Self::emit_node(
2377                    tree,
2378                    portal_id,
2379                    (Point::new(0.0, 0.0), 1.0),
2380                    viewport_rect,
2381                    active_hover_target,
2382                    &mut portal_scratch,
2383                    display_list,
2384                );
2385            }
2386        }
2387        portals.clear();
2388        z_sort.clear();
2389        portal_ancestors.clear();
2390        display_list.arena.portals_scratch = portals;
2391        display_list.arena.z_sort_scratch = z_sort;
2392        display_list.arena.portal_ancestors_scratch = portal_ancestors;
2393    }
2394
2395    /// Resolves the single innermost interactive non-scrim node along the active hover chain so nested controls never stack duplicate hover fills.
2396    ///
2397    /// # Arguments
2398    ///
2399    /// - `&SceneTree` - Retained scene tree.
2400    ///
2401    /// # Returns
2402    ///
2403    /// - `Option<NodeId>` - Innermost interactive node eligible for hover tinting.
2404    #[must_use]
2405    fn resolve_active_hover_target(tree: &SceneTree) -> Option<NodeId> {
2406        let mut cursor: Option<NodeId> = tree.get_focus().hovered_node();
2407        while let Some(id) = cursor {
2408            let Some(node) = tree.get_node(id) else {
2409                break;
2410            };
2411            let style: &Style = node.style_ref();
2412            let paint: &PaintStyle = &style.paint;
2413            let is_scrim: bool = matches!(node.get_kind(), NodeKind::Portal)
2414                || style.layout.get_position() == Position::Fixed;
2415            let is_transparent_canvas: bool = matches!(node.get_kind(), NodeKind::Canvas(_))
2416                && paint.background_color().is_none();
2417            if !is_scrim && !is_transparent_canvas {
2418                let is_interactive: bool = paint.get_cursor() == CursorIcon::Pointer
2419                    || node
2420                        .get_handlers()
2421                        .handler_for(&UiEventKind::Click(Point::default()))
2422                        .is_some();
2423                if is_interactive {
2424                    return Some(id);
2425                }
2426            }
2427            cursor = node.parent_id();
2428        }
2429        None
2430    }
2431
2432    /// Computes subtle shadcn-aligned hover/pressed color tinting for interactive controls.
2433    ///
2434    /// # Arguments
2435    ///
2436    /// - `Option<Color>` - Base background color, if any.
2437    /// - `bool` - Whether the pointer hovers the control.
2438    /// - `bool` - Whether the pointer actively presses the control.
2439    ///
2440    /// # Returns
2441    ///
2442    /// - `Option<Color>` - Tinted background color.
2443    fn interactive_tint(base: Option<Color>, hovered: bool, pressed: bool) -> Option<Color> {
2444        if !hovered && !pressed {
2445            return base;
2446        }
2447        let delta: i32 = if pressed { 24 } else { 14 };
2448        match base {
2449            Some(c) if c.get_a() > 0 => {
2450                let luma: u32 =
2451                    (c.get_r() as u32) * 299 + (c.get_g() as u32) * 587 + (c.get_b() as u32) * 114;
2452                if luma < 120_000 {
2453                    let lift: i32 = if pressed { 30 } else { 20 };
2454                    Some(Color::new(
2455                        (c.get_r() as i32 + lift).clamp(0, 255) as u8,
2456                        (c.get_g() as i32 + lift).clamp(0, 255) as u8,
2457                        (c.get_b() as i32 + lift).clamp(0, 255) as u8,
2458                        c.get_a(),
2459                    ))
2460                } else {
2461                    Some(Color::new(
2462                        (c.get_r() as i32 - delta).clamp(0, 255) as u8,
2463                        (c.get_g() as i32 - delta).clamp(0, 255) as u8,
2464                        (c.get_b() as i32 - delta).clamp(0, 255) as u8,
2465                        c.get_a(),
2466                    ))
2467                }
2468            }
2469            _ => Some(Color::rgba(113, 113, 122, if pressed { 42 } else { 26 })),
2470        }
2471    }
2472
2473    /// Recursively emits commands for `node_id` and its z-sorted children with hierarchical transform and physical-pixel lockstep.
2474    ///
2475    /// # Arguments
2476    ///
2477    /// - `&SceneTree` - Scene tree reference.
2478    /// - `NodeId` - Node to paint.
2479    /// - `(Point, f32)` - Accumulated ancestor physical pixel displacement `(tx_phys - scroll_phys)` and opacity.
2480    /// - `Rect` - Active cull clip rectangle.
2481    /// - `Option<NodeId>` - Innermost hovered interactive node eligible for automatic hover tinting.
2482    /// - `&mut PaintScratch<'_>` - Reusable portal queue and nested z-sort scratch buffers.
2483    /// - `&mut DisplayList` - Output command list.
2484    fn emit_node(
2485        tree: &SceneTree,
2486        node_id: NodeId,
2487        offset_and_opacity: (Point, f32),
2488        cull_rect: Rect,
2489        active_hover_target: Option<NodeId>,
2490        scratch: &mut PaintScratch<'_>,
2491        display_list: &mut DisplayList,
2492    ) {
2493        let (offset_phys, parent_opacity): (Point, f32) = offset_and_opacity;
2494        let Some(node) = tree.get_node(node_id) else {
2495            return;
2496        };
2497        let style: &Style = node.style_ref();
2498        let layout: &LayoutStyle = &style.layout;
2499        if layout.get_display() == Display::None {
2500            return;
2501        }
2502        if let Some(portal_queue) = scratch.portals.as_deref_mut()
2503            && (matches!(node.get_kind(), NodeKind::Portal)
2504                || layout.get_position() == Position::Fixed)
2505        {
2506            portal_queue.push((layout.get_z_index(), portal_queue.len(), node_id));
2507            return;
2508        }
2509        let interaction: InteractionState = node.get_interaction();
2510        let hovered: bool = interaction.get_hovered();
2511        let pressed: bool = interaction.get_pressed();
2512        if !hovered && (parent_opacity * style.paint.get_opacity()) <= 0.0 {
2513            return;
2514        }
2515        let mut paint_owned: Option<PaintStyle> = if hovered { node.hover_paint() } else { None };
2516        let prelim_paint: &PaintStyle = paint_owned.as_ref().unwrap_or(&style.paint);
2517        let opacity: f32 = (parent_opacity * prelim_paint.get_opacity()).clamp(0.0, 1.0);
2518        if opacity <= 0.0 {
2519            return;
2520        }
2521        let scale: f32 = display_list.get_scale_factor().max(0.5);
2522        let inv_scale: f32 = 1.0 / scale;
2523        let raw_bounds: Rect = node.layout_box.get_bounds();
2524        let transform: Transform2D = prelim_paint.get_transform();
2525        let tx_phys: f32 = (transform.get_translate_x() * scale).round();
2526        let ty_phys: f32 = (transform.get_translate_y() * scale).round();
2527        let total_off_x: f32 = offset_phys.get_x() + tx_phys;
2528        let total_off_y: f32 = offset_phys.get_y() + ty_phys;
2529        let raw_x0: f32 = (raw_bounds.get_x() * scale).round();
2530        let raw_y0: f32 = (raw_bounds.get_y() * scale).round();
2531        let raw_x1: f32 = (raw_bounds.right() * scale).round();
2532        let raw_y1: f32 = (raw_bounds.bottom() * scale).round();
2533        let static_w_phys: f32 = (raw_x1 - raw_x0).max(0.0);
2534        let static_h_phys: f32 = (raw_y1 - raw_y0).max(0.0);
2535        let scaled_w_phys: f32 = (static_w_phys * transform.get_scale_x()).round().max(0.0);
2536        let scaled_h_phys: f32 = (static_h_phys * transform.get_scale_y()).round().max(0.0);
2537        let scale_dx_phys: f32 = ((static_w_phys - scaled_w_phys) * 0.5).round();
2538        let scale_dy_phys: f32 = ((static_h_phys - scaled_h_phys) * 0.5).round();
2539        let bounds: Rect = Rect::new(
2540            (raw_x0 + total_off_x + scale_dx_phys) * inv_scale,
2541            (raw_y0 + total_off_y + scale_dy_phys) * inv_scale,
2542            scaled_w_phys * inv_scale,
2543            scaled_h_phys * inv_scale,
2544        );
2545        let clipped: bool = matches!(layout.get_overflow(), Overflow::Hidden | Overflow::Scroll);
2546        let clipped_cull: Option<Rect> = if clipped {
2547            cull_rect.intersect(bounds)
2548        } else {
2549            Some(cull_rect)
2550        };
2551        let focused: bool = interaction.get_focused();
2552        let self_vis_rect: Rect = Self::conservative_self_vis_rect(
2553            node,
2554            bounds,
2555            prelim_paint,
2556            focused,
2557            (total_off_x, total_off_y),
2558            scale,
2559            inv_scale,
2560        );
2561        let self_visible: bool = bounds.get_width() > 0.0
2562            && bounds.get_height() > 0.0
2563            && self_vis_rect.intersect(cull_rect).is_some();
2564        if clipped && clipped_cull.is_none() {
2565            if self_visible {
2566                if let Some(mut shadow) = prelim_paint.box_shadow() {
2567                    shadow.set_color(shadow.get_color().multiply_alpha(opacity));
2568                    display_list.push(DrawCommand::BoxShadow {
2569                        rect: bounds,
2570                        radius: prelim_paint.get_radius(),
2571                        shadow,
2572                    });
2573                }
2574                if focused && let Some(mut ring) = prelim_paint.focus_ring_border() {
2575                    ring.set_color(ring.get_color().multiply_alpha(opacity));
2576                    let ring_w: f32 = ring.get_width();
2577                    let ring_rect: Rect = Rect::new(
2578                        bounds.get_x() - ring_w,
2579                        bounds.get_y() - ring_w,
2580                        bounds.get_width() + ring_w * 2.0,
2581                        bounds.get_height() + ring_w * 2.0,
2582                    );
2583                    display_list.push(DrawCommand::FillRoundedRect {
2584                        rect: ring_rect,
2585                        color: COLOR_TRANSPARENT,
2586                        radius: CornerRadius::all(prelim_paint.get_radius().max_radius() + ring_w),
2587                        border: ring,
2588                    });
2589                }
2590            }
2591            if scratch.portals.is_some()
2592                && Self::is_portal_ancestor(scratch.portal_ancestors, node_id)
2593            {
2594                Self::collect_portals_in_culled_subtree(tree, node_id, opacity, scratch);
2595            }
2596            return;
2597        }
2598        let child_count: usize = tree.child_count(node_id);
2599        if !self_visible && child_count == 0 {
2600            return;
2601        }
2602        let next_cull: Rect = clipped_cull.unwrap_or(cull_rect);
2603        let hover_visual: bool = hovered && active_hover_target == Some(node_id);
2604        if self_visible
2605            && (hover_visual || pressed)
2606            && paint_owned.is_none()
2607            && (hovered || node.hover_paint().is_none())
2608        {
2609            let base_paint: &PaintStyle = &style.paint;
2610            let is_scrim: bool = matches!(node.get_kind(), NodeKind::Portal)
2611                || layout.get_position() == Position::Fixed;
2612            let is_transparent_canvas: bool = matches!(node.get_kind(), NodeKind::Canvas(_))
2613                && base_paint.background_color().is_none();
2614            if !is_scrim && !is_transparent_canvas {
2615                let is_interactive: bool = base_paint.get_cursor() == CursorIcon::Pointer
2616                    || node
2617                        .get_handlers()
2618                        .handler_for(&UiEventKind::Click(Point::default()))
2619                        .is_some();
2620                if is_interactive {
2621                    let mut tinted: PaintStyle = *base_paint;
2622                    tinted.set_background(Self::interactive_tint(
2623                        tinted.background_color(),
2624                        hover_visual,
2625                        pressed,
2626                    ));
2627                    paint_owned = Some(tinted);
2628                }
2629            }
2630        }
2631        let paint: &PaintStyle = paint_owned.as_ref().unwrap_or(&style.paint);
2632        let phys_scale_milli: u32 = Self::quantize_scale_milli(scale);
2633        let mut frag_capture: Option<(usize, usize, u64, u64)> = None;
2634        let frag_overflow_ok: bool = layout.get_overflow() == Overflow::Hidden
2635            || (layout.get_overflow() == Overflow::Visible
2636                && node_id != tree.get_root()
2637                && child_count >= 2);
2638        if self_visible
2639            && scratch.fragments.is_some()
2640            && scratch.portals.is_some()
2641            && matches!(node.get_kind(), NodeKind::View)
2642            && frag_overflow_ok
2643            && !hovered
2644            && !pressed
2645            && !interaction.get_focused()
2646            && active_hover_target != Some(node_id)
2647        {
2648            let vis_x_in: bool = self_vis_rect.get_x() >= cull_rect.get_x()
2649                && self_vis_rect.right() <= cull_rect.right();
2650            let vis_y_in: bool = self_vis_rect.get_y() >= cull_rect.get_y()
2651                && self_vis_rect.bottom() <= cull_rect.bottom();
2652            if vis_x_in && vis_y_in {
2653                let has_text_sel: bool = !tree.text_selection_spans_ref().is_empty();
2654                let unclipped_cull: Option<(Point, Rect, f32, f32)> =
2655                    if layout.get_overflow() == Overflow::Hidden {
2656                        None
2657                    } else {
2658                        let raw_node_scroll: Point = node.layout_box.get_scroll_offset();
2659                        let child_off: Point = Point::new(
2660                            total_off_x - (raw_node_scroll.get_x() * scale).round(),
2661                            total_off_y - (raw_node_scroll.get_y() * scale).round(),
2662                        );
2663                        Some((child_off, cull_rect, scale, inv_scale))
2664                    };
2665                if let Some((geom_hash, style_text_hash)) = Self::fingerprint_subtree(
2666                    tree,
2667                    node_id,
2668                    node,
2669                    unclipped_cull,
2670                    (active_hover_target, has_text_sel),
2671                ) {
2672                    let slot_idx: usize =
2673                        (node_id.get_index() as usize) & (PAINT_FRAGMENT_CACHE_SLOTS - 1);
2674                    let opacity_bits: u32 = parent_opacity.to_bits();
2675                    let dyadic_12: bool = scale == 1.0 || scale == 2.0;
2676                    let dyadic_scale: bool = dyadic_12 || scale == 4.0;
2677                    if let Some(cache) = scratch.fragments.as_deref_mut()
2678                        && let Some(&cached) = cache.slots.get(slot_idx)
2679                        && cached.occupied
2680                        && cached.node_id == node_id
2681                        && cached.phys_scale_milli == phys_scale_milli
2682                        && cached.opacity_bits == opacity_bits
2683                        && cached.geom_hash == geom_hash
2684                        && cached.style_text_hash == style_text_hash
2685                    {
2686                        let dx_phys: f32 = offset_phys.get_x() - cached.offset_phys.get_x();
2687                        let dy_phys: f32 = offset_phys.get_y() - cached.offset_phys.get_y();
2688                        let c_start: usize = cached.cmd_start as usize;
2689                        let c_end: usize = c_start.saturating_add(cached.cmd_len as usize);
2690                        if let Some(cmds) = cache.cmd_slab.get(c_start..c_end) {
2691                            display_list.get_mut_commands().reserve(cmds.len());
2692                            let text_slab: &[u8] = cache.text_slab.as_slice();
2693                            for cmd in cmds.iter() {
2694                                Self::push_translated_command(
2695                                    cmd,
2696                                    text_slab,
2697                                    (dx_phys, dy_phys),
2698                                    (scale, inv_scale, dyadic_scale),
2699                                    display_list,
2700                                );
2701                            }
2702                            cache.fragment_hits = cache.fragment_hits.wrapping_add(1);
2703                            return;
2704                        }
2705                    }
2706                    frag_capture = Some((display_list.len(), slot_idx, geom_hash, style_text_hash));
2707                }
2708            }
2709        }
2710        if self_visible {
2711            let blur_r: f32 = tree.backdrop_blur_radius(node_id);
2712            if blur_r > 0.0 {
2713                display_list.push(DrawCommand::BackdropBlur {
2714                    rect: bounds,
2715                    radius: paint.get_radius(),
2716                    blur_radius: blur_r,
2717                });
2718            }
2719            if let Some(mut shadow) = paint.box_shadow() {
2720                shadow.set_color(shadow.get_color().multiply_alpha(opacity));
2721                display_list.push(DrawCommand::BoxShadow {
2722                    rect: bounds,
2723                    radius: paint.get_radius(),
2724                    shadow,
2725                });
2726            }
2727            if let Some(mut gradient) = paint.background_gradient() {
2728                gradient.set_start_color(gradient.get_start_color().multiply_alpha(opacity));
2729                gradient.set_end_color(gradient.get_end_color().multiply_alpha(opacity));
2730                display_list.push(DrawCommand::LinearGradientRect {
2731                    rect: bounds,
2732                    gradient,
2733                    radius: paint.get_radius(),
2734                });
2735            } else if let Some(bg) = paint.background_color() {
2736                let mut border: Border = paint.get_border();
2737                border.set_color(border.get_color().multiply_alpha(opacity));
2738                display_list.push(DrawCommand::FillRoundedRect {
2739                    rect: bounds,
2740                    color: bg.multiply_alpha(opacity),
2741                    radius: paint.get_radius(),
2742                    border,
2743                });
2744            } else if paint.get_border().get_width() > 0.0 {
2745                let mut border: Border = paint.get_border();
2746                border.set_color(border.get_color().multiply_alpha(opacity));
2747                display_list.push(DrawCommand::FillRoundedRect {
2748                    rect: bounds,
2749                    color: COLOR_TRANSPARENT,
2750                    radius: paint.get_radius(),
2751                    border,
2752                });
2753            }
2754            if interaction.get_focused()
2755                && let Some(mut ring) = paint.focus_ring_border()
2756            {
2757                ring.set_color(ring.get_color().multiply_alpha(opacity));
2758                let ring_w: f32 = ring.get_width();
2759                let ring_rect: Rect = Rect::new(
2760                    bounds.get_x() - ring_w,
2761                    bounds.get_y() - ring_w,
2762                    bounds.get_width() + ring_w * 2.0,
2763                    bounds.get_height() + ring_w * 2.0,
2764                );
2765                display_list.push(DrawCommand::FillRoundedRect {
2766                    rect: ring_rect,
2767                    color: COLOR_TRANSPARENT,
2768                    radius: CornerRadius::all(paint.get_radius().max_radius() + ring_w),
2769                    border: ring,
2770                });
2771            }
2772            match node.get_kind() {
2773                NodeKind::Text(text) => {
2774                    let mut text_style: TextStyle = style.text;
2775                    text_style.set_color(text_style.get_color().multiply_alpha(opacity));
2776                    let content_b: Rect = node.layout_box.get_content_bounds();
2777                    let cx0: f32 = (content_b.get_x() * scale).round();
2778                    let cy0: f32 = (content_b.get_y() * scale).round();
2779                    let shifted_content: Rect = Rect::new(
2780                        (cx0 + total_off_x) * inv_scale,
2781                        (cy0 + total_off_y) * inv_scale,
2782                        content_b.get_width(),
2783                        content_b.get_height(),
2784                    );
2785                    if let Some(sel_range) = tree.text_selection_range_for(node_id) {
2786                        let sel_color: Color = tree
2787                            .effective_selection_color(node_id)
2788                            .multiply_alpha(opacity);
2789                        let sel_rects: Vec<Rect> = compute_text_selection_rects(
2790                            text.as_str(),
2791                            text_style,
2792                            shifted_content,
2793                            sel_range,
2794                        );
2795                        for sel_rect in sel_rects.into_iter() {
2796                            display_list.push(DrawCommand::FillRoundedRect {
2797                                rect: sel_rect,
2798                                color: sel_color,
2799                                radius: CornerRadius::all(2.0),
2800                                border: Border::default(),
2801                            });
2802                        }
2803                    }
2804                    let pooled_text: String = display_list.alloc_text(text.as_str());
2805                    display_list.push(DrawCommand::TextRun {
2806                        rect: shifted_content,
2807                        text: pooled_text,
2808                        style: text_style,
2809                    });
2810                }
2811                NodeKind::Input(input_state) => {
2812                    let mut text_style: TextStyle = style.text;
2813                    let is_empty_value: bool = input_state.get_value().is_empty();
2814                    let is_focused: bool = interaction.get_focused();
2815                    let rendered_text: String = if is_empty_value {
2816                        text_style.set_color(text_style.get_color().multiply_alpha(opacity * 0.55));
2817                        display_list.alloc_text(input_state.get_placeholder().as_str())
2818                    } else if input_state.get_password() {
2819                        text_style.set_color(text_style.get_color().multiply_alpha(opacity));
2820                        let star_count: usize = input_state.get_value().chars().count();
2821                        let mut masked: String = display_list.alloc_text("");
2822                        for _ in 0..star_count {
2823                            masked.push('*');
2824                        }
2825                        masked
2826                    } else {
2827                        text_style.set_color(text_style.get_color().multiply_alpha(opacity));
2828                        display_list.alloc_text(input_state.get_value().as_str())
2829                    };
2830                    let content_b: Rect = node.layout_box.get_content_bounds();
2831                    let cx0: f32 = (content_b.get_x() * scale).round();
2832                    let cy0: f32 = (content_b.get_y() * scale).round();
2833                    let shifted_content: Rect = Rect::new(
2834                        (cx0 + total_off_x) * inv_scale,
2835                        (cy0 + total_off_y) * inv_scale,
2836                        content_b.get_width(),
2837                        content_b.get_height(),
2838                    );
2839                    let line_h: f32 =
2840                        (text_style.get_font_size() * text_style.get_line_height()).max(1.0);
2841                    let text_rect: Rect = if input_state.get_multiline() {
2842                        shifted_content
2843                    } else {
2844                        text_style.set_overflow(TextOverflow::Clip);
2845                        let v_off_phys: f32 =
2846                            (((shifted_content.get_height() - line_h) * 0.5).max(0.0) * scale)
2847                                .round();
2848                        let text_y: f32 = (cy0 + total_off_y + v_off_phys) * inv_scale;
2849                        Rect::new(
2850                            shifted_content.get_x(),
2851                            text_y,
2852                            shifted_content.get_width(),
2853                            line_h,
2854                        )
2855                    };
2856                    let run_rect: Rect =
2857                        if is_empty_value && is_focused && !rendered_text.is_empty() {
2858                            let clearance_phys: f32 =
2859                                (PLACEHOLDER_FOCUSED_CARET_CLEARANCE_PX * scale).round();
2860                            let clearance_logical: f32 = clearance_phys * inv_scale;
2861                            Rect::new(
2862                                text_rect.get_x() + clearance_logical,
2863                                text_rect.get_y(),
2864                                (text_rect.get_width() - clearance_logical).max(0.0),
2865                                text_rect.get_height(),
2866                            )
2867                        } else {
2868                            text_rect
2869                        };
2870                    let show_caret: bool = is_focused && tree.get_caret_visible();
2871                    let caret_text: String = if show_caret && !is_empty_value {
2872                        display_list.alloc_text(rendered_text.as_str())
2873                    } else {
2874                        String::new()
2875                    };
2876                    display_list.push(DrawCommand::PushClip(shifted_content));
2877                    display_list.push(DrawCommand::TextRun {
2878                        rect: run_rect,
2879                        text: rendered_text,
2880                        style: text_style,
2881                    });
2882                    if show_caret {
2883                        let caret_h: f32 = (text_style.get_font_size() * 1.15)
2884                            .min(shifted_content.get_height().max(12.0));
2885                        display_list.push(DrawCommand::TextCaret {
2886                            text_rect,
2887                            content_rect: shifted_content,
2888                            text: caret_text,
2889                            style: text_style,
2890                            caret_height: caret_h,
2891                            color: style.text.get_color().multiply_alpha(opacity),
2892                            multiline: input_state.get_multiline(),
2893                        });
2894                    }
2895                    display_list.push(DrawCommand::PopClip);
2896                }
2897                NodeKind::Image(buffer) => {
2898                    display_list.push(DrawCommand::Image {
2899                        rect: bounds,
2900                        buffer: buffer.clone(),
2901                        radius: paint.get_radius(),
2902                    });
2903                }
2904                NodeKind::Canvas(caching) => {
2905                    if let Some(callback) = node.canvas_callback()
2906                        && let Ok(mut func) = callback.try_borrow_mut()
2907                    {
2908                        let canvas_bw: f32 = paint.get_border().get_width();
2909                        let canvas_clip_rect: Rect = if canvas_bw > 0.0 {
2910                            Rect::new(
2911                                bounds.get_x() + canvas_bw,
2912                                bounds.get_y() + canvas_bw,
2913                                (bounds.get_width() - canvas_bw * 2.0).max(0.0),
2914                                (bounds.get_height() - canvas_bw * 2.0).max(0.0),
2915                            )
2916                        } else {
2917                            bounds
2918                        };
2919                        let canvas_max_r: f32 = (bounds.get_width() * 0.5)
2920                            .min(bounds.get_height() * 0.5)
2921                            .max(0.0);
2922                        let canvas_raw_r: CornerRadius = paint.get_radius();
2923                        let canvas_inner_r: CornerRadius = CornerRadius::new(
2924                            (canvas_raw_r.get_top_left().min(canvas_max_r) - canvas_bw).max(0.0),
2925                            (canvas_raw_r.get_top_right().min(canvas_max_r) - canvas_bw).max(0.0),
2926                            (canvas_raw_r.get_bottom_right().min(canvas_max_r) - canvas_bw)
2927                                .max(0.0),
2928                            (canvas_raw_r.get_bottom_left().min(canvas_max_r) - canvas_bw).max(0.0),
2929                        );
2930                        if canvas_inner_r.max_radius() > 0.25 {
2931                            display_list.push(DrawCommand::PushRoundedClip {
2932                                rect: canvas_clip_rect,
2933                                radius: canvas_inner_r,
2934                            });
2935                        } else {
2936                            display_list.push(DrawCommand::PushClip(canvas_clip_rect));
2937                        }
2938                        let canvas_cmd_start: usize = display_list.len();
2939                        func(bounds, display_list);
2940                        let canvas_cmd_end: usize = display_list.len();
2941                        if *caching != CanvasCaching::RetainedStatic {
2942                            let canvas_is_dynamic: bool =
2943                                if let Some(cache) = scratch.fragments.as_deref_mut() {
2944                                    let emitted: &[DrawCommand] = &display_list.get_commands()
2945                                        [canvas_cmd_start..canvas_cmd_end];
2946                                    cache.record_canvas_output(
2947                                        node_id,
2948                                        phys_scale_milli,
2949                                        bounds,
2950                                        tree.get_revision(),
2951                                        emitted,
2952                                    )
2953                                } else {
2954                                    true
2955                                };
2956                            if canvas_is_dynamic {
2957                                *scratch.saw_canvas = true;
2958                            }
2959                        }
2960                        display_list.push(DrawCommand::PopClip);
2961                    } else if *caching == CanvasCaching::DynamicPerFrame {
2962                        *scratch.saw_canvas = true;
2963                    }
2964                }
2965                NodeKind::View | NodeKind::ScrollView | NodeKind::Portal | NodeKind::Fragment => {}
2966            }
2967        }
2968        let vp: Size = display_list.get_viewport();
2969        let show_scrollbar: bool = vp.get_width().min(vp.get_height()) >= 540.0;
2970        let wants_scrollbar: bool = show_scrollbar
2971            && layout.get_overflow() == Overflow::Scroll
2972            && bounds.get_height() > 24.0;
2973        let emit_clip: bool = clipped && (child_count > 0 || wants_scrollbar);
2974        let clip_push_idx: usize = display_list.len();
2975        let clip_saved_digest: (u64, u64) = display_list.snapshot_digest_state();
2976        if emit_clip {
2977            let bw: f32 = paint.get_border().get_width();
2978            let clip_rect: Rect = if bw > 0.0 {
2979                Rect::new(
2980                    bounds.get_x() + bw,
2981                    bounds.get_y() + bw,
2982                    (bounds.get_width() - bw * 2.0).max(0.0),
2983                    (bounds.get_height() - bw * 2.0).max(0.0),
2984                )
2985            } else {
2986                bounds
2987            };
2988            let max_r: f32 = (bounds.get_width() * 0.5)
2989                .min(bounds.get_height() * 0.5)
2990                .max(0.0);
2991            let raw_r: CornerRadius = paint.get_radius();
2992            let inner_r: CornerRadius = CornerRadius::new(
2993                (raw_r.get_top_left().min(max_r) - bw).max(0.0),
2994                (raw_r.get_top_right().min(max_r) - bw).max(0.0),
2995                (raw_r.get_bottom_right().min(max_r) - bw).max(0.0),
2996                (raw_r.get_bottom_left().min(max_r) - bw).max(0.0),
2997            );
2998            if inner_r.max_radius() > 0.25 {
2999                display_list.push(DrawCommand::PushRoundedClip {
3000                    rect: clip_rect,
3001                    radius: inner_r,
3002                });
3003            } else {
3004                display_list.push(DrawCommand::PushClip(clip_rect));
3005            }
3006        }
3007        if child_count > 0 {
3008            let raw_node_scroll: Point = node.layout_box.get_scroll_offset();
3009            let scroll_x_phys: f32 = (raw_node_scroll.get_x() * scale).round();
3010            let scroll_y_phys: f32 = (raw_node_scroll.get_y() * scale).round();
3011            let child_offset_phys: Point =
3012                Point::new(total_off_x - scroll_x_phys, total_off_y - scroll_y_phys);
3013            let needs_z_sort: bool = child_count > 1 && tree.has_nonzero_z_child(node_id);
3014            if !needs_z_sort {
3015                for child_id in tree.children_iter(node_id) {
3016                    Self::emit_node(
3017                        tree,
3018                        child_id,
3019                        (child_offset_phys, opacity),
3020                        next_cull,
3021                        active_hover_target,
3022                        scratch,
3023                        display_list,
3024                    );
3025                }
3026            } else {
3027                let sort_start: usize = scratch.z_sort.len();
3028                for (idx, cid) in tree.children_iter(node_id).enumerate() {
3029                    if let Some(c) = tree.get_node(cid) {
3030                        scratch
3031                            .z_sort
3032                            .push((c.style_ref().layout.get_z_index(), idx, cid));
3033                    }
3034                }
3035                let sort_end: usize = scratch.z_sort.len();
3036                scratch.z_sort[sort_start..sort_end].sort_by(
3037                    |a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
3038                        a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
3039                    },
3040                );
3041                for slot_idx in sort_start..sort_end {
3042                    let child_id: NodeId = scratch.z_sort[slot_idx].2;
3043                    Self::emit_node(
3044                        tree,
3045                        child_id,
3046                        (child_offset_phys, opacity),
3047                        next_cull,
3048                        active_hover_target,
3049                        scratch,
3050                        display_list,
3051                    );
3052                }
3053                scratch.z_sort.truncate(sort_start);
3054            }
3055        }
3056        if wants_scrollbar {
3057            let lbox: &LayoutBox = &node.layout_box;
3058            let border_w: f32 = paint.get_border().get_width();
3059            let inner_x: f32 = bounds.get_x() + border_w;
3060            let inner_y: f32 = bounds.get_y() + border_w;
3061            let inner_w: f32 = (bounds.get_width() - border_w * 2.0).max(1.0);
3062            let inner_h: f32 = (bounds.get_height() - border_w * 2.0).max(1.0);
3063            let view_w: f32 = lbox.get_content_bounds().get_width().max(1.0);
3064            let view_h: f32 = lbox.get_content_bounds().get_height().max(1.0);
3065            let (scroll_y, total_h): (f32, f32) = match node.virtual_scroll_metrics() {
3066                Some((vy, vh)) => (vy, vh),
3067                None => (
3068                    lbox.get_scroll_offset().get_y(),
3069                    lbox.get_content_size().get_height(),
3070                ),
3071            };
3072            let scroll_x: f32 = lbox.get_scroll_offset().get_x();
3073            let total_w: f32 = lbox.get_content_size().get_width();
3074            let max_scroll_y: f32 = (total_h - view_h).max(0.0);
3075            let max_scroll_x: f32 = (total_w - view_w).max(0.0);
3076            let has_v_bar: bool = max_scroll_y > 1.0;
3077            let has_h_bar: bool = max_scroll_x > 1.0 && bounds.get_width() > 24.0;
3078            let corner_inset: f32 = if has_v_bar && has_h_bar { 8.0 } else { 0.0 };
3079            if has_v_bar {
3080                let track_margin: f32 = 3.0;
3081                let track_w: f32 = if hovered { 6.0 } else { 4.0 };
3082                let track_x: f32 = (inner_x + inner_w - track_w - 2.0).max(inner_x);
3083                let track_y: f32 = inner_y + track_margin;
3084                let track_h: f32 = (inner_h - track_margin * 2.0 - corner_inset).max(16.0);
3085                let ratio: f32 = (view_h / total_h.max(view_h)).clamp(0.0, 1.0);
3086                let min_thumb_h: f32 = 20.0_f32.min(track_h);
3087                let thumb_h: f32 = (track_h * ratio).clamp(min_thumb_h, track_h);
3088                let scroll_frac: f32 = (scroll_y / max_scroll_y).clamp(0.0, 1.0);
3089                let thumb_y: f32 = track_y + (track_h - thumb_h) * scroll_frac;
3090                let track_x_snapped: f32 = (track_x * scale).round() * inv_scale;
3091                let track_y_snapped: f32 = (track_y * scale).round() * inv_scale;
3092                let track_w_snapped: f32 = (track_w * scale).round().max(1.0) * inv_scale;
3093                let track_h_snapped: f32 = (track_h * scale).round().max(1.0) * inv_scale;
3094                let thumb_y_snapped: f32 = (thumb_y * scale).round() * inv_scale;
3095                let thumb_h_snapped: f32 = (thumb_h * scale).round().max(1.0) * inv_scale;
3096                if hovered {
3097                    display_list.push(DrawCommand::FillRoundedRect {
3098                        rect: Rect::new(
3099                            track_x_snapped,
3100                            track_y_snapped,
3101                            track_w_snapped,
3102                            track_h_snapped,
3103                        ),
3104                        color: Color::rgba(113, 113, 122, 24).multiply_alpha(opacity),
3105                        radius: CornerRadius::all(3.0),
3106                        border: Border::default(),
3107                    });
3108                }
3109                let thumb_alpha: u8 = if hovered { 180 } else { 112 };
3110                display_list.push(DrawCommand::FillRoundedRect {
3111                    rect: Rect::new(
3112                        track_x_snapped,
3113                        thumb_y_snapped,
3114                        track_w_snapped,
3115                        thumb_h_snapped,
3116                    ),
3117                    color: Color::rgba(113, 113, 122, thumb_alpha).multiply_alpha(opacity),
3118                    radius: CornerRadius::all(track_w * 0.5),
3119                    border: Border::default(),
3120                });
3121            }
3122            if has_h_bar {
3123                let track_margin: f32 = 3.0;
3124                let track_h: f32 = if hovered { 6.0 } else { 4.0 };
3125                let track_y: f32 = (inner_y + inner_h - track_h - 2.0).max(inner_y);
3126                let track_x: f32 = inner_x + track_margin;
3127                let track_w: f32 = (inner_w - track_margin * 2.0 - corner_inset).max(16.0);
3128                let ratio: f32 = (view_w / total_w.max(view_w)).clamp(0.0, 1.0);
3129                let min_thumb_w: f32 = 20.0_f32.min(track_w);
3130                let thumb_w: f32 = (track_w * ratio).clamp(min_thumb_w, track_w);
3131                let scroll_frac: f32 = (scroll_x / max_scroll_x).clamp(0.0, 1.0);
3132                let thumb_x: f32 = track_x + (track_w - thumb_w) * scroll_frac;
3133                let track_x_snapped: f32 = (track_x * scale).round() * inv_scale;
3134                let track_y_snapped: f32 = (track_y * scale).round() * inv_scale;
3135                let track_w_snapped: f32 = (track_w * scale).round().max(1.0) * inv_scale;
3136                let track_h_snapped: f32 = (track_h * scale).round().max(1.0) * inv_scale;
3137                let thumb_x_snapped: f32 = (thumb_x * scale).round() * inv_scale;
3138                let thumb_w_snapped: f32 = (thumb_w * scale).round().max(1.0) * inv_scale;
3139                if hovered {
3140                    display_list.push(DrawCommand::FillRoundedRect {
3141                        rect: Rect::new(
3142                            track_x_snapped,
3143                            track_y_snapped,
3144                            track_w_snapped,
3145                            track_h_snapped,
3146                        ),
3147                        color: Color::rgba(113, 113, 122, 24).multiply_alpha(opacity),
3148                        radius: CornerRadius::all(3.0),
3149                        border: Border::default(),
3150                    });
3151                }
3152                let thumb_alpha: u8 = if hovered { 180 } else { 112 };
3153                display_list.push(DrawCommand::FillRoundedRect {
3154                    rect: Rect::new(
3155                        thumb_x_snapped,
3156                        track_y_snapped,
3157                        thumb_w_snapped,
3158                        track_h_snapped,
3159                    ),
3160                    color: Color::rgba(113, 113, 122, thumb_alpha).multiply_alpha(opacity),
3161                    radius: CornerRadius::all(track_h * 0.5),
3162                    border: Border::default(),
3163                });
3164            }
3165        }
3166        if emit_clip {
3167            if display_list.len() == clip_push_idx + 1 {
3168                display_list.pop_empty_clip(clip_saved_digest);
3169            } else {
3170                display_list.push(DrawCommand::PopClip);
3171            }
3172        }
3173        if let Some((cmd_start, slot_idx, geom_hash, style_text_hash)) = frag_capture
3174            && let Some(cache) = scratch.fragments.as_deref_mut()
3175        {
3176            let cmd_slice: &[DrawCommand] = &display_list.get_commands()[cmd_start..];
3177            cache.capture_fragment(
3178                slot_idx,
3179                (
3180                    node_id,
3181                    phys_scale_milli,
3182                    parent_opacity.to_bits(),
3183                    offset_phys,
3184                    geom_hash,
3185                    style_text_hash,
3186                ),
3187                cmd_slice,
3188            );
3189        }
3190    }
3191}