euv-core 0.51.0

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

/// Exclusive byte end and overlap utilities for `DirtyBufferSpan`.
impl DirtyBufferSpan {
    /// Returns the exclusive ending byte offset (`byte_offset + byte_len`).
    ///
    /// # Returns
    ///
    /// - `usize` - Exclusive byte end offset.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn byte_end(&self) -> usize {
        self.get_byte_offset().saturating_add(self.get_byte_len())
    }

    /// Returns `true` when this span covers zero bytes.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `byte_len == 0`.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.get_byte_len() == 0
    }
}

/// Default `DirtySpanCoalescer` configured with `DIRTY_SPAN_MERGE_GAP_BYTES` (`256` bytes).
impl Default for DirtySpanCoalescer {
    /// Creates an empty `DirtySpanCoalescer` with the default 256-byte gap merge threshold.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized dirty span coalescer.
    fn default() -> Self {
        Self::with_merge_gap(DIRTY_SPAN_MERGE_GAP_BYTES)
    }
}

/// Dirty byte-range collection and gap-bridging coalescing for `DirtySpanCoalescer`.
impl DirtySpanCoalescer {
    /// Creates an empty `DirtySpanCoalescer` merging spans separated by at most `merge_gap_bytes`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum inter-span byte gap bridged during coalescing.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured dirty span coalescer.
    #[must_use]
    pub fn with_merge_gap(merge_gap_bytes: usize) -> Self {
        Self {
            merge_gap_bytes,
            pending: Vec::new(),
            coalesced: Vec::new(),
            needs_coalesce: false,
            retained_primitives: Vec::new(),
            last_dirty_bytes: 0,
            last_full_bytes: 0,
            cumulative_bytes_saved: 0,
        }
    }

    /// Clears all pending and coalesced spans while retaining backing vector capacity.
    pub fn clear(&mut self) {
        let Self {
            pending,
            coalesced,
            needs_coalesce,
            ..
        } = self;
        pending.clear();
        coalesced.clear();
        *needs_coalesce = false;
    }

    /// Records a dirty byte range `[byte_offset .. byte_offset + byte_len)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Inclusive starting byte offset.
    /// - `usize` - Byte length of the dirty range.
    pub fn mark_range(&mut self, byte_offset: usize, byte_len: usize) {
        if byte_len == 0 {
            return;
        }
        let Self {
            pending,
            needs_coalesce,
            ..
        } = self;
        pending.push(DirtyBufferSpan::new(byte_offset, byte_len));
        *needs_coalesce = true;
    }

    /// Records a single dirty fixed-stride record at `elem_index` (`elem_index * stride_bytes`).
    ///
    /// # Arguments
    ///
    /// - `usize` - Zero-based element index inside the target GPU storage buffer.
    /// - `usize` - Byte stride per element.
    pub fn mark_element(&mut self, elem_index: usize, stride_bytes: usize) {
        self.mark_range(elem_index.saturating_mul(stride_bytes), stride_bytes);
    }

    /// Sorts and merges all pending spans whose inter-span gap is `<= merge_gap_bytes`, returning the coalesced slice.
    ///
    /// # Returns
    ///
    /// - `&[DirtyBufferSpan]` - Sorted, non-overlapping coalesced dirty spans ready for GPU upload.
    pub fn coalesce(&mut self) -> &[DirtyBufferSpan] {
        let Self {
            merge_gap_bytes,
            pending,
            coalesced,
            needs_coalesce,
            ..
        } = self;
        if !*needs_coalesce {
            return coalesced.as_slice();
        }
        coalesced.clear();
        if !pending.is_empty() {
            pending.sort_unstable_by_key(|span: &DirtyBufferSpan| {
                (span.get_byte_offset(), span.get_byte_len())
            });
            let mut active: DirtyBufferSpan = pending[0];
            for next_span in pending.iter().copied().skip(1) {
                let active_end: usize = active.byte_end();
                let next_start: usize = next_span.get_byte_offset();
                let next_end: usize = next_span.byte_end();
                if next_start <= active_end.saturating_add(*merge_gap_bytes) {
                    let merged_end: usize = active_end.max(next_end);
                    active.set_byte_len(merged_end.saturating_sub(active.get_byte_offset()));
                } else {
                    coalesced.push(active);
                    active = next_span;
                }
            }
            coalesced.push(active);
            pending.clear();
        }
        *needs_coalesce = false;
        coalesced.as_slice()
    }

    /// Returns the total number of bytes covered by all currently coalesced spans.
    ///
    /// # Returns
    ///
    /// - `usize` - Sum of `byte_len` across all coalesced spans.
    #[must_use]
    pub fn total_coalesced_bytes(&mut self) -> usize {
        self.coalesce()
            .iter()
            .map(DirtyBufferSpan::get_byte_len)
            .sum()
    }

    /// Returns `true` when no pending or coalesced dirty spans are recorded.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        let Self {
            pending, coalesced, ..
        } = self;
        pending.is_empty() && coalesced.is_empty()
    }

    /// Diffs `current` against the retained primitive buffer and returns coalesced dirty byte spans for Pass 1 upload.
    ///
    /// # Arguments
    ///
    /// - `&[GpuPrimitiveInstance]` - Current frame's packed 64-byte primitive slice.
    ///
    /// # Returns
    ///
    /// - `&[DirtyBufferSpan]` - Coalesced dirty byte ranges requiring GPU copy.
    pub fn diff_and_coalesce(&mut self, current: &[GpuPrimitiveInstance]) -> &[DirtyBufferSpan] {
        let stride: usize = size_of::<GpuPrimitiveInstance>();
        let full_bytes: usize = current.len().saturating_mul(stride);
        let Self {
            merge_gap_bytes,
            pending,
            coalesced,
            needs_coalesce,
            retained_primitives,
            last_dirty_bytes,
            last_full_bytes,
            cumulative_bytes_saved,
        } = self;
        pending.clear();
        coalesced.clear();
        *needs_coalesce = false;
        let prev_len: usize = retained_primitives.len();
        let cur_len: usize = current.len();
        if prev_len != cur_len {
            retained_primitives.clear();
            retained_primitives.extend_from_slice(current);
            if full_bytes > 0 {
                coalesced.push(DirtyBufferSpan::new(0, full_bytes));
            }
            *last_dirty_bytes = full_bytes;
            *last_full_bytes = full_bytes;
            return coalesced.as_slice();
        }
        let mut run_start: Option<usize> = None;
        for (idx, prim) in current.iter().enumerate() {
            // SAFETY: `GpuPrimitiveInstance` is `#[repr(C)]` 64 bytes with no uninitialized padding bytes.
            let prev_words: &[u64; 8] = unsafe {
                &*(&retained_primitives[idx] as *const GpuPrimitiveInstance).cast::<[u64; 8]>()
            };
            // SAFETY: `GpuPrimitiveInstance` is `#[repr(C)]` 64 bytes with no uninitialized padding bytes.
            let cur_words: &[u64; 8] =
                unsafe { &*(prim as *const GpuPrimitiveInstance).cast::<[u64; 8]>() };
            if prev_words != cur_words {
                retained_primitives[idx] = *prim;
                if run_start.is_none() {
                    run_start = Some(idx);
                }
            } else if let Some(start_idx) = run_start.take() {
                coalesced.push(DirtyBufferSpan::new(
                    start_idx.saturating_mul(stride),
                    idx.saturating_sub(start_idx).saturating_mul(stride),
                ));
            }
        }
        if let Some(start_idx) = run_start {
            coalesced.push(DirtyBufferSpan::new(
                start_idx.saturating_mul(stride),
                cur_len.saturating_sub(start_idx).saturating_mul(stride),
            ));
        }
        coalesce_dirty_buffer_spans(coalesced, *merge_gap_bytes);
        let dirty_bytes: usize = coalesced
            .iter()
            .map(|span: &DirtyBufferSpan| span.get_byte_len())
            .sum();
        *last_dirty_bytes = dirty_bytes;
        *last_full_bytes = full_bytes;
        *cumulative_bytes_saved =
            cumulative_bytes_saved.saturating_add(full_bytes.saturating_sub(dirty_bytes) as u64);
        coalesced.as_slice()
    }

    /// Returns the most recent upload bandwidth savings ratio in `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `f32` - Fraction of full-frame primitive bytes avoided by dirty-span coalescing.
    #[must_use]
    pub fn last_savings_ratio(&self) -> f32 {
        let full: usize = self.get_last_full_bytes();
        if full == 0 {
            return 0.0;
        }
        let dirty: usize = self.get_last_dirty_bytes().min(full);
        ((full - dirty) as f32) / (full as f32)
    }

    /// Clears the retained shadow buffer and dirty spans, forcing a full upload on the next frame.
    pub fn reset(&mut self) {
        let Self {
            pending,
            coalesced,
            needs_coalesce,
            retained_primitives,
            ..
        } = self;
        pending.clear();
        coalesced.clear();
        *needs_coalesce = false;
        retained_primitives.clear();
    }
}

/// Level-contiguous Breadth-First Search topology construction and query helpers for `FlatBfsTopology`.
impl FlatBfsTopology {
    /// Returns the total number of reachable nodes in the BFS ordering.
    ///
    /// # Returns
    ///
    /// - `usize` - Reachable BFS node count.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.get_bfs_to_arena().len()
    }

    /// Returns the number of tree depth levels (`0` when empty).
    ///
    /// # Returns
    ///
    /// - `usize` - Depth level count.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn depth_count(&self) -> usize {
        self.get_level_offsets().len().saturating_sub(1)
    }

    /// Returns the inclusive-exclusive BFS index range `[start, end)` for tree depth `level`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Zero-based tree depth level (`0` = root).
    ///
    /// # Returns
    ///
    /// - `(usize, usize)` - Contiguous BFS slice bounds for `level`.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn level_range(&self, level: usize) -> (usize, usize) {
        let offsets: &[u32] = self.get_level_offsets().as_slice();
        if level + 1 >= offsets.len() {
            return (0, 0);
        }
        (offsets[level] as usize, offsets[level + 1] as usize)
    }

    /// Returns the contiguous BFS index range `[first, first + count)` of direct children for `bfs_index`.
    ///
    /// # Arguments
    ///
    /// - `usize` - BFS node index.
    ///
    /// # Returns
    ///
    /// - `(usize, usize)` - Contiguous direct-child BFS slice bounds.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn children_bfs_range(&self, bfs_index: usize) -> (usize, usize) {
        let first: u32 = self
            .get_child_first()
            .get(bfs_index)
            .copied()
            .unwrap_or(GPU_LAYOUT_INDEX_NONE);
        let count: u32 = self.get_child_count().get(bfs_index).copied().unwrap_or(0);
        if first == GPU_LAYOUT_INDEX_NONE || count == 0 {
            return (0, 0);
        }
        let start: usize = first as usize;
        (start, start.saturating_add(count as usize))
    }

    /// Rebuilds the level-contiguous BFS topology from `tree` only when `topology_revision` or `root` changed.
    ///
    /// # Arguments
    ///
    /// - `&SceneTree` - Retained scene tree reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when topology was rebuilt; `false` when already up to date.
    pub fn rebuild_from_tree(&mut self, tree: &SceneTree) -> bool {
        let root_id: NodeId = tree.get_root();
        let root_arena: u32 = root_id.get_index();
        let tree_topo_rev: u64 = tree.get_topology_revision();
        let arena_len: usize = tree.get_nodes().len();
        if self.get_topology_revision() == tree_topo_rev
            && self.get_root_arena_index() == root_arena
            && self.get_arena_to_bfs().len() == arena_len
            && !self.get_bfs_to_arena().is_empty()
        {
            return false;
        }
        let Self {
            topology_revision,
            root_arena_index,
            bfs_to_arena,
            arena_to_bfs,
            parent_bfs,
            child_first,
            child_count,
            level_offsets,
            subtree_sizes,
        } = self;
        bfs_to_arena.clear();
        parent_bfs.clear();
        child_first.clear();
        child_count.clear();
        level_offsets.clear();
        subtree_sizes.clear();
        arena_to_bfs.clear();
        arena_to_bfs.resize(arena_len, GPU_LAYOUT_INDEX_NONE);
        if tree.get_node(root_id).is_none() {
            *topology_revision = tree_topo_rev;
            *root_arena_index = GPU_LAYOUT_INDEX_NONE;
            return true;
        }
        let live_cap: usize = tree.live_node_count().max(1);
        if bfs_to_arena.capacity() < live_cap {
            bfs_to_arena.reserve(live_cap - bfs_to_arena.len());
            parent_bfs.reserve(live_cap - parent_bfs.len());
            child_first.reserve(live_cap - child_first.len());
            child_count.reserve(live_cap - child_count.len());
        }
        let meta_slice: &[NodeMeta] = tree.get_meta().as_slice();
        let topo_slice: &[NodeTopology] = tree.get_topology().as_slice();
        arena_to_bfs[root_arena as usize] = 0;
        bfs_to_arena.push(root_arena);
        parent_bfs.push(GPU_LAYOUT_INDEX_NONE);
        child_first.push(GPU_LAYOUT_INDEX_NONE);
        child_count.push(0);
        level_offsets.push(0);
        let mut level_start: usize = 0;
        while level_start < bfs_to_arena.len() {
            let level_end: usize = bfs_to_arena.len();
            level_offsets.push(level_end as u32);
            for cur_bfs in level_start..level_end {
                let cur_arena: usize = bfs_to_arena[cur_bfs] as usize;
                let mut child_arena: u32 = topo_slice[cur_arena].get_first_child();
                let mut first_slot: u32 = GPU_LAYOUT_INDEX_NONE;
                let mut pushed_children: u32 = 0;
                while child_arena != NODE_INDEX_NONE {
                    let child_idx: usize = child_arena as usize;
                    let next_sib: u32 = topo_slice[child_idx].get_next_sibling();
                    let is_alive: bool = (meta_slice[child_idx].get_flags() & NODE_FLAG_ALIVE) != 0;
                    if is_alive && arena_to_bfs[child_idx] == GPU_LAYOUT_INDEX_NONE {
                        let next_bfs: u32 = bfs_to_arena.len() as u32;
                        if first_slot == GPU_LAYOUT_INDEX_NONE {
                            first_slot = next_bfs;
                        }
                        arena_to_bfs[child_idx] = next_bfs;
                        bfs_to_arena.push(child_arena);
                        parent_bfs.push(cur_bfs as u32);
                        child_first.push(GPU_LAYOUT_INDEX_NONE);
                        child_count.push(0);
                        pushed_children = pushed_children.saturating_add(1);
                    }
                    child_arena = next_sib;
                }
                child_first[cur_bfs] = first_slot;
                child_count[cur_bfs] = pushed_children;
            }
            level_start = level_end;
        }
        let total_bfs: usize = bfs_to_arena.len();
        subtree_sizes.resize(total_bfs, 1);
        for cur_bfs in (1..total_bfs).rev() {
            let parent_idx: u32 = parent_bfs[cur_bfs];
            if parent_idx != GPU_LAYOUT_INDEX_NONE {
                let sub_val: u32 = subtree_sizes[cur_bfs];
                let p_slot: usize = parent_idx as usize;
                subtree_sizes[p_slot] = subtree_sizes[p_slot].saturating_add(sub_val);
            }
        }
        *topology_revision = tree_topo_rev;
        *root_arena_index = root_arena;
        true
    }
}

/// Incremental `SceneTree` extraction, GPU compute input packing, and box write-back for `SceneLayoutSoa`.
impl SceneLayoutSoa {
    /// Returns the UTF-8 text string slice stored in `text_bytes` for arena slot `arena_index`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Scene tree arena slot index.
    ///
    /// # Returns
    ///
    /// - `&str` - Contiguous UTF-8 text payload (`""` for non-text nodes).
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn text_for_arena(&self, arena_index: usize) -> &str {
        let Some(slice) = self.get_text_slices().get(arena_index).copied() else {
            return "";
        };
        let start: usize = slice.get_byte_start() as usize;
        let end: usize = start.saturating_add(slice.get_byte_len() as usize);
        if end > self.get_text_bytes().len() || start == end {
            return "";
        }
        from_utf8(&self.get_text_bytes()[start..end]).unwrap_or("")
    }

    /// Synchronizes `FlatBfsTopology`, dense `Send + Sync` SoA slabs, and GPU dirty-range inputs from `tree`.
    ///
    /// # Arguments
    ///
    /// - `&SceneTree` - Retained scene tree to mirror into SoA slabs.
    ///
    /// # Returns
    ///
    /// - `SoaSyncMode` - Whether sync was skipped, incremental, or a full topology rebuild.
    pub fn sync_from_tree(&mut self, tree: &SceneTree) -> SoaSyncMode {
        let tree_rev: u64 = tree.get_revision();
        let tree_topo_rev: u64 = tree.get_topology_revision();
        let tree_serial_epoch: u64 = tree.get_serial_layout_epoch();
        if self.get_synced_revision() == tree_rev
            && self.get_synced_topology_revision() == tree_topo_rev
            && self.get_synced_serial_epoch() == tree_serial_epoch
            && !self.get_topology().get_bfs_to_arena().is_empty()
        {
            self.get_mut_input_dirty_spans().clear();
            self.get_mut_visual_dirty_spans().clear();
            self.set_last_sync_mode(SoaSyncMode::SkippedClean);
            return SoaSyncMode::SkippedClean;
        }
        let topo_rebuilt: bool = self.get_mut_topology().rebuild_from_tree(tree);
        let arena_len: usize = tree.get_nodes().len();
        let bfs_len: usize = self.get_topology().node_count();
        let Self {
            synced_revision,
            synced_topology_revision,
            synced_serial_epoch,
            last_sync_mode,
            topology,
            node_ids,
            node_kinds,
            layout_styles,
            text_styles,
            border_widths,
            transforms,
            layout_boxes,
            dirty_masks,
            synced_node_epochs,
            text_slices,
            text_bytes,
            image_sizes,
            gpu_inputs,
            gpu_outputs,
            gpu_visuals,
            input_dirty_spans,
            visual_dirty_spans,
        } = self;
        let serial_diverged: bool = *synced_serial_epoch != tree_serial_epoch;
        let force_full: bool = topo_rebuilt
            || node_ids.len() != arena_len
            || synced_node_epochs.len() != arena_len
            || gpu_inputs.len() != bfs_len
            || gpu_visuals.len() != bfs_len;
        input_dirty_spans.clear();
        visual_dirty_spans.clear();
        if force_full {
            node_ids.resize(arena_len, NodeId::default());
            node_kinds.resize(arena_len, SoaNodeKindTag::Container);
            layout_styles.resize(arena_len, LayoutStyle::default());
            text_styles.resize(arena_len, TextStyle::default());
            border_widths.resize(arena_len, 0.0);
            transforms.resize(arena_len, Transform2D::default());
            layout_boxes.resize(arena_len, LayoutBox::default());
            dirty_masks.resize(arena_len, 0);
            synced_node_epochs.resize(arena_len, 0);
            text_slices.resize(arena_len, SoaTextSlice::default());
            image_sizes.resize(arena_len, Size::default());
            text_bytes.clear();
            gpu_inputs.resize(bfs_len, GpuLayoutNodeInput::default());
            gpu_outputs.resize(bfs_len, GpuLayoutNodeOutput::default());
            gpu_visuals.resize(bfs_len, GpuVisualStyleInput::default());
        }
        let nodes: &[SceneNode] = tree.get_nodes().as_slice();
        let meta_slice: &[NodeMeta] = tree.get_meta().as_slice();
        let tree_epochs: &[u32] = tree.get_node_mutation_epochs().as_slice();
        let bfs_to_arena: &[u32] = topology.get_bfs_to_arena().as_slice();
        let parent_bfs: &[u32] = topology.get_parent_bfs().as_slice();
        let child_first: &[u32] = topology.get_child_first().as_slice();
        let child_count: &[u32] = topology.get_child_count().as_slice();
        for bfs_idx in 0..bfs_len {
            let arena_idx: usize = bfs_to_arena[bfs_idx] as usize;
            let node: &SceneNode = &nodes[arena_idx];
            let dirty_bits: u16 = meta_slice[arena_idx].get_dirty();
            let node_epoch: u32 = tree_epochs.get(arena_idx).copied().unwrap_or(0);
            let node_changed: bool = force_full
                || dirty_bits != 0
                || dirty_masks[arena_idx] != dirty_bits
                || synced_node_epochs[arena_idx] != node_epoch
                || node_ids[arena_idx].get_generation() != node.get_generation();
            if !node_changed {
                if serial_diverged {
                    let cur_box: LayoutBox = node.get_layout_box();
                    layout_boxes[arena_idx] = cur_box;
                    dirty_masks[arena_idx] = dirty_bits;
                    let bounds: Rect = cur_box.get_bounds();
                    let content_bounds: Rect = cur_box.get_content_bounds();
                    gpu_outputs[bfs_idx] = GpuLayoutNodeOutput {
                        rect: [
                            bounds.get_x(),
                            bounds.get_y(),
                            bounds.get_width(),
                            bounds.get_height(),
                        ],
                        content_rect: [
                            content_bounds.get_x(),
                            content_bounds.get_y(),
                            content_bounds.get_width(),
                            content_bounds.get_height(),
                        ],
                    };
                }
                continue;
            }
            synced_node_epochs[arena_idx] = node_epoch;
            node_ids[arena_idx] = NodeId::new(arena_idx as u32, node.get_generation());
            let kind_tag: SoaNodeKindTag = soa_kind_from_node_kind(node.get_kind());
            node_kinds[arena_idx] = kind_tag;
            let style_ref: &Style = node.style_ref();
            let layout_style: LayoutStyle = *style_ref.layout_ref();
            let paint_style: &PaintStyle = style_ref.paint_ref();
            let text_style: TextStyle = *style_ref.text_ref();
            let border_width: f32 = paint_style.get_border().get_width();
            layout_styles[arena_idx] = layout_style;
            text_styles[arena_idx] = text_style;
            border_widths[arena_idx] = border_width;
            transforms[arena_idx] = paint_style.get_transform();
            layout_boxes[arena_idx] = node.get_layout_box();
            dirty_masks[arena_idx] = dirty_bits;
            let mut intrinsic_size: Size = Size::default();
            let mut wrapping_text: bool = false;
            match node.get_kind() {
                NodeKind::Text(text) => {
                    let raw_bytes: &[u8] = text.as_bytes();
                    let prev_slice: SoaTextSlice = text_slices[arena_idx];
                    let prev_start: usize = prev_slice.get_byte_start() as usize;
                    let prev_len: usize = prev_slice.get_byte_len() as usize;
                    let next_slice: SoaTextSlice = if !force_full
                        && raw_bytes.len() <= prev_len
                        && prev_start.saturating_add(prev_len) <= text_bytes.len()
                    {
                        text_bytes[prev_start..prev_start + raw_bytes.len()]
                            .copy_from_slice(raw_bytes);
                        SoaTextSlice::new(
                            prev_slice.get_byte_start(),
                            raw_bytes.len() as u32,
                            text.is_ascii(),
                        )
                    } else {
                        let text_start: u32 = text_bytes.len() as u32;
                        text_bytes.extend_from_slice(raw_bytes);
                        SoaTextSlice::new(text_start, raw_bytes.len() as u32, text.is_ascii())
                    };
                    text_slices[arena_idx] = next_slice;
                    wrapping_text = text_style.get_overflow() != TextOverflow::Clip;
                }
                NodeKind::Input(input_state) => {
                    let sample: &str = if input_state.get_value().is_empty() {
                        input_state.get_placeholder().as_str()
                    } else {
                        input_state.get_value().as_str()
                    };
                    let raw_bytes: &[u8] = sample.as_bytes();
                    let prev_slice: SoaTextSlice = text_slices[arena_idx];
                    let prev_start: usize = prev_slice.get_byte_start() as usize;
                    let prev_len: usize = prev_slice.get_byte_len() as usize;
                    let next_slice: SoaTextSlice = if !force_full
                        && raw_bytes.len() <= prev_len
                        && prev_start.saturating_add(prev_len) <= text_bytes.len()
                    {
                        text_bytes[prev_start..prev_start + raw_bytes.len()]
                            .copy_from_slice(raw_bytes);
                        SoaTextSlice::new(
                            prev_slice.get_byte_start(),
                            raw_bytes.len() as u32,
                            sample.is_ascii(),
                        )
                    } else {
                        let text_start: u32 = text_bytes.len() as u32;
                        text_bytes.extend_from_slice(raw_bytes);
                        SoaTextSlice::new(text_start, raw_bytes.len() as u32, sample.is_ascii())
                    };
                    text_slices[arena_idx] = next_slice;
                    wrapping_text = text_style.get_overflow() != TextOverflow::Clip;
                }
                NodeKind::Image(img) => {
                    intrinsic_size = Size::new(img.get_width() as f32, img.get_height() as f32);
                    image_sizes[arena_idx] = intrinsic_size;
                    text_slices[arena_idx] = SoaTextSlice::default();
                }
                NodeKind::View
                | NodeKind::ScrollView
                | NodeKind::Portal
                | NodeKind::Fragment
                | NodeKind::Canvas(_) => {
                    text_slices[arena_idx] = SoaTextSlice::default();
                }
            }
            let p_bfs: u32 = parent_bfs[bfs_idx];
            let clip_ancestor_bfs: u32 = if p_bfs == GPU_LAYOUT_INDEX_NONE {
                GPU_LAYOUT_INDEX_NONE
            } else {
                let p_arena: usize = bfs_to_arena[p_bfs as usize] as usize;
                if matches!(
                    layout_styles[p_arena].get_overflow(),
                    Overflow::Hidden | Overflow::Scroll
                ) {
                    p_bfs
                } else {
                    gpu_visuals[p_bfs as usize].get_clip_ancestor_bfs()
                }
            };
            let scroll_layer_id: u32 = if p_bfs == GPU_LAYOUT_INDEX_NONE {
                0
            } else {
                gpu_visuals[p_bfs as usize].get_scroll_layer_id()
            };
            let next_input: GpuLayoutNodeInput = pack_gpu_layout_node_input(
                (p_bfs, child_first[bfs_idx], child_count[bfs_idx]),
                layout_style,
                kind_tag,
                (border_width, dirty_bits, intrinsic_size, wrapping_text),
            );
            if force_full || gpu_inputs[bfs_idx] != next_input {
                gpu_inputs[bfs_idx] = next_input;
                if !force_full {
                    input_dirty_spans.mark_element(bfs_idx, GPU_LAYOUT_NODE_INPUT_BYTES);
                }
            }
            let next_visual: GpuVisualStyleInput = pack_gpu_visual_style_input(
                paint_style,
                layout_style,
                clip_ancestor_bfs,
                scroll_layer_id,
            );
            if force_full || gpu_visuals[bfs_idx] != next_visual {
                gpu_visuals[bfs_idx] = next_visual;
                if !force_full {
                    visual_dirty_spans.mark_element(bfs_idx, GPU_VISUAL_STYLE_INPUT_BYTES);
                }
            }
            let cur_box: LayoutBox = layout_boxes[arena_idx];
            let bounds: Rect = cur_box.get_bounds();
            let content_bounds: Rect = cur_box.get_content_bounds();
            gpu_outputs[bfs_idx] = GpuLayoutNodeOutput {
                rect: [
                    bounds.get_x(),
                    bounds.get_y(),
                    bounds.get_width(),
                    bounds.get_height(),
                ],
                content_rect: [
                    content_bounds.get_x(),
                    content_bounds.get_y(),
                    content_bounds.get_width(),
                    content_bounds.get_height(),
                ],
            };
        }
        if force_full && bfs_len > 0 {
            input_dirty_spans.mark_range(0, bfs_len.saturating_mul(GPU_LAYOUT_NODE_INPUT_BYTES));
            visual_dirty_spans.mark_range(0, bfs_len.saturating_mul(GPU_VISUAL_STYLE_INPUT_BYTES));
        }
        *synced_revision = tree_rev;
        *synced_topology_revision = tree_topo_rev;
        *synced_serial_epoch = tree_serial_epoch;
        let sync_mode: SoaSyncMode = if force_full {
            SoaSyncMode::FullRebuild
        } else {
            SoaSyncMode::Incremental
        };
        *last_sync_mode = sync_mode;
        sync_mode
    }

    /// Mirrors updated arena-indexed `layout_boxes` into BFS-ordered `gpu_outputs` for downstream GPU indirect rendering.
    pub fn sync_gpu_outputs_from_boxes(&mut self) {
        let Self {
            topology,
            layout_boxes,
            gpu_outputs,
            ..
        } = self;
        let bfs_to_arena: &[u32] = topology.get_bfs_to_arena().as_slice();
        if gpu_outputs.len() != bfs_to_arena.len() {
            gpu_outputs.resize(bfs_to_arena.len(), GpuLayoutNodeOutput::default());
        }
        for (bfs_idx, &arena_u32) in bfs_to_arena.iter().enumerate() {
            let cur_box: LayoutBox = layout_boxes[arena_u32 as usize];
            let bounds: Rect = cur_box.get_bounds();
            let content_bounds: Rect = cur_box.get_content_bounds();
            gpu_outputs[bfs_idx] = GpuLayoutNodeOutput {
                rect: [
                    bounds.get_x(),
                    bounds.get_y(),
                    bounds.get_width(),
                    bounds.get_height(),
                ],
                content_rect: [
                    content_bounds.get_x(),
                    content_bounds.get_y(),
                    content_bounds.get_width(),
                    content_bounds.get_height(),
                ],
            };
        }
    }

    /// Exports this synchronized `SceneLayoutSoa` directly into a `GpuComputeSceneInput` sharing the exact unified `GpuLayoutNodeInput` and `GpuVisualStyleInput` ABI.
    ///
    /// # Arguments
    ///
    /// - `f32` - Physical viewport width in pixels.
    /// - `f32` - Physical viewport height in pixels.
    /// - `f32` - Simulation frame delta time in seconds.
    ///
    /// # Returns
    ///
    /// - `GpuComputeSceneInput` - Ready-to-dispatch compute layout scene mirroring `topology` and `gpu_visuals`.
    #[must_use]
    pub fn to_gpu_compute_scene(
        &self,
        viewport_width: f32,
        viewport_height: f32,
        dt_secs: f32,
    ) -> GpuComputeSceneInput {
        let bfs_to_arena: &[u32] = self.get_topology().get_bfs_to_arena().as_slice();
        let node_count: usize = bfs_to_arena.len();
        let mut nodes: Vec<GpuLayoutNodeInput> = Vec::with_capacity(node_count);
        for (bfs_idx, &arena_u32) in bfs_to_arena.iter().enumerate() {
            let mut input: GpuLayoutNodeInput = self
                .get_gpu_inputs()
                .get(bfs_idx)
                .copied()
                .unwrap_or_default();
            let style: LayoutStyle = self
                .get_layout_styles()
                .get(arena_u32 as usize)
                .copied()
                .unwrap_or_default();
            let mode: GpuLayoutMode = match style.get_display() {
                Display::None | Display::Block => GpuLayoutMode::Block,
                Display::Grid => GpuLayoutMode::Grid,
                Display::Flex => match style.get_flex_direction() {
                    FlexDirection::Row | FlexDirection::RowReverse => GpuLayoutMode::FlexRow,
                    FlexDirection::Column | FlexDirection::ColumnReverse => {
                        GpuLayoutMode::FlexColumn
                    }
                },
            };
            let justify: GpuJustifyMode = match style.get_justify_content() {
                JustifyContent::Start => GpuJustifyMode::Start,
                JustifyContent::Center => GpuJustifyMode::Center,
                JustifyContent::End => GpuJustifyMode::End,
                JustifyContent::SpaceBetween
                | JustifyContent::SpaceAround
                | JustifyContent::SpaceEvenly => GpuJustifyMode::SpaceBetween,
            };
            let align: GpuAlignMode = match style.get_align_items() {
                AlignItems::Start => GpuAlignMode::Start,
                AlignItems::Center => GpuAlignMode::Center,
                AlignItems::End => GpuAlignMode::End,
                AlignItems::Stretch => GpuAlignMode::Stretch,
            };
            let visible: bool = style.get_display() != Display::None;
            let clips: bool = matches!(style.get_overflow(), Overflow::Hidden | Overflow::Scroll);
            let visual_color: u32 = self
                .get_gpu_visuals()
                .get(bfs_idx)
                .map_or(0, GpuVisualStyleInput::get_color_rgba);
            let emit_visual: bool = visible && (visual_color >> 24) > 0;
            input.set_flags_kind(pack_gpu_layout_flags(
                mode,
                justify,
                align,
                visible,
                clips,
                emit_visual,
            ));
            nodes.push(input);
        }
        let safe_w: f32 = viewport_width.max(1.0);
        let safe_h: f32 = viewport_height.max(1.0);
        GpuComputeSceneInput {
            nodes,
            visuals: self.get_gpu_visuals().clone(),
            level_offsets: self.get_topology().get_level_offsets().clone(),
            viewport_size: [safe_w, safe_h],
            root_boundary_rect: [0.0, 0.0, safe_w, safe_h],
            dt_secs: if dt_secs.is_finite() && dt_secs > 0.0 {
                dt_secs
            } else {
                1.0 / 120.0
            },
            pick_point: None,
            clear_color: Color::rgba(0, 0, 0, 0),
        }
    }
}