Skip to main content

euv_core/layout/engine/
impl.rs

1use super::*;
2
3/// Core layout solver, split cache management, and spatial hit-testing operations for `LayoutEngine`.
4impl LayoutEngine {
5    /// Computes layout for the entire `tree` within `viewport`, skipping clean cached subtrees.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Mutable layout engine.
10    /// - `&mut SceneTree` - Retained scene tree to lay out.
11    /// - `Size` - Logical viewport dimensions.
12    ///
13    /// # Returns
14    ///
15    /// - `LayoutStats` - Computed vs cached subtree counts.
16    pub fn compute(&mut self, tree: &mut SceneTree, viewport: Size) -> LayoutStats {
17        let Self {
18            track_damage,
19            damage_fallback,
20            layout_snapshots,
21            ..
22        } = self;
23        *track_damage = false;
24        *damage_fallback = LAYOUT_FALLBACK_NONE;
25        layout_snapshots.clear();
26        if layout_snapshots.capacity() < DIRTY_PAINT_FULL_THRESHOLD {
27            layout_snapshots.reserve(DIRTY_PAINT_FULL_THRESHOLD);
28        }
29        self.compute_inner(tree, viewport)
30    }
31
32    /// Computes layout for `tree` while recording pre/post-layout conservative bounds diffs into a tight `LayoutDamageReport`.
33    ///
34    /// # Arguments
35    ///
36    /// - `&Self` - Mutable layout engine.
37    /// - `&mut SceneTree` - Retained scene tree to lay out.
38    /// - `Size` - Logical viewport dimensions.
39    /// - `f32` - Active display scale factor for outward-rounded physical damage rects.
40    ///
41    /// # Returns
42    ///
43    /// - `(LayoutStats, LayoutDamageReport)` - Layout pass stats and surgical physical damage or fallback cause.
44    pub(crate) fn compute_with_damage(
45        &mut self,
46        tree: &mut SceneTree,
47        viewport: Size,
48        scale: f32,
49    ) -> (LayoutStats, LayoutDamageReport) {
50        {
51            let Self {
52                track_damage,
53                damage_fallback,
54                layout_snapshots,
55                split_cache,
56                ..
57            } = self;
58            *track_damage = true;
59            *damage_fallback = LAYOUT_FALLBACK_NONE;
60            layout_snapshots.clear();
61            split_cache.begin_snapshot_pass();
62        }
63        let stats: LayoutStats = self.compute_inner(tree, viewport);
64        let fallback_after: u8 = {
65            let Self {
66                track_damage,
67                damage_fallback,
68                ..
69            } = self;
70            *track_damage = false;
71            *damage_fallback
72        };
73        if fallback_after != LAYOUT_FALLBACK_NONE {
74            let Self {
75                layout_snapshots, ..
76            } = self;
77            layout_snapshots.clear();
78            return (
79                stats,
80                LayoutDamageReport {
81                    damage: DamageRegion::full(),
82                    fallback_kind: fallback_after,
83                },
84            );
85        }
86        let mut damage: DamageRegion = DamageRegion::default();
87        let mut final_fallback: u8 = LAYOUT_FALLBACK_NONE;
88        let Self {
89            layout_snapshots, ..
90        } = self;
91        for snap in layout_snapshots.iter().copied() {
92            let Some(node) = tree.get_node(snap.id) else {
93                continue;
94            };
95            let lbox: LayoutBox = node.get_layout_box();
96            let new_bounds: Rect = lbox.get_bounds();
97            let new_content_bounds: Rect = lbox.get_content_bounds();
98            let new_content_size: Size = lbox.get_content_size();
99            let bounds_changed: bool = !Self::rect_approx_eq(snap.old_bounds, new_bounds);
100            let content_changed: bool =
101                !Self::rect_approx_eq(snap.old_content_bounds, new_content_bounds);
102            let is_scroll_box: bool =
103                node.style_ref().layout_ref().get_overflow() == Overflow::Scroll;
104            let scroll_content_changed: bool =
105                is_scroll_box && !Self::size_approx_eq(snap.old_content_size, new_content_size);
106            let geom_changed: bool = bounds_changed || content_changed;
107            if !geom_changed && !scroll_content_changed {
108                continue;
109            }
110            let is_portal_or_fixed: bool = matches!(node.get_kind(), NodeKind::Portal)
111                || node.style_ref().layout_ref().get_position() == Position::Fixed;
112            if is_portal_or_fixed {
113                final_fallback = LAYOUT_FALLBACK_PORTAL;
114                break;
115            }
116            if snap.has_old_screen {
117                damage.add_rect(SceneTree::scale_logical_to_phys_rect(
118                    snap.old_screen,
119                    scale,
120                ));
121            }
122            if new_bounds.get_width() > 0.0 && new_bounds.get_height() > 0.0 {
123                match tree.node_conservative_logical_rect(snap.id) {
124                    Some(new_screen) => {
125                        damage.add_rect(SceneTree::scale_logical_to_phys_rect(new_screen, scale));
126                    }
127                    None => {
128                        final_fallback = LAYOUT_FALLBACK_UNSAFE;
129                        break;
130                    }
131                }
132            }
133        }
134        layout_snapshots.clear();
135        if final_fallback != LAYOUT_FALLBACK_NONE {
136            return (
137                stats,
138                LayoutDamageReport {
139                    damage: DamageRegion::full(),
140                    fallback_kind: final_fallback,
141                },
142            );
143        }
144        (
145            stats,
146            LayoutDamageReport {
147                damage,
148                fallback_kind: LAYOUT_FALLBACK_NONE,
149            },
150        )
151    }
152
153    /// Executes the core layout traversal over `tree` using the current `track_damage` mode.
154    ///
155    /// # Arguments
156    ///
157    /// - `&Self` - Mutable layout engine.
158    /// - `&mut SceneTree` - Retained scene tree to lay out.
159    /// - `Size` - Logical viewport dimensions.
160    ///
161    /// # Returns
162    ///
163    /// - `LayoutStats` - Computed vs cached subtree counts.
164    fn compute_inner(&mut self, tree: &mut SceneTree, viewport: Size) -> LayoutStats {
165        let root_id: NodeId = tree.get_root();
166        let space: AvailableSpace = AvailableSpace::root(viewport);
167        let mut stats: LayoutStats = LayoutStats::default();
168        {
169            let Self {
170                split_cache,
171                last_split_stats,
172                ..
173            } = self;
174            split_cache.begin_pass();
175            *last_split_stats = SplitCacheStats::default();
176        }
177        self.get_mut_children_scratch().clear();
178        self.get_mut_flow_scratch().clear();
179        self.get_mut_abs_scratch().clear();
180        self.get_mut_flex_items_scratch().clear();
181        self.get_mut_flex_lines_scratch().clear();
182        self.get_mut_translate_scratch().clear();
183        let _: (Size, u8, f32) = self.layout_node_mode(
184            tree,
185            root_id,
186            space,
187            LayoutRunMode::PerformLayout,
188            &mut stats,
189        );
190        debug_assert!(self.get_children_scratch().is_empty());
191        debug_assert!(self.get_flow_scratch().is_empty());
192        debug_assert!(self.get_abs_scratch().is_empty());
193        debug_assert!(self.get_flex_items_scratch().is_empty());
194        debug_assert!(self.get_flex_lines_scratch().is_empty());
195        debug_assert!(self.get_mut_translate_scratch().is_empty());
196        {
197            let Self { split_cache, .. } = self;
198            split_cache.mark_synced(root_id, tree.get_revision());
199        }
200        self.set_last_stats(stats);
201        let invalidations: u64 = tree.get_layout_invalidations();
202        let changed_now: u64 = stats.get_nodes_changed() as u64;
203        let telemetry: &mut LayoutTelemetry = self.get_mut_telemetry();
204        telemetry.set_invalidations(invalidations);
205        telemetry.set_passes(telemetry.get_passes().saturating_add(1));
206        if changed_now > 0 {
207            telemetry.set_changed_passes(telemetry.get_changed_passes().saturating_add(1));
208            telemetry.set_changed_nodes_total(
209                telemetry
210                    .get_changed_nodes_total()
211                    .saturating_add(changed_now),
212            );
213        }
214        stats
215    }
216
217    /// Returns cumulative `LayoutTelemetry` counters (`invalidations`, `passes`, `changed_passes`, `changed_nodes_total`).
218    ///
219    /// # Arguments
220    ///
221    /// - `&Self` - Layout engine reference.
222    ///
223    /// # Returns
224    ///
225    /// - `LayoutTelemetry` - Cumulative layout telemetry snapshot.
226    #[must_use]
227    pub fn layout_telemetry(&self) -> LayoutTelemetry {
228        self.get_telemetry()
229    }
230
231    /// Resets cumulative `LayoutTelemetry` counters to zero.
232    ///
233    /// # Arguments
234    ///
235    /// - `&Self` - Mutable layout engine.
236    pub fn reset_telemetry(&mut self) {
237        self.set_telemetry(LayoutTelemetry::default());
238    }
239
240    /// Returns per-pass split measure/final layout cache and interval text cache diagnostics.
241    ///
242    /// # Arguments
243    ///
244    /// - `&Self` - Layout engine reference.
245    ///
246    /// # Returns
247    ///
248    /// - `SplitCacheStats` - Split cache hit/miss diagnostics from the most recent layout pass.
249    #[must_use]
250    pub fn split_cache_stats(&self) -> SplitCacheStats {
251        let Self {
252            last_split_stats, ..
253        } = self;
254        *last_split_stats
255    }
256
257    /// Returns the cached spatial `subtree_bounds` computed for `node_id`, if valid.
258    ///
259    /// # Arguments
260    ///
261    /// - `&Self` - Layout engine reference.
262    /// - `NodeId` - Target scene node handle.
263    ///
264    /// # Returns
265    ///
266    /// - `Option<Rect>` - Cached subtree visual/interactive bounding box in root logical coordinates.
267    #[must_use]
268    pub fn subtree_bounds(&self, node_id: NodeId) -> Option<Rect> {
269        let Self { split_cache, .. } = self;
270        split_cache.subtree_bounds_for(node_id)
271    }
272
273    /// Performs zero-allocation spatial hit-testing accelerated by cached `subtree_bounds` and `has_nonzero_z_child`.
274    ///
275    /// # Arguments
276    ///
277    /// - `&Self` - Layout engine reference owning the spatial cache.
278    /// - `&SceneTree` - Retained scene tree after layout.
279    /// - `Point` - Logical pointer coordinates in root space.
280    ///
281    /// # Returns
282    ///
283    /// - `Option<NodeId>` - Topmost matching node handle, if any.
284    #[must_use]
285    pub fn hit_test(&self, tree: &SceneTree, point: Point) -> Option<NodeId> {
286        let mut visited: usize = 0;
287        let Self { split_cache, .. } = self;
288        hit_test_with_cache(tree, point, Some(split_cache), &mut visited)
289    }
290
291    /// Performs zero-allocation spatial hit-testing and also returns the number of inspected scene nodes.
292    ///
293    /// # Arguments
294    ///
295    /// - `&Self` - Layout engine reference owning the spatial cache.
296    /// - `&SceneTree` - Retained scene tree after layout.
297    /// - `Point` - Logical pointer coordinates in root space.
298    ///
299    /// # Returns
300    ///
301    /// - `(Option<NodeId>, usize)` - Pair of `(topmost_hit, nodes_visited)`.
302    #[must_use]
303    pub fn hit_test_with_visited(&self, tree: &SceneTree, point: Point) -> (Option<NodeId>, usize) {
304        let mut visited: usize = 0;
305        let Self { split_cache, .. } = self;
306        let hit: Option<NodeId> = hit_test_with_cache(tree, point, Some(split_cache), &mut visited);
307        (hit, visited)
308    }
309
310    /// Records the first pre-layout geometry snapshot of `node_id` in O(1) using generation-stamped deduplication.
311    ///
312    /// # Arguments
313    ///
314    /// - `&Self` - Mutable layout engine.
315    /// - `&SceneTree` - Retained scene tree prior to writing `node_id`'s updated layout box.
316    /// - `NodeId` - Target node handle about to be mutated.
317    #[inline]
318    fn record_layout_snapshot(&mut self, tree: &SceneTree, node_id: NodeId) {
319        let Self {
320            track_damage,
321            damage_fallback,
322            layout_snapshots,
323            split_cache,
324            ..
325        } = self;
326        if !*track_damage || *damage_fallback != LAYOUT_FALLBACK_NONE {
327            return;
328        }
329        if split_cache.is_snapshot_seen(node_id) {
330            return;
331        }
332        if layout_snapshots.len() >= DIRTY_PAINT_FULL_THRESHOLD {
333            *damage_fallback = LAYOUT_FALLBACK_OVERFLOW;
334            return;
335        }
336        let Some(node) = tree.get_node(node_id) else {
337            return;
338        };
339        let lbox: LayoutBox = node.get_layout_box();
340        let old_bounds: Rect = lbox.get_bounds();
341        let old_content_bounds: Rect = lbox.get_content_bounds();
342        let old_content_size: Size = lbox.get_content_size();
343        let (has_old_screen, old_screen): (bool, Rect) =
344            if old_bounds.get_width() > 0.0 && old_bounds.get_height() > 0.0 {
345                match tree.node_conservative_logical_rect(node_id) {
346                    Some(rect) => (true, rect),
347                    None => {
348                        *damage_fallback = LAYOUT_FALLBACK_UNSAFE;
349                        return;
350                    }
351                }
352            } else {
353                (false, Rect::default())
354            };
355        split_cache.mark_snapshot_seen(node_id);
356        layout_snapshots.push(LayoutNodeSnapshot {
357            id: node_id,
358            old_bounds,
359            old_content_bounds,
360            old_content_size,
361            has_old_screen,
362            old_screen,
363        });
364    }
365
366    /// Returns `true` when two layout rectangles are equal within subpixel tolerance.
367    ///
368    /// # Arguments
369    ///
370    /// - `Rect` - First rectangle.
371    /// - `Rect` - Second rectangle.
372    ///
373    /// # Returns
374    ///
375    /// - `bool` - Whether position and dimensions match within `0.001` logical pixels.
376    #[inline]
377    fn rect_approx_eq(a: Rect, b: Rect) -> bool {
378        (a.get_x() - b.get_x()).abs() <= 0.001
379            && (a.get_y() - b.get_y()).abs() <= 0.001
380            && (a.get_width() - b.get_width()).abs() <= 0.001
381            && (a.get_height() - b.get_height()).abs() <= 0.001
382    }
383
384    /// Returns `true` when `length` depends on the root viewport dimensions (`vw` or `vh`).
385    ///
386    /// # Arguments
387    ///
388    /// - `Length` - Length value to classify.
389    ///
390    /// # Returns
391    ///
392    /// - `bool` - `true` when `length` is `Length::ViewportWidth` or `Length::ViewportHeight`.
393    #[inline(always)]
394    fn is_viewport_length(length: Length) -> bool {
395        matches!(length, Length::ViewportWidth(_)) || matches!(length, Length::ViewportHeight(_))
396    }
397
398    /// Returns `true` when two layout sizes are equal within subpixel tolerance.
399    ///
400    /// # Arguments
401    ///
402    /// - `Size` - First size.
403    /// - `Size` - Second size.
404    ///
405    /// # Returns
406    ///
407    /// - `bool` - Whether width and height match within `0.001` logical pixels.
408    #[inline]
409    fn size_approx_eq(a: Size, b: Size) -> bool {
410        (a.get_width() - b.get_width()).abs() <= 0.001
411            && (a.get_height() - b.get_height()).abs() <= 0.001
412    }
413
414    /// Measures text bounding dimensions via per-node cached 128-bit hashes and the interval-aware `TextSizeCache`.
415    ///
416    /// # Arguments
417    ///
418    /// - `&Self` - Mutable layout engine reference.
419    /// - `NodeId` - Target text or input node handle.
420    /// - `&str` - UTF-8 text content to measure.
421    /// - `TextStyle` - Active typography style.
422    /// - `Option<f32>` - Optional maximum wrap width in logical pixels.
423    /// - `bool` - Whether `DIRTY_TEXT` is set on the node.
424    ///
425    /// # Returns
426    ///
427    /// - `TextSizeMeasurement` - Exact measured bounding dimensions and wrap-interval metadata.
428    fn measure_node_text_cached(
429        &mut self,
430        node_id: NodeId,
431        text: &str,
432        style: TextStyle,
433        max_width: Option<f32>,
434        dirty_text: bool,
435    ) -> TextSizeMeasurement {
436        let measurer: DeterministicTextMeasurer = self.get_measurer();
437        let Self {
438            text_size_cache,
439            split_cache,
440            last_split_stats,
441            ..
442        } = self;
443        let Some((hash_a, hash_b, text_len, reused_hash)) =
444            split_cache.text_hash_for_node(node_id, text, dirty_text)
445        else {
446            let measured: Size = measurer.measure_size(text, style, max_width);
447            return TextSizeMeasurement {
448                size: measured,
449                unwrapped: false,
450                max_content_w: f32::INFINITY,
451                cache_hit: false,
452            };
453        };
454        if reused_hash {
455            last_split_stats.text_hash_reuses = last_split_stats.text_hash_reuses.saturating_add(1);
456        }
457        let result: TextSizeMeasurement = text_size_cache.get_or_measure_hashed(
458            text,
459            (hash_a, hash_b, text_len),
460            style,
461            max_width,
462            |raw: &str, text_style: TextStyle, limit: Option<f32>| {
463                measurer.measure_size(raw, text_style, limit)
464            },
465        );
466        if result.cache_hit {
467            last_split_stats.text_interval_hits =
468                last_split_stats.text_interval_hits.saturating_add(1);
469        }
470        result
471    }
472
473    /// Computes or retrieves cached layout for `node_id` in either `ComputeSize` (measure) or `PerformLayout` (final) mode.
474    ///
475    /// # Arguments
476    ///
477    /// - `&Self` - Mutable layout engine reference.
478    /// - `&mut SceneTree` - Mutable scene tree.
479    /// - `NodeId` - Node handle to measure or lay out.
480    /// - `AvailableSpace` - Parent space constraint and origin.
481    /// - `LayoutRunMode` - `ComputeSize` probe vs `PerformLayout` placement mode.
482    /// - `&mut LayoutStats` - Mutable telemetry counters.
483    ///
484    /// # Returns
485    ///
486    /// - `(Size, u8, f32)` - Computed border-box size, dependency mask (`LAYOUT_DEP_*`), and invariant `min_avail_w`.
487    fn layout_node_mode(
488        &mut self,
489        tree: &mut SceneTree,
490        node_id: NodeId,
491        space: AvailableSpace,
492        mode: LayoutRunMode,
493        stats: &mut LayoutStats,
494    ) -> (Size, u8, f32) {
495        let is_dirty: bool = match tree.get_node(node_id) {
496            Some(node) => node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK),
497            None => return (Size::default(), LAYOUT_DEP_NONE, 0.0),
498        };
499        let (slot_idx, content_gen): (usize, u32) = {
500            let Self { split_cache, .. } = self;
501            split_cache.prepare_node(node_id, is_dirty)
502        };
503        if mode == LayoutRunMode::ComputeSize {
504            let measure_hit: Option<(Size, u8, f32)> = {
505                let Self { split_cache, .. } = self;
506                split_cache.lookup_measure(slot_idx, space, content_gen)
507            };
508            if let Some(hit) = measure_hit {
509                let Self {
510                    last_split_stats, ..
511                } = self;
512                last_split_stats.measure_hits = last_split_stats.measure_hits.saturating_add(1);
513                stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
514                return hit;
515            }
516            if !is_dirty {
517                let final_hit: Option<FinalLayoutSlot> = {
518                    let Self { split_cache, .. } = self;
519                    split_cache.lookup_final(slot_idx, content_gen)
520                };
521                if let Some(fslot) = final_hit
522                    && !fslot.hidden
523                    && fslot.space.can_reuse(space)
524                {
525                    let Self {
526                        last_split_stats, ..
527                    } = self;
528                    last_split_stats.measure_hits = last_split_stats.measure_hits.saturating_add(1);
529                    stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
530                    return (fslot.size, fslot.dep_flags, fslot.min_avail_w);
531                }
532            }
533            {
534                let Self {
535                    last_split_stats, ..
536                } = self;
537                last_split_stats.measure_misses = last_split_stats.measure_misses.saturating_add(1);
538            }
539            stats.set_nodes_computed(stats.get_nodes_computed() + 1);
540        } else {
541            if !is_dirty {
542                let final_hit: Option<FinalLayoutSlot> = {
543                    let Self { split_cache, .. } = self;
544                    split_cache.lookup_final(slot_idx, content_gen)
545                };
546                if let Some(fslot) = final_hit
547                    && fslot.space.can_reuse(space)
548                {
549                    if fslot.hidden {
550                        let Self {
551                            last_split_stats, ..
552                        } = self;
553                        last_split_stats.final_hits = last_split_stats.final_hits.saturating_add(1);
554                        stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
555                        return (Size::default(), LAYOUT_DEP_NONE, 0.0);
556                    }
557                    if !fslot.space.same_origin(space) {
558                        let dx: f32 = space.get_origin_x() - fslot.space.get_origin_x();
559                        let dy: f32 = space.get_origin_y() - fslot.space.get_origin_y();
560                        self.translate_subtree(tree, node_id, dx, dy);
561                        if dx.abs() > 0.001 || dy.abs() > 0.001 {
562                            stats.set_nodes_changed(stats.get_nodes_changed().saturating_add(1));
563                        }
564                    }
565                    if fslot.post_stretched {
566                        let restored_opt: Option<(Rect, Rect, Size)> = {
567                            let Self { split_cache, .. } = self;
568                            split_cache.lookup_final(slot_idx, content_gen).map(
569                                |s: FinalLayoutSlot| (s.bounds, s.content_bounds, s.content_size),
570                            )
571                        };
572                        if let Some((r_bounds, r_content, r_csize)) = restored_opt {
573                            self.record_layout_snapshot(tree, node_id);
574                            if let Some(node) = tree.get_node_mut(node_id) {
575                                node.get_mut_layout_box().set_bounds(r_bounds);
576                                node.get_mut_layout_box().set_content_bounds(r_content);
577                                node.get_mut_layout_box().set_content_size(r_csize);
578                            }
579                            let Self { split_cache, .. } = self;
580                            if let Some(slot_mut) = split_cache.final_slots[slot_idx].as_mut() {
581                                slot_mut.post_stretched = false;
582                            }
583                        }
584                    }
585                    let Self {
586                        last_split_stats, ..
587                    } = self;
588                    last_split_stats.final_hits = last_split_stats.final_hits.saturating_add(1);
589                    stats.set_subtrees_skipped(stats.get_subtrees_skipped() + 1);
590                    return (fslot.size, fslot.dep_flags, fslot.min_avail_w);
591                }
592            }
593            {
594                let Self {
595                    last_split_stats, ..
596                } = self;
597                last_split_stats.final_misses = last_split_stats.final_misses.saturating_add(1);
598            }
599            stats.set_nodes_computed(stats.get_nodes_computed() + 1);
600        }
601        let Some(node) = tree.get_node(node_id) else {
602            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
603        };
604        let style_ref: &Style = node.style_ref();
605        let Style {
606            layout: layout_ref,
607            paint: paint_ref,
608            text: text_ref,
609        } = style_ref;
610        if layout_ref.get_display() == Display::None {
611            {
612                let Self {
613                    last_split_stats, ..
614                } = self;
615                last_split_stats.display_none_skips =
616                    last_split_stats.display_none_skips.saturating_add(1);
617            }
618            if mode == LayoutRunMode::ComputeSize {
619                let Self { split_cache, .. } = self;
620                split_cache.store_measure(
621                    slot_idx,
622                    space,
623                    LayoutRunMode::ComputeSize,
624                    content_gen,
625                    (Size::default(), LAYOUT_DEP_NONE, 0.0),
626                );
627                return (Size::default(), LAYOUT_DEP_NONE, 0.0);
628            }
629            self.record_layout_snapshot(tree, node_id);
630            let (prev_content_size, had_subtree_dirty): (Size, bool) =
631                if let Some(hidden_node) = tree.get_node_mut(node_id) {
632                    let old_b: Rect = hidden_node.get_layout_box().get_bounds();
633                    let csize: Size = hidden_node.get_layout_box().get_content_size();
634                    let sub_dirty: bool = hidden_node.get_dirty().intersects(DIRTY_SUBTREE_LAYOUT);
635                    if !Self::rect_approx_eq(old_b, Rect::default()) {
636                        stats.set_nodes_changed(stats.get_nodes_changed().saturating_add(1));
637                    }
638                    hidden_node.get_mut_layout_box().set_bounds(Rect::default());
639                    hidden_node
640                        .get_mut_layout_box()
641                        .set_content_bounds(Rect::default());
642                    hidden_node.set_last_constraint(Some(space));
643                    hidden_node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
644                    (csize, sub_dirty)
645                } else {
646                    (Size::default(), false)
647                };
648            if let Some(meta) = tree.get_mut_meta().get_mut(node_id.as_usize()) {
649                let next_dirty: u16 = meta.get_dirty() & !DIRTY_LAYOUT_PASS_MASK;
650                let _: &mut NodeMeta = meta.set_dirty(next_dirty);
651            }
652            if had_subtree_dirty {
653                tree.set_has_stale_hidden_dirty(true);
654            }
655            let Self { split_cache, .. } = self;
656            split_cache.store_final(
657                slot_idx,
658                FinalLayoutSlot {
659                    space,
660                    subtree_gen: content_gen,
661                    size: Size::default(),
662                    bounds: Rect::default(),
663                    content_bounds: Rect::default(),
664                    content_size: prev_content_size,
665                    dep_flags: LAYOUT_DEP_NONE,
666                    min_avail_w: 0.0,
667                    post_stretched: false,
668                    hidden: true,
669                },
670            );
671            split_cache.store_subtree_meta(slot_idx, Rect::default(), false);
672            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
673        }
674        let w_len: Length = layout_ref.get_width();
675        let h_len: Length = layout_ref.get_height();
676        let min_w_len: Length = layout_ref.get_min_width();
677        let max_w_len: Length = layout_ref.get_max_width();
678        let min_h_len: Length = layout_ref.get_min_height();
679        let max_h_len: Length = layout_ref.get_max_height();
680        let mut own_deps: u8 = LAYOUT_DEP_NONE;
681        if matches!(w_len, Length::Percent(_))
682            || matches!(min_w_len, Length::Percent(_))
683            || matches!(max_w_len, Length::Percent(_))
684        {
685            own_deps |= LAYOUT_DEP_AVAIL_W;
686        }
687        if matches!(h_len, Length::Percent(_))
688            || matches!(min_h_len, Length::Percent(_))
689            || matches!(max_h_len, Length::Percent(_))
690        {
691            own_deps |= LAYOUT_DEP_AVAIL_H;
692        }
693        if Self::is_viewport_length(w_len)
694            || Self::is_viewport_length(h_len)
695            || Self::is_viewport_length(min_w_len)
696            || Self::is_viewport_length(max_w_len)
697            || Self::is_viewport_length(min_h_len)
698            || Self::is_viewport_length(max_h_len)
699        {
700            own_deps |= LAYOUT_DEP_VIEWPORT;
701        }
702        let padding: Edges = layout_ref.get_padding();
703        let border_w: f32 = paint_ref.get_border().get_width();
704        let node_transform: Transform2D = paint_ref.get_transform();
705        let node_scroll: Point = node.get_layout_box().get_scroll_offset();
706        let self_is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
707            || layout_ref.get_position() == Position::Fixed;
708        let chrome_h: f32 = padding.horizontal() + border_w * 2.0;
709        let chrome_v: f32 = padding.vertical() + border_w * 2.0;
710        let explicit_w: Option<f32> = w_len.resolve(space.get_width(), space.get_viewport());
711        let explicit_h: Option<f32> = h_len.resolve(space.get_height(), space.get_viewport());
712        let mut resolved_w: Option<f32> = explicit_w;
713        let mut resolved_h: Option<f32> = explicit_h;
714        let stretched_w: bool = resolved_w.is_none() && space.get_stretch_width();
715        let stretched_h: bool = resolved_h.is_none() && space.get_stretch_height();
716        if stretched_w {
717            resolved_w = Some(space.get_width());
718            own_deps |= LAYOUT_DEP_AVAIL_W;
719        }
720        if stretched_h {
721            resolved_h = Some(space.get_height());
722            own_deps |= LAYOUT_DEP_AVAIL_H;
723        }
724        let min_w: f32 = min_w_len
725            .resolve(space.get_width(), space.get_viewport())
726            .unwrap_or(0.0);
727        let min_h: f32 = min_h_len
728            .resolve(space.get_height(), space.get_viewport())
729            .unwrap_or(0.0);
730        let max_w: f32 = max_w_len
731            .resolve(space.get_width(), space.get_viewport())
732            .unwrap_or(f32::INFINITY)
733            .max(min_w);
734        let max_h: f32 = max_h_len
735            .resolve(space.get_height(), space.get_viewport())
736            .unwrap_or(f32::INFINITY)
737            .max(min_h);
738        let aspect_ratio: Option<f32> = layout_ref.aspect_ratio_value();
739        if let Some(ratio) = aspect_ratio
740            && ratio > 0.0
741        {
742            if let Some(w) = resolved_w
743                && resolved_h.is_none()
744            {
745                resolved_h = Some(w.clamp(min_w, max_w) / ratio);
746            } else if let Some(h) = resolved_h
747                && resolved_w.is_none()
748            {
749                resolved_w = Some(h.clamp(min_h, max_h) * ratio);
750            }
751        }
752        let node_overflow: Overflow = layout_ref.get_overflow();
753        let node_flex_grow: f32 = layout_ref.get_flex_grow();
754        let width_independent: bool = explicit_w.is_some()
755            || (stretched_w
756                && resolved_w.is_some()
757                && (node_overflow != Overflow::Visible || node_flex_grow > 0.0));
758        let height_independent: bool = resolved_h.is_some() && h_len != Length::Auto;
759        if mode == LayoutRunMode::ComputeSize && width_independent && resolved_h.is_some() {
760            let final_w: f32 = resolved_w.unwrap_or(0.0).clamp(min_w, max_w).max(0.0);
761            let final_h: f32 = resolved_h.unwrap_or(0.0).clamp(min_h, max_h).max(0.0);
762            let final_size: Size = Size::new(final_w, final_h);
763            let Self { split_cache, .. } = self;
764            split_cache.store_measure(
765                slot_idx,
766                space,
767                LayoutRunMode::ComputeSize,
768                content_gen,
769                (final_size, own_deps, 0.0),
770            );
771            return (final_size, own_deps, 0.0);
772        }
773        let avail_w_outer: f32 = resolved_w
774            .unwrap_or(space.get_width())
775            .max(min_w)
776            .min(max_w);
777        let avail_h_outer: f32 = resolved_h
778            .unwrap_or(space.get_height())
779            .max(min_h)
780            .min(max_h);
781        let inner_avail_w: f32 = (avail_w_outer - chrome_h).max(0.0);
782        let inner_avail_h: f32 = (avail_h_outer - chrome_v).max(0.0);
783        let origin_x: f32 = space.get_origin_x();
784        let origin_y: f32 = space.get_origin_y();
785        let content_origin_x: f32 = origin_x + padding.get_left() + border_w;
786        let content_origin_y: f32 = origin_y + padding.get_top() + border_w;
787        let shields_avail_w: bool = resolved_w.is_some() && (own_deps & LAYOUT_DEP_AVAIL_W) == 0;
788        let shields_avail_h: bool = resolved_h.is_some() && (own_deps & LAYOUT_DEP_AVAIL_H) == 0;
789        let skip_leaf_measure: bool =
790            node_overflow != Overflow::Scroll && width_independent && height_independent;
791        let dirty_text: bool = node.get_dirty().intersects(DIRTY_TEXT);
792        let mut child_range: Option<(usize, usize)> = None;
793        let mut child_deps: u8 = LAYOUT_DEP_NONE;
794        let mut child_min_aw: f32 = 0.0;
795        let leaf_content_size: Option<Size> = match node.get_kind() {
796            NodeKind::Text(text) => {
797                if skip_leaf_measure {
798                    Some(Size::new(inner_avail_w, inner_avail_h))
799                } else {
800                    let measured: TextSizeMeasurement = self.measure_node_text_cached(
801                        node_id,
802                        text.as_str(),
803                        *text_ref,
804                        Some(inner_avail_w.max(1.0)),
805                        dirty_text,
806                    );
807                    if text_ref.get_overflow() != TextOverflow::Clip {
808                        if measured.unwrapped && measured.max_content_w.is_finite() {
809                            child_min_aw = measured.max_content_w + 0.5;
810                        } else {
811                            child_deps |= LAYOUT_DEP_AVAIL_W;
812                        }
813                    }
814                    Some(measured.size)
815                }
816            }
817            NodeKind::Image(img) => {
818                Some(Size::new(img.get_width() as f32, img.get_height() as f32))
819            }
820            NodeKind::Input(input_state) => {
821                if skip_leaf_measure {
822                    Some(Size::new(inner_avail_w, inner_avail_h))
823                } else {
824                    let sample: &str = if input_state.get_value().is_empty() {
825                        input_state.get_placeholder().as_str()
826                    } else {
827                        input_state.get_value().as_str()
828                    };
829                    let measured: TextSizeMeasurement = self.measure_node_text_cached(
830                        node_id,
831                        sample,
832                        *text_ref,
833                        Some(inner_avail_w.max(1.0)),
834                        dirty_text,
835                    );
836                    if text_ref.get_overflow() != TextOverflow::Clip {
837                        if measured.unwrapped && measured.max_content_w.is_finite() {
838                            child_min_aw = measured.max_content_w + 0.5;
839                        } else {
840                            child_deps |= LAYOUT_DEP_AVAIL_W;
841                        }
842                    }
843                    Some(Size::new(
844                        measured.size.get_width().max(120.0),
845                        measured.size.get_height().max(20.0),
846                    ))
847                }
848            }
849            NodeKind::View
850            | NodeKind::ScrollView
851            | NodeKind::Portal
852            | NodeKind::Fragment
853            | NodeKind::Canvas(_) => {
854                if !tree.has_children(node_id) {
855                    Some(Size::default())
856                } else {
857                    let start: usize = self.get_children_scratch().len();
858                    self.get_mut_children_scratch()
859                        .extend(tree.children_iter(node_id));
860                    let end: usize = self.get_children_scratch().len();
861                    child_range = Some((start, end));
862                    None
863                }
864            }
865        };
866        let parent_layout_copy: LayoutStyle = *layout_ref;
867        let content_size: Size = if let Some(size) = leaf_content_size {
868            size
869        } else if let Some((child_start, child_end)) = child_range {
870            let min_inner_size: Size =
871                Size::new((min_w - chrome_h).max(0.0), (min_h - chrome_v).max(0.0));
872            let frame: ContainerFrame = ContainerFrame::new(
873                parent_layout_copy,
874                Size::new(inner_avail_w, inner_avail_h),
875                space.get_viewport(),
876                Point::new(content_origin_x, content_origin_y),
877                resolved_w.is_some(),
878                resolved_h.is_some(),
879                min_inner_size,
880            );
881            let (size, c_deps, c_min_aw): (Size, u8, f32) =
882                self.layout_children(tree, (child_start, child_end), frame, mode, stats);
883            child_deps = c_deps;
884            child_min_aw = c_min_aw;
885            if mode == LayoutRunMode::ComputeSize {
886                self.get_mut_children_scratch().truncate(child_start);
887            }
888            size
889        } else {
890            Size::default()
891        };
892        let content_outer_w: f32 = content_size.get_width() + chrome_h;
893        let content_outer_h: f32 = content_size.get_height() + chrome_v;
894        let mut final_w: f32 = match (explicit_w, stretched_w) {
895            (Some(w), _) => w,
896            (None, true) => {
897                let base_w: f32 = resolved_w.unwrap_or(content_outer_w);
898                if node_overflow == Overflow::Visible
899                    && node_flex_grow <= 0.0
900                    && content_outer_w > base_w + 0.5
901                {
902                    content_outer_w
903                } else {
904                    base_w
905                }
906            }
907            (None, false) => content_outer_w,
908        };
909        let mut final_h: f32 = resolved_h.unwrap_or(content_outer_h);
910        if let Some(ratio) = aspect_ratio
911            && ratio > 0.0
912        {
913            if resolved_w.is_some() && resolved_h.is_none() {
914                final_h = final_w / ratio;
915            } else if resolved_h.is_some() && resolved_w.is_none() {
916                final_w = final_h * ratio;
917            }
918        }
919        final_w = final_w.clamp(min_w, max_w).max(0.0);
920        final_h = final_h.clamp(min_h, max_h).max(0.0);
921        let final_size: Size = Size::new(final_w, final_h);
922        let mut final_deps: u8 = own_deps | (child_deps & LAYOUT_DEP_VIEWPORT);
923        let mut final_min_aw: f32 = 0.0;
924        if !shields_avail_w {
925            if (child_deps & LAYOUT_DEP_AVAIL_W) != 0 {
926                final_deps |= LAYOUT_DEP_AVAIL_W;
927            } else if child_min_aw > 0.0 {
928                final_min_aw = child_min_aw + chrome_h;
929            }
930        }
931        if !shields_avail_h {
932            final_deps |= child_deps & LAYOUT_DEP_AVAIL_H;
933        }
934        if mode == LayoutRunMode::ComputeSize {
935            let Self { split_cache, .. } = self;
936            split_cache.store_measure(
937                slot_idx,
938                space,
939                LayoutRunMode::ComputeSize,
940                content_gen,
941                (final_size, final_deps, final_min_aw),
942            );
943            return (final_size, final_deps, final_min_aw);
944        }
945        let bounds: Rect = Rect::new(origin_x, origin_y, final_w, final_h);
946        let content_bounds: Rect = Rect::new(
947            content_origin_x,
948            content_origin_y,
949            (final_w - chrome_h).max(0.0),
950            (final_h - chrome_v).max(0.0),
951        );
952        self.record_layout_snapshot(tree, node_id);
953        if let Some(node) = tree.get_node_mut(node_id) {
954            let prev_box: LayoutBox = node.get_layout_box();
955            let changed: bool = !Self::rect_approx_eq(prev_box.get_bounds(), bounds)
956                || !Self::rect_approx_eq(prev_box.get_content_bounds(), content_bounds)
957                || !Self::size_approx_eq(prev_box.get_content_size(), content_size);
958            if changed {
959                stats.set_nodes_changed(stats.get_nodes_changed().saturating_add(1));
960            }
961            node.get_mut_layout_box().set_bounds(bounds);
962            node.get_mut_layout_box().set_content_bounds(content_bounds);
963            node.get_mut_layout_box().set_content_size(content_size);
964            node.set_last_constraint(Some(space));
965            node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
966        }
967        if let Some(meta) = tree.get_mut_meta().get_mut(node_id.as_usize()) {
968            let next_dirty: u16 = meta.get_dirty() & !DIRTY_LAYOUT_PASS_MASK;
969            let _: &mut NodeMeta = meta.set_dirty(next_dirty);
970        }
971        let own_vis: Rect = shifted_node_bounds(bounds, Point::default(), node_transform);
972        let is_clipped: bool = matches!(node_overflow, Overflow::Hidden | Overflow::Scroll);
973        let mut sub_bounds: Rect = own_vis;
974        let mut has_nonzero_z: bool = false;
975        if let Some((c_start, c_end)) = child_range {
976            let tx: f32 = node_transform.get_translate_x() - node_scroll.get_x();
977            let ty: f32 = node_transform.get_translate_y() - node_scroll.get_y();
978            for idx in c_start..c_end {
979                let cid: NodeId = self.get_children_scratch()[idx];
980                if let Some(cnode) = tree.get_node(cid) {
981                    let clayout: &LayoutStyle = cnode.style_ref().layout_ref();
982                    if clayout.get_z_index() != 0 {
983                        has_nonzero_z = true;
984                    }
985                    let c_is_portal: bool = matches!(cnode.get_kind(), NodeKind::Portal)
986                        || clayout.get_position() == Position::Fixed;
987                    if !is_clipped
988                        && clayout.get_display() != Display::None
989                        && (self_is_portal || !c_is_portal)
990                    {
991                        let child_sb: Rect = {
992                            let Self { split_cache, .. } = self;
993                            split_cache.subtree_bounds_for(cid)
994                        }
995                        .unwrap_or_else(|| {
996                            shifted_node_bounds(
997                                cnode.get_layout_box().get_bounds(),
998                                Point::default(),
999                                cnode.style_ref().paint_ref().get_transform(),
1000                            )
1001                        });
1002                        if child_sb.get_width() > 0.0 && child_sb.get_height() > 0.0 {
1003                            let shifted_child: Rect = Rect::new(
1004                                child_sb.get_x() + tx,
1005                                child_sb.get_y() + ty,
1006                                child_sb.get_width(),
1007                                child_sb.get_height(),
1008                            );
1009                            sub_bounds = sub_bounds.union(shifted_child);
1010                        }
1011                    }
1012                }
1013            }
1014            self.get_mut_children_scratch().truncate(c_start);
1015        }
1016        let Self { split_cache, .. } = self;
1017        split_cache.store_final(
1018            slot_idx,
1019            FinalLayoutSlot {
1020                space,
1021                subtree_gen: content_gen,
1022                size: final_size,
1023                bounds,
1024                content_bounds,
1025                content_size,
1026                dep_flags: final_deps,
1027                min_avail_w: final_min_aw,
1028                post_stretched: false,
1029                hidden: false,
1030            },
1031        );
1032        if split_cache
1033            .lookup_measure(slot_idx, space, content_gen)
1034            .is_none()
1035        {
1036            split_cache.store_measure(
1037                slot_idx,
1038                space,
1039                LayoutRunMode::PerformLayout,
1040                content_gen,
1041                (final_size, final_deps, final_min_aw),
1042            );
1043        }
1044        split_cache.store_subtree_meta(slot_idx, sub_bounds, has_nonzero_z);
1045        (final_size, final_deps, final_min_aw)
1046    }
1047
1048    /// Lays out children according to Flex, Grid, or Block rules plus Absolute/Fixed overlays in `PerformLayout`.
1049    ///
1050    /// # Arguments
1051    ///
1052    /// - `&Self` - Mutable layout engine reference.
1053    /// - `&mut SceneTree` - Mutable scene tree.
1054    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `children_scratch`.
1055    /// - `ContainerFrame` - Parent layout constraints and origin.
1056    /// - `LayoutRunMode` - `ComputeSize` probe vs `PerformLayout` placement mode.
1057    /// - `&mut LayoutStats` - Mutable telemetry counters.
1058    ///
1059    /// # Returns
1060    ///
1061    /// - `(Size, u8, f32)` - Aggregate flow content size, dependency mask, and invariant `min_avail_w`.
1062    fn layout_children(
1063        &mut self,
1064        tree: &mut SceneTree,
1065        child_range: (usize, usize),
1066        frame: ContainerFrame,
1067        mode: LayoutRunMode,
1068        stats: &mut LayoutStats,
1069    ) -> (Size, u8, f32) {
1070        let (child_start, child_end): (usize, usize) = child_range;
1071        let child_count: usize = child_end.saturating_sub(child_start);
1072        if child_count == 0 {
1073            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
1074        }
1075        let parent_layout: LayoutStyle = frame.get_parent_layout();
1076        let inner_avail: Size = frame.get_inner_avail();
1077        let viewport: Size = frame.get_viewport();
1078        let content_origin: Point = frame.get_content_origin();
1079        let flex_dir_opt: Option<FlexDirection> = match parent_layout.get_display() {
1080            Display::Grid => None,
1081            Display::Block => Some(FlexDirection::Column),
1082            Display::Flex | Display::None => Some(parent_layout.get_flex_direction()),
1083        };
1084        let is_row_dir: bool = matches!(
1085            flex_dir_opt,
1086            Some(FlexDirection::Row | FlexDirection::RowReverse)
1087        );
1088        let is_reverse_dir: bool = matches!(
1089            flex_dir_opt,
1090            Some(FlexDirection::RowReverse | FlexDirection::ColumnReverse)
1091        );
1092        let parent_align: AlignItems = parent_layout.get_align_items();
1093        let parent_height_auto: bool = parent_layout.get_height() == Length::Auto;
1094        let mut single_pass_ok: bool = flex_dir_opt.is_some()
1095            && parent_layout.get_flex_wrap() != FlexWrap::Wrap
1096            && !is_reverse_dir
1097            && parent_layout.get_justify_content() == JustifyContent::Start;
1098        let flow_start: usize = self.get_flow_scratch().len();
1099        let abs_start: usize = self.get_abs_scratch().len();
1100        for idx in child_start..child_end {
1101            let child_id: NodeId = self.get_children_scratch()[idx];
1102            if let Some(child_node) = tree.get_node(child_id) {
1103                let Style {
1104                    layout: child_layout,
1105                    ..
1106                } = child_node.style_ref();
1107                if child_layout.get_display() == Display::None {
1108                    if mode == LayoutRunMode::PerformLayout {
1109                        let _: (Size, u8, f32) = self.layout_node_mode(
1110                            tree,
1111                            child_id,
1112                            AvailableSpace::new(0.0, 0.0, viewport, 0.0, 0.0),
1113                            LayoutRunMode::PerformLayout,
1114                            stats,
1115                        );
1116                    }
1117                    continue;
1118                }
1119                match child_layout.get_position() {
1120                    Position::Relative => {
1121                        if single_pass_ok {
1122                            if child_layout.get_flex_grow() > 0.0 {
1123                                single_pass_ok = false;
1124                            } else {
1125                                let align: AlignItems = match child_layout.get_align_self() {
1126                                    AlignSelf::Auto => parent_align,
1127                                    AlignSelf::Stretch => AlignItems::Stretch,
1128                                    AlignSelf::Start => AlignItems::Start,
1129                                    AlignSelf::Center => AlignItems::Center,
1130                                    AlignSelf::End => AlignItems::End,
1131                                };
1132                                let non_start_align: bool =
1133                                    matches!(align, AlignItems::Center | AlignItems::End);
1134                                let auto_row_stretch: bool = align == AlignItems::Stretch
1135                                    && is_row_dir
1136                                    && child_layout.get_height() == Length::Auto
1137                                    && (parent_height_auto
1138                                        || frame.get_min_inner_size().get_height() > 0.0);
1139                                if non_start_align || auto_row_stretch {
1140                                    single_pass_ok = false;
1141                                }
1142                            }
1143                        }
1144                        self.get_mut_flow_scratch().push(child_id);
1145                    }
1146                    Position::Absolute | Position::Fixed => {
1147                        if mode == LayoutRunMode::PerformLayout {
1148                            self.get_mut_abs_scratch().push(child_id);
1149                        }
1150                    }
1151                }
1152            }
1153        }
1154        let flow_end: usize = self.get_flow_scratch().len();
1155        let abs_end: usize = self.get_abs_scratch().len();
1156        let flow_result: (Size, u8, f32) = if let Some(flex_dir) = flex_dir_opt {
1157            self.layout_flex(
1158                tree,
1159                (flow_start, flow_end),
1160                frame,
1161                flex_dir,
1162                (single_pass_ok, mode),
1163                stats,
1164            )
1165        } else {
1166            self.layout_grid(tree, (flow_start, flow_end), frame, mode, stats)
1167        };
1168        self.get_mut_flow_scratch().truncate(flow_start);
1169        if mode == LayoutRunMode::PerformLayout {
1170            for abs_idx in abs_start..abs_end {
1171                let abs_id: NodeId = self.get_abs_scratch()[abs_idx];
1172                let child_layout_opt: Option<LayoutStyle> = tree
1173                    .get_node(abs_id)
1174                    .map(|node: &SceneNode| node.style_ref().get_layout());
1175                let Some(child_layout) = child_layout_opt else {
1176                    continue;
1177                };
1178                let is_fixed: bool = child_layout.get_position() == Position::Fixed;
1179                let ref_origin: Point = if is_fixed {
1180                    Point::new(0.0, 0.0)
1181                } else {
1182                    content_origin
1183                };
1184                let ref_size: Size = if is_fixed { viewport } else { inner_avail };
1185                let resolved_w: Option<f32> = child_layout
1186                    .get_width()
1187                    .resolve(ref_size.get_width(), viewport);
1188                let resolved_h: Option<f32> = child_layout
1189                    .get_height()
1190                    .resolve(ref_size.get_height(), viewport);
1191                let needs_intrinsic: bool = (resolved_w.is_none()
1192                    && child_layout.left_offset().is_none()
1193                    && child_layout.right_offset().is_some())
1194                    || (resolved_h.is_none()
1195                        && child_layout.top_offset().is_none()
1196                        && child_layout.bottom_offset().is_some());
1197                let probed: Size = if needs_intrinsic {
1198                    let probe_space: AvailableSpace = AvailableSpace::new(
1199                        ref_size.get_width(),
1200                        ref_size.get_height(),
1201                        viewport,
1202                        ref_origin.get_x(),
1203                        ref_origin.get_y(),
1204                    );
1205                    self.layout_node_mode(
1206                        tree,
1207                        abs_id,
1208                        probe_space,
1209                        LayoutRunMode::ComputeSize,
1210                        stats,
1211                    )
1212                    .0
1213                } else {
1214                    Size::new(ref_size.get_width(), ref_size.get_height())
1215                };
1216                let child_w: f32 = resolved_w.unwrap_or(probed.get_width());
1217                let child_h: f32 = resolved_h.unwrap_or(probed.get_height());
1218                let x: f32 = if let Some(left) = child_layout.left_offset() {
1219                    ref_origin.get_x() + left
1220                } else if let Some(right) = child_layout.right_offset() {
1221                    ref_origin.get_x() + (ref_size.get_width() - child_w - right)
1222                } else {
1223                    ref_origin.get_x()
1224                };
1225                let y: f32 = if let Some(top) = child_layout.top_offset() {
1226                    ref_origin.get_y() + top
1227                } else if let Some(bottom) = child_layout.bottom_offset() {
1228                    ref_origin.get_y() + (ref_size.get_height() - child_h - bottom)
1229                } else {
1230                    ref_origin.get_y()
1231                };
1232                let abs_space: AvailableSpace = AvailableSpace::new(
1233                    ref_size.get_width(),
1234                    ref_size.get_height(),
1235                    viewport,
1236                    x,
1237                    y,
1238                );
1239                let _: (Size, u8, f32) = self.layout_node_mode(
1240                    tree,
1241                    abs_id,
1242                    abs_space,
1243                    LayoutRunMode::PerformLayout,
1244                    stats,
1245                );
1246            }
1247            self.get_mut_abs_scratch().truncate(abs_start);
1248        }
1249        flow_result
1250    }
1251
1252    /// Executes single-line or multi-line Flexbox layout with split `ComputeSize` probing and `PerformLayout` placement.
1253    ///
1254    /// # Arguments
1255    ///
1256    /// - `&Self` - Mutable layout engine reference.
1257    /// - `&mut SceneTree` - Mutable scene tree.
1258    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flow_scratch`.
1259    /// - `ContainerFrame` - Container constraints and origin.
1260    /// - `FlexDirection` - Effective main-axis direction.
1261    /// - `(bool, LayoutRunMode)` - Pair of `(single_pass_ok, run_mode)`.
1262    /// - `&mut LayoutStats` - Mutable telemetry counters.
1263    ///
1264    /// # Returns
1265    ///
1266    /// - `(Size, u8, f32)` - Aggregate content size, dependency mask, and invariant `min_avail_w`.
1267    fn layout_flex(
1268        &mut self,
1269        tree: &mut SceneTree,
1270        flow_range: (usize, usize),
1271        frame: ContainerFrame,
1272        direction: FlexDirection,
1273        mode_flags: (bool, LayoutRunMode),
1274        stats: &mut LayoutStats,
1275    ) -> (Size, u8, f32) {
1276        let (flow_start, flow_end): (usize, usize) = flow_range;
1277        let (single_pass_ok, mode): (bool, LayoutRunMode) = mode_flags;
1278        let count_all: usize = flow_end.saturating_sub(flow_start);
1279        if count_all == 0 {
1280            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
1281        }
1282        let parent_layout: LayoutStyle = frame.get_parent_layout();
1283        let inner_avail: Size = frame.get_inner_avail();
1284        let viewport: Size = frame.get_viewport();
1285        let content_origin: Point = frame.get_content_origin();
1286        let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
1287        let is_reverse: bool = matches!(
1288            direction,
1289            FlexDirection::RowReverse | FlexDirection::ColumnReverse
1290        );
1291        let main_gap: f32 = if is_row {
1292            parent_layout.get_column_gap()
1293        } else {
1294            parent_layout.get_row_gap()
1295        };
1296        let cross_gap: f32 = if is_row {
1297            parent_layout.get_row_gap()
1298        } else {
1299            parent_layout.get_column_gap()
1300        };
1301        let main_avail: f32 = if is_row {
1302            inner_avail.get_width()
1303        } else {
1304            inner_avail.get_height()
1305        };
1306        let cross_avail: f32 = if is_row {
1307            inner_avail.get_height()
1308        } else {
1309            inner_avail.get_width()
1310        };
1311        if is_reverse {
1312            self.get_mut_flow_scratch()[flow_start..flow_end].reverse();
1313        }
1314        let wrap_enabled: bool = parent_layout.get_flex_wrap() == FlexWrap::Wrap;
1315        if single_pass_ok {
1316            let parent_align: AlignItems = parent_layout.get_align_items();
1317            let mut main_cursor: f32 = 0.0;
1318            let mut max_cross: f32 = 0.0;
1319            let mut agg_deps: u8 = LAYOUT_DEP_NONE;
1320            let mut agg_min_aw: f32 = 0.0;
1321            let records_start: usize = self.get_flex_items_scratch().len();
1322            for offset in 0..count_all {
1323                let child_id: NodeId = self.get_flow_scratch()[flow_start + offset];
1324                let (margin, align, width_auto, height_auto, c_overflow, c_transform): (
1325                    Edges,
1326                    AlignItems,
1327                    bool,
1328                    bool,
1329                    Overflow,
1330                    Transform2D,
1331                ) = if let Some(node) = tree.get_node(child_id) {
1332                    let Style {
1333                        layout: child_layout,
1334                        paint: child_paint,
1335                        ..
1336                    } = node.style_ref();
1337                    let a: AlignItems = match child_layout.get_align_self() {
1338                        AlignSelf::Auto => parent_align,
1339                        AlignSelf::Stretch => AlignItems::Stretch,
1340                        AlignSelf::Start => AlignItems::Start,
1341                        AlignSelf::Center => AlignItems::Center,
1342                        AlignSelf::End => AlignItems::End,
1343                    };
1344                    (
1345                        child_layout.get_margin(),
1346                        a,
1347                        child_layout.get_width() == Length::Auto,
1348                        child_layout.get_height() == Length::Auto,
1349                        child_layout.get_overflow(),
1350                        child_paint.get_transform(),
1351                    )
1352                } else {
1353                    (
1354                        Edges::default(),
1355                        parent_align,
1356                        true,
1357                        true,
1358                        Overflow::Visible,
1359                        Transform2D::default(),
1360                    )
1361                };
1362                let (x, y): (f32, f32) = if is_row {
1363                    (
1364                        content_origin.get_x() + main_cursor + margin.get_left(),
1365                        content_origin.get_y() + margin.get_top(),
1366                    )
1367                } else {
1368                    (
1369                        content_origin.get_x() + margin.get_left(),
1370                        content_origin.get_y() + main_cursor + margin.get_top(),
1371                    )
1372                };
1373                let stretch_w: bool = !is_row && align == AlignItems::Stretch && width_auto;
1374                let stretch_h: bool = is_row && align == AlignItems::Stretch && height_auto;
1375                if stretch_w {
1376                    agg_deps |= LAYOUT_DEP_AVAIL_W;
1377                }
1378                if stretch_h {
1379                    agg_deps |= LAYOUT_DEP_AVAIL_H;
1380                }
1381                let space_w: f32 = if stretch_w {
1382                    (inner_avail.get_width() - margin.horizontal()).max(0.0)
1383                } else {
1384                    inner_avail.get_width()
1385                };
1386                let space_h: f32 = if stretch_h {
1387                    (inner_avail.get_height() - margin.vertical()).max(0.0)
1388                } else {
1389                    inner_avail.get_height()
1390                };
1391                let final_space: AvailableSpace =
1392                    AvailableSpace::new(space_w, space_h, viewport, x, y)
1393                        .with_stretch(stretch_w, stretch_h);
1394                let (placed, c_deps, c_min_aw): (Size, u8, f32) =
1395                    self.layout_node_mode(tree, child_id, final_space, mode, stats);
1396                agg_deps |= c_deps;
1397                if c_min_aw > 0.0 {
1398                    agg_min_aw = agg_min_aw.max(c_min_aw + margin.horizontal());
1399                }
1400                let target_w: f32 = if stretch_w {
1401                    space_w.max(placed.get_width())
1402                } else {
1403                    placed.get_width()
1404                };
1405                let target_h: f32 = if stretch_h {
1406                    space_h.max(placed.get_height())
1407                } else {
1408                    placed.get_height()
1409                };
1410                if mode == LayoutRunMode::PerformLayout {
1411                    if (stretch_w && target_w > placed.get_width() + 0.01)
1412                        || (stretch_h && target_h > placed.get_height() + 0.01)
1413                    {
1414                        self.record_layout_snapshot(tree, child_id);
1415                        let updated_b: Option<Rect> =
1416                            if let Some(node) = tree.get_node_mut(child_id) {
1417                                let mut b: Rect = node.get_layout_box().get_bounds();
1418                                b.set_width(target_w);
1419                                b.set_height(target_h);
1420                                node.get_mut_layout_box().set_bounds(b);
1421                                Some(b)
1422                            } else {
1423                                None
1424                            };
1425                        if let Some(b) = updated_b {
1426                            let is_clipped: bool =
1427                                matches!(c_overflow, Overflow::Hidden | Overflow::Scroll);
1428                            let Self { split_cache, .. } = self;
1429                            split_cache.mark_post_stretched(child_id, b, c_transform, is_clipped);
1430                        }
1431                    }
1432                    if stretch_w {
1433                        self.get_mut_flex_items_scratch().push(FlexItemRecord {
1434                            node_id: child_id,
1435                            size: Size::new(target_w, target_h),
1436                            margin,
1437                            flex_grow: 0.0,
1438                            align_self: AlignSelf::Stretch,
1439                            overflow: c_overflow,
1440                            flags: 0,
1441                        });
1442                    }
1443                }
1444                if is_row {
1445                    main_cursor += target_w + margin.horizontal();
1446                    max_cross = max_cross.max(target_h + margin.vertical());
1447                } else {
1448                    main_cursor += target_h + margin.vertical();
1449                    max_cross = max_cross.max(target_w + margin.horizontal());
1450                }
1451                if offset + 1 < count_all {
1452                    main_cursor += main_gap;
1453                }
1454            }
1455            let records_end: usize = self.get_flex_items_scratch().len();
1456            if mode == LayoutRunMode::PerformLayout
1457                && records_end > records_start
1458                && max_cross > cross_avail + 0.5
1459            {
1460                for rec_idx in records_start..records_end {
1461                    let rec: FlexItemRecord = self.get_flex_items_scratch()[rec_idx];
1462                    let widened: f32 =
1463                        (max_cross - rec.margin.horizontal()).max(rec.size.get_width());
1464                    self.record_layout_snapshot(tree, rec.node_id);
1465                    let updated_opt: Option<(Rect, Transform2D)> =
1466                        if let Some(node) = tree.get_node_mut(rec.node_id) {
1467                            let tr: Transform2D = node.style_ref().paint_ref().get_transform();
1468                            let mut b: Rect = node.get_layout_box().get_bounds();
1469                            b.set_width(widened);
1470                            node.get_mut_layout_box().set_bounds(b);
1471                            Some((b, tr))
1472                        } else {
1473                            None
1474                        };
1475                    if let Some((b, tr)) = updated_opt {
1476                        let is_clipped: bool =
1477                            matches!(rec.overflow, Overflow::Hidden | Overflow::Scroll);
1478                        let Self { split_cache, .. } = self;
1479                        split_cache.mark_post_stretched(rec.node_id, b, tr, is_clipped);
1480                    }
1481                }
1482            }
1483            self.get_mut_flex_items_scratch().truncate(records_start);
1484            let out_size: Size = if is_row {
1485                Size::new(main_cursor, max_cross)
1486            } else {
1487                Size::new(max_cross, main_cursor)
1488            };
1489            return (out_size, agg_deps, agg_min_aw);
1490        }
1491        let items_start: usize = self.get_flex_items_scratch().len();
1492        let probe_template: AvailableSpace = AvailableSpace::new(
1493            inner_avail.get_width(),
1494            inner_avail.get_height(),
1495            viewport,
1496            content_origin.get_x(),
1497            content_origin.get_y(),
1498        );
1499        let mut total_grow: f32 = 0.0;
1500        let mut single_line_main: f32 = 0.0;
1501        let mut single_line_cross: f32 = 0.0;
1502        let mut pass1_deps: u8 = LAYOUT_DEP_NONE;
1503        let mut pass1_min_aw: f32 = 0.0;
1504        for flow_idx in flow_start..flow_end {
1505            let child_id: NodeId = self.get_flow_scratch()[flow_idx];
1506            let mut rec: FlexItemRecord = FlexItemRecord {
1507                node_id: child_id,
1508                size: Size::default(),
1509                margin: Edges::default(),
1510                flex_grow: 0.0,
1511                align_self: AlignSelf::Auto,
1512                overflow: Overflow::Visible,
1513                flags: FLEX_ITEM_DEFAULT_FLAGS,
1514            };
1515            let mut zero_basis_size: Option<Size> = None;
1516            if let Some(node) = tree.get_node(child_id) {
1517                let Style {
1518                    layout: child_layout,
1519                    ..
1520                } = node.style_ref();
1521                let width_len: Length = child_layout.get_width();
1522                let height_len: Length = child_layout.get_height();
1523                let grow: f32 = child_layout.get_flex_grow();
1524                let width_auto: bool = width_len == Length::Auto;
1525                let height_auto: bool = height_len == Length::Auto;
1526                let mut f: u16 = 0;
1527                if width_auto {
1528                    f |= FLEX_ITEM_WIDTH_AUTO;
1529                }
1530                if height_auto {
1531                    f |= FLEX_ITEM_HEIGHT_AUTO;
1532                }
1533                if matches!(width_len, Length::Percent(_)) {
1534                    f |= FLEX_ITEM_WIDTH_PERCENT;
1535                }
1536                if matches!(height_len, Length::Percent(_)) {
1537                    f |= FLEX_ITEM_HEIGHT_PERCENT;
1538                }
1539                let zero_basis: bool =
1540                    !wrap_enabled && grow > 0.0 && if is_row { width_auto } else { height_auto };
1541                if zero_basis {
1542                    if is_row {
1543                        if matches!(height_len, Length::Percent(_)) {
1544                            pass1_deps |= LAYOUT_DEP_AVAIL_H;
1545                        }
1546                        if Self::is_viewport_length(height_len) {
1547                            pass1_deps |= LAYOUT_DEP_VIEWPORT;
1548                        }
1549                        let h: f32 = height_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1550                        zero_basis_size = Some(Size::new(0.0, h));
1551                    } else {
1552                        if matches!(width_len, Length::Percent(_)) {
1553                            pass1_deps |= LAYOUT_DEP_AVAIL_W;
1554                        }
1555                        if Self::is_viewport_length(width_len) {
1556                            pass1_deps |= LAYOUT_DEP_VIEWPORT;
1557                        }
1558                        let w: f32 = width_len.resolve(cross_avail, viewport).unwrap_or(0.0);
1559                        zero_basis_size = Some(Size::new(w, 0.0));
1560                    }
1561                }
1562                rec.margin = child_layout.get_margin();
1563                rec.flex_grow = grow;
1564                rec.align_self = child_layout.get_align_self();
1565                rec.overflow = child_layout.get_overflow();
1566                rec.flags = f;
1567            }
1568            total_grow += rec.flex_grow;
1569            let child_size: Size = if let Some(zb) = zero_basis_size {
1570                zb
1571            } else {
1572                let (measured, c_deps, c_min_aw): (Size, u8, f32) = self.layout_node_mode(
1573                    tree,
1574                    child_id,
1575                    probe_template,
1576                    LayoutRunMode::ComputeSize,
1577                    stats,
1578                );
1579                pass1_deps |= c_deps;
1580                if c_min_aw > 0.0 {
1581                    pass1_min_aw = pass1_min_aw.max(c_min_aw + rec.margin.horizontal());
1582                }
1583                measured
1584            };
1585            if !wrap_enabled {
1586                if is_row {
1587                    single_line_main += child_size.get_width() + rec.margin.horizontal();
1588                    single_line_cross =
1589                        single_line_cross.max(child_size.get_height() + rec.margin.vertical());
1590                } else {
1591                    single_line_main += child_size.get_height() + rec.margin.vertical();
1592                    single_line_cross =
1593                        single_line_cross.max(child_size.get_width() + rec.margin.horizontal());
1594                }
1595            }
1596            rec.size = child_size;
1597            self.get_mut_flex_items_scratch().push(rec);
1598        }
1599        let items_end: usize = self.get_flex_items_scratch().len();
1600        if !wrap_enabled {
1601            let line_ctx: FlexLineContext = FlexLineContext {
1602                frame,
1603                is_row,
1604                wrap_enabled: false,
1605                main_gap,
1606                main_avail,
1607                cross_avail,
1608                total_grow,
1609                line_count: 1,
1610                mode,
1611            };
1612            let (line_size, line_deps, line_min_aw): (Size, u8, f32) = self.layout_flex_line(
1613                tree,
1614                (items_start, items_end),
1615                0.0,
1616                Some((single_line_main, single_line_cross)),
1617                line_ctx,
1618                stats,
1619            );
1620            self.get_mut_flex_items_scratch().truncate(items_start);
1621            return (
1622                line_size,
1623                pass1_deps | line_deps,
1624                pass1_min_aw.max(line_min_aw),
1625            );
1626        }
1627        let lines_start: usize = self.get_flex_lines_scratch().len();
1628        let mut cur_line_start: usize = items_start;
1629        let mut line_main: f32 = 0.0;
1630        for item_idx in items_start..items_end {
1631            let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1632            let item_main: f32 = if is_row {
1633                item.size.get_width() + item.margin.horizontal()
1634            } else {
1635                item.size.get_height() + item.margin.vertical()
1636            };
1637            let line_empty: bool = item_idx == cur_line_start;
1638            let needed: f32 = if line_empty {
1639                item_main
1640            } else {
1641                line_main + main_gap + item_main
1642            };
1643            if !line_empty && needed > main_avail && main_avail > 0.0 {
1644                self.get_mut_flex_lines_scratch()
1645                    .push((cur_line_start, item_idx));
1646                cur_line_start = item_idx;
1647                line_main = item_main;
1648            } else {
1649                line_main = needed;
1650            }
1651        }
1652        if cur_line_start < items_end {
1653            self.get_mut_flex_lines_scratch()
1654                .push((cur_line_start, items_end));
1655        }
1656        let lines_end: usize = self.get_flex_lines_scratch().len();
1657        let mut cross_cursor: f32 = 0.0;
1658        let mut max_main_extent: f32 = 0.0;
1659        let line_count: usize = lines_end.saturating_sub(lines_start);
1660        let mut wrap_deps: u8 = pass1_deps;
1661        let mut wrap_min_aw: f32 = pass1_min_aw;
1662        if is_row {
1663            if line_count > 1 {
1664                wrap_deps |= LAYOUT_DEP_AVAIL_W;
1665            } else {
1666                wrap_min_aw = wrap_min_aw.max(line_main + 0.5);
1667            }
1668        } else {
1669            wrap_deps |= LAYOUT_DEP_AVAIL_H;
1670        }
1671        for line_offset in 0..line_count {
1672            let line_range: (usize, usize) =
1673                self.get_flex_lines_scratch()[lines_start + line_offset];
1674            let mut line_grow: f32 = 0.0;
1675            for item_idx in line_range.0..line_range.1 {
1676                line_grow += self.get_flex_items_scratch()[item_idx].flex_grow;
1677            }
1678            let line_ctx: FlexLineContext = FlexLineContext {
1679                frame,
1680                is_row,
1681                wrap_enabled: true,
1682                main_gap,
1683                main_avail,
1684                cross_avail,
1685                total_grow: line_grow,
1686                line_count,
1687                mode,
1688            };
1689            let (line_size, l_deps, l_min_aw): (Size, u8, f32) =
1690                self.layout_flex_line(tree, line_range, cross_cursor, None, line_ctx, stats);
1691            wrap_deps |= l_deps;
1692            wrap_min_aw = wrap_min_aw.max(l_min_aw);
1693            if is_row {
1694                max_main_extent = max_main_extent.max(line_size.get_width());
1695                cross_cursor += line_size.get_height();
1696            } else {
1697                max_main_extent = max_main_extent.max(line_size.get_height());
1698                cross_cursor += line_size.get_width();
1699            }
1700            if line_offset + 1 < line_count {
1701                cross_cursor += cross_gap;
1702            }
1703        }
1704        self.get_mut_flex_lines_scratch().truncate(lines_start);
1705        self.get_mut_flex_items_scratch().truncate(items_start);
1706        let out_size: Size = if is_row {
1707            Size::new(max_main_extent, cross_cursor)
1708        } else {
1709            Size::new(cross_cursor, max_main_extent)
1710        };
1711        (out_size, wrap_deps, wrap_min_aw)
1712    }
1713
1714    /// Resolves flex-grow and places a single flex line slice `[line_start..line_end)`, skipping Pass 3 in `ComputeSize` mode.
1715    ///
1716    /// # Arguments
1717    ///
1718    /// - `&Self` - Mutable layout engine reference.
1719    /// - `&mut SceneTree` - Mutable scene tree.
1720    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flex_items_scratch`.
1721    /// - `f32` - Cross-axis cursor offset where this line begins.
1722    /// - `Option<(f32, f32)>` - Optional pre-accumulated `(items_main_sum, line_cross)` for unwrapped single-line passes.
1723    /// - `FlexLineContext` - Enclosing container axis, gap, and execution mode parameters.
1724    /// - `&mut LayoutStats` - Mutable telemetry counters.
1725    ///
1726    /// # Returns
1727    ///
1728    /// - `(Size, u8, f32)` - Occupied `(width, height)` extent, dependency mask, and invariant `min_avail_w`.
1729    #[inline(always)]
1730    fn layout_flex_line(
1731        &mut self,
1732        tree: &mut SceneTree,
1733        line_range: (usize, usize),
1734        cross_cursor: f32,
1735        precomputed: Option<(f32, f32)>,
1736        ctx: FlexLineContext,
1737        stats: &mut LayoutStats,
1738    ) -> (Size, u8, f32) {
1739        let (line_start, line_end): (usize, usize) = line_range;
1740        let frame: ContainerFrame = ctx.frame;
1741        let is_row: bool = ctx.is_row;
1742        let wrap_enabled: bool = ctx.wrap_enabled;
1743        let main_gap: f32 = ctx.main_gap;
1744        let main_avail: f32 = ctx.main_avail;
1745        let cross_avail: f32 = ctx.cross_avail;
1746        let total_grow: f32 = ctx.total_grow;
1747        let line_count: usize = ctx.line_count;
1748        let mode: LayoutRunMode = ctx.mode;
1749        let parent_layout: LayoutStyle = frame.get_parent_layout();
1750        let inner_avail: Size = frame.get_inner_avail();
1751        let viewport: Size = frame.get_viewport();
1752        let content_origin: Point = frame.get_content_origin();
1753        let count: usize = line_end.saturating_sub(line_start);
1754        let gaps_total: f32 = if count > 1 {
1755            main_gap * ((count - 1) as f32)
1756        } else {
1757            0.0
1758        };
1759        let mut line_deps: u8 = LAYOUT_DEP_NONE;
1760        let mut line_min_aw: f32 = 0.0;
1761        let has_definite_or_grow: bool = frame.get_definite_width() || total_grow > 0.0;
1762        let effective_main_avail: f32 = if is_row {
1763            if has_definite_or_grow || wrap_enabled {
1764                if total_grow > 0.0 {
1765                    line_deps |= LAYOUT_DEP_AVAIL_W;
1766                }
1767                main_avail
1768            } else {
1769                let min_w_len: Length = parent_layout.get_min_width();
1770                if matches!(min_w_len, Length::Percent(_)) || Self::is_viewport_length(min_w_len) {
1771                    line_deps |= LAYOUT_DEP_VIEWPORT;
1772                }
1773                frame.get_min_inner_size().get_width()
1774            }
1775        } else if frame.get_definite_height() {
1776            if total_grow > 0.0 {
1777                line_deps |= LAYOUT_DEP_AVAIL_H;
1778            }
1779            main_avail
1780        } else {
1781            let min_h_len: Length = parent_layout.get_min_height();
1782            if matches!(min_h_len, Length::Percent(_)) || Self::is_viewport_length(min_h_len) {
1783                line_deps |= LAYOUT_DEP_VIEWPORT;
1784            }
1785            frame.get_min_inner_size().get_height()
1786        };
1787        let (final_used_main, line_cross): (f32, f32) = if let Some((items_main, pre_cross)) =
1788            precomputed
1789            && total_grow == 0.0
1790        {
1791            (items_main + gaps_total, pre_cross)
1792        } else {
1793            let used_main: f32 = if let Some((items_main, _)) = precomputed {
1794                items_main + gaps_total
1795            } else {
1796                let mut acc: f32 = gaps_total;
1797                for item_idx in line_start..line_end {
1798                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1799                    let sz: f32 = if is_row {
1800                        item.size.get_width() + item.margin.horizontal()
1801                    } else {
1802                        item.size.get_height() + item.margin.vertical()
1803                    };
1804                    acc += sz;
1805                }
1806                acc
1807            };
1808            let free_main: f32 = (effective_main_avail - used_main).max(0.0);
1809            if total_grow > 0.0 && free_main > 0.0 {
1810                for item_idx in line_start..line_end {
1811                    let item: &mut FlexItemRecord =
1812                        &mut self.get_mut_flex_items_scratch()[item_idx];
1813                    let grow: f32 = item.flex_grow;
1814                    if grow > 0.0 {
1815                        let extra: f32 = free_main * (grow / total_grow);
1816                        if is_row {
1817                            item.size.set_width(item.size.get_width() + extra);
1818                        } else {
1819                            item.size.set_height(item.size.get_height() + extra);
1820                        }
1821                    }
1822                }
1823            }
1824            if total_grow > 0.0 {
1825                for item_idx in line_start..line_end {
1826                    let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1827                    let auto_cross: bool = item.flex_grow > 0.0
1828                        && if is_row {
1829                            (item.flags & FLEX_ITEM_HEIGHT_AUTO) != 0
1830                        } else {
1831                            (item.flags & FLEX_ITEM_WIDTH_AUTO) != 0
1832                        };
1833                    if auto_cross {
1834                        let probe_w: f32 = if is_row {
1835                            item.size.get_width()
1836                        } else {
1837                            cross_avail
1838                        };
1839                        let probe_h: f32 = if is_row {
1840                            cross_avail
1841                        } else {
1842                            item.size.get_height()
1843                        };
1844                        let stretch_pw: bool = is_row && (item.flags & FLEX_ITEM_WIDTH_AUTO) != 0;
1845                        let stretch_ph: bool = !is_row && (item.flags & FLEX_ITEM_HEIGHT_AUTO) != 0;
1846                        let probe_sp: AvailableSpace = AvailableSpace::new(
1847                            probe_w,
1848                            probe_h,
1849                            viewport,
1850                            content_origin.get_x(),
1851                            content_origin.get_y(),
1852                        )
1853                        .with_stretch(stretch_pw, stretch_ph);
1854                        let (measured, c_deps, c_min_aw): (Size, u8, f32) = self.layout_node_mode(
1855                            tree,
1856                            item.node_id,
1857                            probe_sp,
1858                            LayoutRunMode::ComputeSize,
1859                            stats,
1860                        );
1861                        line_deps |= c_deps;
1862                        if c_min_aw > 0.0 {
1863                            line_min_aw = line_min_aw.max(c_min_aw + item.margin.horizontal());
1864                        }
1865                        let slot: &mut FlexItemRecord =
1866                            &mut self.get_mut_flex_items_scratch()[item_idx];
1867                        if is_row {
1868                            slot.size.set_height(measured.get_height());
1869                        } else {
1870                            slot.size.set_width(measured.get_width());
1871                        }
1872                    }
1873                }
1874            }
1875            let mut sum_main: f32 = gaps_total;
1876            let mut max_cross: f32 = 0.0;
1877            for item_idx in line_start..line_end {
1878                let item: FlexItemRecord = self.get_flex_items_scratch()[item_idx];
1879                if is_row {
1880                    sum_main += item.size.get_width() + item.margin.horizontal();
1881                    max_cross = max_cross.max(item.size.get_height() + item.margin.vertical());
1882                } else {
1883                    sum_main += item.size.get_height() + item.margin.vertical();
1884                    max_cross = max_cross.max(item.size.get_width() + item.margin.horizontal());
1885                }
1886            }
1887            (sum_main, max_cross)
1888        };
1889        if mode == LayoutRunMode::ComputeSize {
1890            let sz: Size = if is_row {
1891                Size::new(final_used_main, line_cross)
1892            } else {
1893                Size::new(line_cross, final_used_main)
1894            };
1895            return (sz, line_deps, line_min_aw);
1896        }
1897        let rem: f32 = (effective_main_avail - final_used_main).max(0.0);
1898        let (mut main_cursor, extra_step): (f32, f32) = match parent_layout.get_justify_content() {
1899            JustifyContent::Start => (0.0, 0.0),
1900            JustifyContent::Center => (rem * 0.5, 0.0),
1901            JustifyContent::End => (rem, 0.0),
1902            JustifyContent::SpaceBetween => {
1903                if count > 1 {
1904                    (0.0, rem / ((count - 1) as f32))
1905                } else {
1906                    (0.0, 0.0)
1907                }
1908            }
1909            JustifyContent::SpaceAround => {
1910                let slot: f32 = rem / (count.max(1) as f32);
1911                (slot * 0.5, slot)
1912            }
1913            JustifyContent::SpaceEvenly => {
1914                let slot: f32 = rem / ((count + 1) as f32);
1915                (slot, slot)
1916            }
1917        };
1918        let min_cross: f32 = if is_row {
1919            frame.get_min_inner_size().get_height()
1920        } else {
1921            frame.get_min_inner_size().get_width()
1922        };
1923        let definite_cross: bool = !is_row || frame.get_definite_height();
1924        let effective_line_cross: f32 = if line_count == 1 {
1925            let floor_cross: f32 = if definite_cross && (!wrap_enabled || is_row) {
1926                cross_avail.max(min_cross)
1927            } else {
1928                min_cross
1929            };
1930            line_cross.max(floor_cross)
1931        } else {
1932            line_cross
1933        };
1934        let mut actual_line_cross: f32 = line_cross;
1935        let parent_align: AlignItems = parent_layout.get_align_items();
1936        for idx in 0..count {
1937            let rec: FlexItemRecord = self.get_flex_items_scratch()[line_start + idx];
1938            let child_id: NodeId = rec.node_id;
1939            let child_size: Size = rec.size;
1940            let margin: Edges = rec.margin;
1941            let width_auto: bool = (rec.flags & FLEX_ITEM_WIDTH_AUTO) != 0;
1942            let height_auto: bool = (rec.flags & FLEX_ITEM_HEIGHT_AUTO) != 0;
1943            let item_cross: f32 = if is_row {
1944                child_size.get_height()
1945            } else {
1946                child_size.get_width()
1947            };
1948            let align: AlignItems = match rec.align_self {
1949                AlignSelf::Auto => parent_align,
1950                AlignSelf::Stretch => AlignItems::Stretch,
1951                AlignSelf::Start => AlignItems::Start,
1952                AlignSelf::Center => AlignItems::Center,
1953                AlignSelf::End => AlignItems::End,
1954            };
1955            let avail_item_cross: f32 = (effective_line_cross
1956                - if is_row {
1957                    margin.vertical()
1958                } else {
1959                    margin.horizontal()
1960                })
1961            .max(0.0);
1962            let cross_offset: f32 = match align {
1963                AlignItems::Start | AlignItems::Stretch => 0.0,
1964                AlignItems::Center => ((avail_item_cross - item_cross) * 0.5).max(0.0),
1965                AlignItems::End => (avail_item_cross - item_cross).max(0.0),
1966            };
1967            let auto_cross_grow: bool =
1968                rec.flex_grow > 0.0 && if is_row { height_auto } else { width_auto };
1969            let target_w: f32 = if !is_row && align == AlignItems::Stretch && width_auto {
1970                avail_item_cross.max(child_size.get_width())
1971            } else {
1972                child_size.get_width()
1973            };
1974            let target_h: f32 = if is_row && align == AlignItems::Stretch && height_auto {
1975                avail_item_cross.max(child_size.get_height())
1976            } else {
1977                child_size.get_height()
1978            };
1979            let (x, y): (f32, f32) = if is_row {
1980                (
1981                    content_origin.get_x() + main_cursor + margin.get_left(),
1982                    content_origin.get_y() + cross_cursor + cross_offset + margin.get_top(),
1983                )
1984            } else {
1985                (
1986                    content_origin.get_x() + cross_cursor + cross_offset + margin.get_left(),
1987                    content_origin.get_y() + main_cursor + margin.get_top(),
1988                )
1989            };
1990            let space_w: f32 = if (rec.flags & FLEX_ITEM_WIDTH_PERCENT) != 0 {
1991                inner_avail.get_width()
1992            } else if auto_cross_grow && !is_row {
1993                cross_avail
1994            } else {
1995                target_w
1996            };
1997            let space_h: f32 = if (rec.flags & FLEX_ITEM_HEIGHT_PERCENT) != 0 {
1998                inner_avail.get_height()
1999            } else if auto_cross_grow && is_row {
2000                cross_avail
2001            } else {
2002                target_h
2003            };
2004            let stretch_child_w: bool = !(auto_cross_grow && !is_row)
2005                && ((!is_row && align == AlignItems::Stretch && width_auto)
2006                    || (is_row && rec.flex_grow > 0.0 && width_auto));
2007            let stretch_child_h: bool = !(auto_cross_grow && is_row)
2008                && ((is_row && align == AlignItems::Stretch && height_auto)
2009                    || (!is_row && rec.flex_grow > 0.0 && height_auto));
2010            let final_space: AvailableSpace = AvailableSpace::new(space_w, space_h, viewport, x, y)
2011                .with_stretch(stretch_child_w, stretch_child_h);
2012            let (placed, _, _): (Size, u8, f32) = self.layout_node_mode(
2013                tree,
2014                child_id,
2015                final_space,
2016                LayoutRunMode::PerformLayout,
2017                stats,
2018            );
2019            let is_clipped: bool = matches!(rec.overflow, Overflow::Hidden | Overflow::Scroll);
2020            let (desired_w, desired_h): (f32, f32) = if auto_cross_grow {
2021                if is_row {
2022                    actual_line_cross =
2023                        actual_line_cross.max(placed.get_height() + margin.vertical());
2024                    (target_w, placed.get_height())
2025                } else {
2026                    actual_line_cross =
2027                        actual_line_cross.max(placed.get_width() + margin.horizontal());
2028                    (placed.get_width(), target_h)
2029                }
2030            } else if is_clipped || rec.flex_grow > 0.0 {
2031                (target_w, target_h)
2032            } else {
2033                (
2034                    target_w.max(placed.get_width()),
2035                    target_h.max(placed.get_height()),
2036                )
2037            };
2038            let needs_box_adjust: bool = tree.get_node(child_id).is_some_and(|n: &SceneNode| {
2039                let b: Rect = n.get_layout_box().get_bounds();
2040                (b.get_width() - desired_w).abs() > 0.001
2041                    || (b.get_height() - desired_h).abs() > 0.001
2042            });
2043            if needs_box_adjust {
2044                self.record_layout_snapshot(tree, child_id);
2045                let adjusted_opt: Option<(Rect, Transform2D)> =
2046                    if let Some(node) = tree.get_node_mut(child_id) {
2047                        let tr: Transform2D = node.style_ref().paint_ref().get_transform();
2048                        let mut b: Rect = node.get_layout_box().get_bounds();
2049                        b.set_width(desired_w);
2050                        b.set_height(desired_h);
2051                        node.get_mut_layout_box().set_bounds(b);
2052                        Some((b, tr))
2053                    } else {
2054                        None
2055                    };
2056                if let Some((b, tr)) = adjusted_opt {
2057                    let Self { split_cache, .. } = self;
2058                    split_cache.mark_post_stretched(child_id, b, tr, is_clipped);
2059                }
2060            }
2061            let advance: f32 = if is_row {
2062                target_w + margin.horizontal()
2063            } else {
2064                target_h + margin.vertical()
2065            };
2066            main_cursor += advance;
2067            if idx + 1 < count {
2068                main_cursor += main_gap + extra_step;
2069            }
2070        }
2071        let sz: Size = if is_row {
2072            Size::new(final_used_main, actual_line_cross)
2073        } else {
2074            Size::new(actual_line_cross, final_used_main)
2075        };
2076        (sz, line_deps, line_min_aw)
2077    }
2078
2079    /// Executes uniform-column CSS Grid layout with row and column gaps in `ComputeSize` or `PerformLayout` mode.
2080    ///
2081    /// # Arguments
2082    ///
2083    /// - `&Self` - Mutable layout engine reference.
2084    /// - `&mut SceneTree` - Mutable scene tree.
2085    /// - `(usize, usize)` - Inclusive start and exclusive end indices into `flow_scratch`.
2086    /// - `ContainerFrame` - Grid container constraints and origin.
2087    /// - `LayoutRunMode` - `ComputeSize` probe vs `PerformLayout` placement mode.
2088    /// - `&mut LayoutStats` - Mutable telemetry counters.
2089    ///
2090    /// # Returns
2091    ///
2092    /// - `(Size, u8, f32)` - Aggregate grid content dimensions, dependency mask, and invariant `min_avail_w`.
2093    fn layout_grid(
2094        &mut self,
2095        tree: &mut SceneTree,
2096        flow_range: (usize, usize),
2097        frame: ContainerFrame,
2098        mode: LayoutRunMode,
2099        stats: &mut LayoutStats,
2100    ) -> (Size, u8, f32) {
2101        let (flow_start, flow_end): (usize, usize) = flow_range;
2102        if flow_start >= flow_end {
2103            return (Size::default(), LAYOUT_DEP_NONE, 0.0);
2104        }
2105        let parent_layout: LayoutStyle = frame.get_parent_layout();
2106        let inner_avail: Size = frame.get_inner_avail();
2107        let viewport: Size = frame.get_viewport();
2108        let content_origin: Point = frame.get_content_origin();
2109        let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
2110        let col_gap: f32 = parent_layout.get_column_gap();
2111        let row_gap: f32 = parent_layout.get_row_gap();
2112        let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
2113        let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
2114        let col_step: f32 = col_w + col_gap;
2115        let origin_x: f32 = content_origin.get_x();
2116        let origin_y: f32 = content_origin.get_y();
2117        let inner_h: f32 = inner_avail.get_height();
2118        let mut y_cursor: f32 = 0.0;
2119        let mut idx: usize = flow_start;
2120        let mut grid_deps: u8 = LAYOUT_DEP_AVAIL_W;
2121        while idx < flow_end {
2122            let row_end: usize = (idx + cols).min(flow_end);
2123            let mut row_h: f32 = 0.0;
2124            let mut min_row_h: f32 = f32::INFINITY;
2125            let y: f32 = origin_y + y_cursor;
2126            let mut x: f32 = origin_x;
2127            for pos in idx..row_end {
2128                let child_id: NodeId = self.get_flow_scratch()[pos];
2129                let auto_w: bool = tree.get_node(child_id).is_some_and(|n: &SceneNode| {
2130                    n.style_ref().layout_ref().get_width() == Length::Auto
2131                });
2132                let cell_space: AvailableSpace =
2133                    AvailableSpace::new(col_w, inner_h, viewport, x, y).with_stretch(auto_w, false);
2134                let (child_size, c_deps, _): (Size, u8, f32) =
2135                    self.layout_node_mode(tree, child_id, cell_space, mode, stats);
2136                grid_deps |= c_deps;
2137                if mode == LayoutRunMode::PerformLayout
2138                    && (child_size.get_width() - col_w).abs() > 0.001
2139                {
2140                    self.record_layout_snapshot(tree, child_id);
2141                    let adjusted_opt: Option<(Rect, Transform2D, bool)> =
2142                        if let Some(node) = tree.get_node_mut(child_id) {
2143                            let tr: Transform2D = node.style_ref().paint_ref().get_transform();
2144                            let clipped: bool = matches!(
2145                                node.style_ref().layout_ref().get_overflow(),
2146                                Overflow::Hidden | Overflow::Scroll
2147                            );
2148                            let mut b: Rect = node.get_layout_box().get_bounds();
2149                            b.set_width(col_w);
2150                            node.get_mut_layout_box().set_bounds(b);
2151                            Some((b, tr, clipped))
2152                        } else {
2153                            None
2154                        };
2155                    if let Some((b, tr, clipped)) = adjusted_opt {
2156                        let Self { split_cache, .. } = self;
2157                        split_cache.mark_post_stretched(child_id, b, tr, clipped);
2158                    }
2159                }
2160                let ch: f32 = child_size.get_height();
2161                row_h = row_h.max(ch);
2162                min_row_h = min_row_h.min(ch);
2163                x += col_step;
2164            }
2165            if mode == LayoutRunMode::PerformLayout && row_end - idx > 1 && min_row_h < row_h {
2166                for pos in idx..row_end {
2167                    let child_id: NodeId = self.get_flow_scratch()[pos];
2168                    let needs_stretch: bool =
2169                        tree.get_node(child_id).is_some_and(|n: &SceneNode| {
2170                            n.get_layout_box().get_bounds().get_height() < row_h
2171                        });
2172                    if needs_stretch {
2173                        self.record_layout_snapshot(tree, child_id);
2174                        let adjusted_opt: Option<(Rect, Transform2D, bool)> =
2175                            if let Some(node) = tree.get_node_mut(child_id) {
2176                                let tr: Transform2D = node.style_ref().paint_ref().get_transform();
2177                                let clipped: bool = matches!(
2178                                    node.style_ref().layout_ref().get_overflow(),
2179                                    Overflow::Hidden | Overflow::Scroll
2180                                );
2181                                let mut b: Rect = node.get_layout_box().get_bounds();
2182                                b.set_height(row_h);
2183                                node.get_mut_layout_box().set_bounds(b);
2184                                Some((b, tr, clipped))
2185                            } else {
2186                                None
2187                            };
2188                        if let Some((b, tr, clipped)) = adjusted_opt {
2189                            let Self { split_cache, .. } = self;
2190                            split_cache.mark_post_stretched(child_id, b, tr, clipped);
2191                        }
2192                    }
2193                }
2194            }
2195            y_cursor += row_h;
2196            if row_end < flow_end {
2197                y_cursor += row_gap;
2198            }
2199            idx = row_end;
2200        }
2201        (Size::new(inner_avail.get_width(), y_cursor), grid_deps, 0.0)
2202    }
2203
2204    /// Translates the cached layout geometry and SoA `SplitLayoutCache` bounds of `root_id` and non-fixed descendants by `(dx, dy)`.
2205    ///
2206    /// # Arguments
2207    ///
2208    /// - `&Self` - Mutable layout engine reference.
2209    /// - `&mut SceneTree` - Mutable retained scene tree.
2210    /// - `NodeId` - Root node of the clean subtree being shifted.
2211    /// - `f32` - Horizontal translation delta in logical pixels.
2212    /// - `f32` - Vertical translation delta in logical pixels.
2213    fn translate_subtree(&mut self, tree: &mut SceneTree, root_id: NodeId, dx: f32, dy: f32) {
2214        if dx == 0.0 && dy == 0.0 {
2215            return;
2216        }
2217        self.record_layout_snapshot(tree, root_id);
2218        let Some(root_node) = tree.get_node_mut(root_id) else {
2219            return;
2220        };
2221        let Style { layout, .. } = root_node.style_ref();
2222        let root_none_disp: bool = layout.get_display() == Display::None;
2223        if let Some(mut c) = root_node.cached_constraint() {
2224            c.set_origin_x(c.get_origin_x() + dx);
2225            c.set_origin_y(c.get_origin_y() + dy);
2226            root_node.set_last_constraint(Some(c));
2227        }
2228        if root_none_disp {
2229            let Self { split_cache, .. } = self;
2230            split_cache.translate_node_cache(root_id, dx, dy);
2231            return;
2232        }
2233        let mut root_bounds: Rect = root_node.get_layout_box().get_bounds();
2234        root_bounds.set_x(root_bounds.get_x() + dx);
2235        root_bounds.set_y(root_bounds.get_y() + dy);
2236        root_node.get_mut_layout_box().set_bounds(root_bounds);
2237        let mut root_content: Rect = root_node.get_layout_box().get_content_bounds();
2238        root_content.set_x(root_content.get_x() + dx);
2239        root_content.set_y(root_content.get_y() + dy);
2240        root_node
2241            .get_mut_layout_box()
2242            .set_content_bounds(root_content);
2243        let root_children_empty: bool = !tree.has_children(root_id);
2244        if !root_children_empty {
2245            self.get_mut_translate_scratch().clear();
2246            self.get_mut_translate_scratch()
2247                .extend(tree.children_iter(root_id));
2248        }
2249        {
2250            let Self { split_cache, .. } = self;
2251            split_cache.translate_node_cache(root_id, dx, dy);
2252        }
2253        if root_children_empty {
2254            return;
2255        }
2256        while let Some(nid) = self.get_mut_translate_scratch().pop() {
2257            let (is_fixed_pos, is_none_disp): (bool, bool) = match tree.get_node(nid) {
2258                Some(node) => {
2259                    let Style { layout, .. } = node.style_ref();
2260                    (
2261                        layout.get_position() == Position::Fixed,
2262                        layout.get_display() == Display::None,
2263                    )
2264                }
2265                None => continue,
2266            };
2267            if is_fixed_pos {
2268                continue;
2269            }
2270            if !is_none_disp {
2271                self.record_layout_snapshot(tree, nid);
2272            }
2273            let Some(node) = tree.get_node_mut(nid) else {
2274                continue;
2275            };
2276            if let Some(mut c) = node.cached_constraint() {
2277                c.set_origin_x(c.get_origin_x() + dx);
2278                c.set_origin_y(c.get_origin_y() + dy);
2279                node.set_last_constraint(Some(c));
2280            }
2281            if is_none_disp {
2282                let Self { split_cache, .. } = self;
2283                split_cache.translate_node_cache(nid, dx, dy);
2284                continue;
2285            }
2286            let mut bounds: Rect = node.get_layout_box().get_bounds();
2287            bounds.set_x(bounds.get_x() + dx);
2288            bounds.set_y(bounds.get_y() + dy);
2289            node.get_mut_layout_box().set_bounds(bounds);
2290            let mut content: Rect = node.get_layout_box().get_content_bounds();
2291            content.set_x(content.get_x() + dx);
2292            content.set_y(content.get_y() + dy);
2293            node.get_mut_layout_box().set_content_bounds(content);
2294            let has_children: bool = tree.has_children(nid);
2295            if has_children {
2296                self.get_mut_translate_scratch()
2297                    .extend(tree.children_iter(nid));
2298            }
2299            let Self { split_cache, .. } = self;
2300            split_cache.translate_node_cache(nid, dx, dy);
2301        }
2302    }
2303}