Skip to main content

strata_render/
compositor.rs

1//! CSS 2.1 Appendix E 7-Layer Stacking Context Compositor & Display List Generator.
2
3use crate::scene3d::Scene3D;
4use strata_layout::{LayoutNode, Rect};
5use strata_primitives::geom::EdgeInsets;
6use strata_style::effects::{BackdropFilter, ClipPath};
7use strata_style::types::{
8    BlendMode, BorderCollapse, BorderRadius, BorderStyle, BoxShadow, Color, ColorStop, Display,
9    FontWeight, Isolation, Overflow, Position,
10};
11
12/// Low-level drawing primitives emitted to GPU command buffers.
13#[derive(Debug, Clone, PartialEq)]
14pub enum DrawCommand {
15    DrawRect {
16        bounds: Rect,
17        color: Color,
18    },
19    DrawRoundedRect {
20        bounds: Rect,
21        color: Color,
22        border_radius: BorderRadius,
23        border_width: EdgeInsets<f32>,
24        border_color: Option<Color>,
25    },
26    DrawShadow {
27        bounds: Rect,
28        shadow: BoxShadow,
29        border_radius: BorderRadius,
30    },
31    DrawInsetShadow {
32        bounds: Rect,
33        shadow: BoxShadow,
34        border_radius: BorderRadius,
35    },
36    DrawLinearGradient {
37        bounds: Rect,
38        angle_deg: f32,
39        stops: Vec<ColorStop>,
40        border_radius: BorderRadius,
41    },
42    DrawRadialGradient {
43        bounds: Rect,
44        center: (f32, f32),
45        stops: Vec<ColorStop>,
46        border_radius: BorderRadius,
47    },
48    PushBackdropFilter {
49        bounds: Rect,
50        radius: BorderRadius,
51        filter: BackdropFilter,
52    },
53    PopBackdropFilter,
54    PushFilter {
55        bounds: Rect,
56        filter: BackdropFilter,
57    },
58    PopFilter,
59    PushClipPath {
60        bounds: Rect,
61        clip_path: ClipPath,
62    },
63    PopClipPath,
64    PushBlendMode {
65        mode: BlendMode,
66    },
67    PopBlendMode,
68    PushIsolation {
69        isolate: bool,
70    },
71    PopIsolation,
72    PushOpacity {
73        alpha: f32,
74    },
75    PopOpacity,
76    DrawBorder {
77        bounds: Rect,
78        widths: EdgeInsets<f32>,
79        color: Color,
80        border_radius: BorderRadius,
81        style: BorderStyle,
82    },
83    DrawText {
84        origin: (f32, f32),
85        bounds_width: Option<f32>,
86        bounds_height: Option<f32>,
87        text_align: strata_style::TextAlign,
88        text: String,
89        font_size: f32,
90        line_height: f32,
91        font_weight: FontWeight,
92        color: Color,
93        is_monospace: bool,
94        font_family: strata_primitives::AtomId,
95    },
96    DrawTextFragments {
97        fragments: Vec<strata_layout::TextFragment>,
98    },
99    DrawViewport3D {
100        bounds: Rect,
101        scene: std::sync::Arc<Scene3D>,
102    },
103    DrawCanvas2D {
104        bounds: Rect,
105        commands: Vec<crate::canvas2d::CanvasCommand>,
106    },
107    DrawSvgPath {
108        bounds: Rect,
109        path_data: String,
110        stroke_color: Option<Color>,
111        fill_color: Option<Color>,
112        stroke_width: f32,
113        stroke_linecap: strata_layout::StrokeLineCap,
114        stroke_linejoin: strata_layout::StrokeLineJoin,
115        stroke_dasharray: Vec<f32>,
116        fill_rule: strata_layout::FillRule,
117        view_box: (f32, f32),
118    },
119    DrawGpuPath {
120        bounds: Rect,
121        path: strata_gpu_path::Path,
122        stroke: Option<strata_gpu_path::StrokeOptions>,
123        fill_color: Option<Color>,
124        stroke_color: Option<Color>,
125        transform: Option<strata_primitives::geom::Matrix4x4>,
126    },
127    DrawImage {
128        bounds: Rect,
129        image: strata_layout::ImageResource,
130    },
131    PushClip {
132        bounds: Rect,
133        radius: BorderRadius,
134    },
135    PopClip,
136    PushTransform {
137        matrix: strata_primitives::geom::Matrix4x4,
138    },
139    PopTransform,
140}
141
142impl DrawCommand {
143    /// Returns true if this command is a clipping push or pop instruction.
144    #[inline]
145    pub fn is_clip(&self) -> bool {
146        matches!(
147            self,
148            Self::PushClip { .. }
149                | Self::PopClip
150                | Self::PushBackdropFilter { .. }
151                | Self::PopBackdropFilter
152                | Self::PushClipPath { .. }
153                | Self::PopClipPath
154        )
155    }
156
157    /// Returns true if this command mutates the render stack (push or pop).
158    ///
159    /// Stack commands must never be spatially culled, otherwise a pop would be
160    /// executed without its matching push (for example a Cairo group pop with
161    /// no group to pop).
162    #[inline]
163    pub fn is_state_command(&self) -> bool {
164        matches!(
165            self,
166            Self::PushClip { .. }
167                | Self::PopClip
168                | Self::PushBackdropFilter { .. }
169                | Self::PopBackdropFilter
170                | Self::PushClipPath { .. }
171                | Self::PopClipPath
172                | Self::PushFilter { .. }
173                | Self::PopFilter
174                | Self::PushBlendMode { .. }
175                | Self::PopBlendMode
176                | Self::PushIsolation { .. }
177                | Self::PopIsolation
178                | Self::PushOpacity { .. }
179                | Self::PopOpacity
180                | Self::PushTransform { .. }
181                | Self::PopTransform
182        )
183    }
184
185    /// Returns the bounding rectangle for this drawing command, if applicable.
186    pub fn bounds(&self) -> Option<Rect> {
187        match self {
188            Self::DrawRect { bounds, .. } => Some(*bounds),
189            Self::DrawRoundedRect { bounds, .. } => Some(*bounds),
190            Self::DrawShadow { bounds, shadow, .. } => {
191                let spread = shadow.spread_radius + shadow.blur_radius;
192                Some(Rect::new(
193                    bounds.x + shadow.offset_x - spread,
194                    bounds.y + shadow.offset_y - spread,
195                    bounds.width + spread * 2.0,
196                    bounds.height + spread * 2.0,
197                ))
198            }
199            Self::DrawInsetShadow { bounds, .. } => Some(*bounds),
200            Self::DrawLinearGradient { bounds, .. } => Some(*bounds),
201            Self::DrawRadialGradient { bounds, .. } => Some(*bounds),
202            Self::PushBackdropFilter { bounds, .. } => Some(*bounds),
203            Self::PopBackdropFilter => None,
204            Self::PushFilter { bounds, .. } => Some(*bounds),
205            Self::PopFilter => None,
206            Self::PushClipPath { bounds, .. } => Some(*bounds),
207            Self::PopClipPath => None,
208            Self::PushBlendMode { .. } | Self::PopBlendMode => None,
209            Self::PushIsolation { .. } | Self::PopIsolation => None,
210            Self::PushOpacity { .. } | Self::PopOpacity => None,
211            Self::DrawBorder { bounds, .. } => Some(*bounds),
212            Self::DrawText {
213                origin,
214                text,
215                font_size,
216                line_height,
217                ..
218            } => {
219                let h = line_height.max(*font_size);
220                let w = text.len() as f32 * font_size * 0.6;
221                Some(Rect::new(origin.0, origin.1, w, h))
222            }
223            Self::DrawTextFragments { fragments } => {
224                if fragments.is_empty() {
225                    None
226                } else {
227                    let mut min_x = f32::MAX;
228                    let mut min_y = f32::MAX;
229                    let mut max_x = f32::MIN;
230                    let mut max_y = f32::MIN;
231                    for f in fragments {
232                        min_x = min_x.min(f.bounds.x);
233                        min_y = min_y.min(f.bounds.y);
234                        max_x = max_x.max(f.bounds.x + f.bounds.width);
235                        max_y = max_y.max(f.bounds.y + f.bounds.height);
236                    }
237                    Some(Rect::new(
238                        min_x,
239                        min_y,
240                        (max_x - min_x).max(0.0),
241                        (max_y - min_y).max(0.0),
242                    ))
243                }
244            }
245            Self::DrawViewport3D { bounds, .. } => Some(*bounds),
246            Self::DrawCanvas2D { bounds, .. } => Some(*bounds),
247            Self::DrawSvgPath { bounds, .. } => Some(*bounds),
248            Self::DrawGpuPath { bounds, .. } => Some(*bounds),
249            Self::DrawImage { bounds, .. } => Some(*bounds),
250            Self::PushClip { bounds, .. } => Some(*bounds),
251            Self::PopClip => None,
252            Self::PushTransform { .. } | Self::PopTransform => None,
253        }
254    }
255}
256
257/// A serialized sequence of render instructions for a single frame.
258#[derive(Debug, Default, Clone, PartialEq)]
259pub struct DisplayList {
260    pub commands: Vec<DrawCommand>,
261}
262
263impl DisplayList {
264    pub fn new() -> Self {
265        Self::default()
266    }
267
268    pub fn push(&mut self, cmd: DrawCommand) {
269        self.commands.push(cmd);
270    }
271
272    pub fn commands(&self) -> &[DrawCommand] {
273        &self.commands
274    }
275
276    pub fn clear(&mut self) {
277        self.commands.clear();
278    }
279
280    pub fn len(&self) -> usize {
281        self.commands.len()
282    }
283
284    pub fn is_empty(&self) -> bool {
285        self.commands.is_empty()
286    }
287}
288
289/// Tracks damaged (dirty) screen regions across frames to minimize redraw overhead.
290#[derive(Debug, Default, Clone, PartialEq)]
291pub struct DamageTracker {
292    pub dirty_rects: Vec<Rect>,
293}
294
295impl DamageTracker {
296    pub fn new() -> Self {
297        Self::default()
298    }
299
300    pub fn add_damage(&mut self, rect: Rect) {
301        if rect.width > 0.0 && rect.height > 0.0 {
302            self.dirty_rects.push(rect);
303        }
304    }
305
306    /// Computes the minimal bounding rectangle covering all dirty regions.
307    pub fn bounding_damage(&self) -> Option<Rect> {
308        if self.dirty_rects.is_empty() {
309            return None;
310        }
311
312        let mut min_x = f32::MAX;
313        let mut min_y = f32::MAX;
314        let mut max_x = f32::MIN;
315        let mut max_y = f32::MIN;
316
317        for r in &self.dirty_rects {
318            min_x = min_x.min(r.x);
319            min_y = min_y.min(r.y);
320            max_x = max_x.max(r.max_x());
321            max_y = max_y.max(r.max_y());
322        }
323
324        Some(Rect::new(min_x, min_y, max_x - min_x, max_y - min_y))
325    }
326
327    /// Hierarchically clusters dirty rects into isolated non-overlapping bounding regions.
328    ///
329    /// Prevents disjoint localized damage (e.g., caret blink at top-left, button ripple at bottom-right)
330    /// from inflating into a catastrophic full-canvas bounding box.
331    pub fn cluster_damage_rects(&self) -> Vec<Rect> {
332        if self.dirty_rects.is_empty() {
333            return Vec::new();
334        }
335
336        let mut clusters: Vec<Rect> = Vec::new();
337        for &r in &self.dirty_rects {
338            let mut merged = false;
339            for cluster in &mut clusters {
340                // If rects intersect or are within a close margin (16px), merge them
341                let expanded = Rect::new(
342                    cluster.x - 16.0,
343                    cluster.y - 16.0,
344                    cluster.width + 32.0,
345                    cluster.height + 32.0,
346                );
347                if expanded.intersect(r).is_some() {
348                    let min_x = cluster.x.min(r.x);
349                    let min_y = cluster.y.min(r.y);
350                    let max_x = cluster.max_x().max(r.max_x());
351                    let max_y = cluster.max_y().max(r.max_y());
352                    *cluster = Rect::new(min_x, min_y, max_x - min_x, max_y - min_y);
353                    merged = true;
354                    break;
355                }
356            }
357            if !merged {
358                clusters.push(r);
359            }
360        }
361        clusters
362    }
363
364    pub fn reset(&mut self) {
365        self.dirty_rects.clear();
366    }
367}
368
369/// Compiles a `LayoutNode` tree into a `DisplayList` following CSS 2.1 Appendix E.
370pub struct Compositor;
371
372impl Compositor {
373    /// Compiles a layout tree root into an ordered DisplayList.
374    pub fn build_display_list(root: &LayoutNode) -> DisplayList {
375        Self::build_display_list_with_viewport(root, None)
376    }
377
378    /// Compiles a layout tree root into an ordered DisplayList with spatial viewport culling.
379    /// Elements outside the active viewport buffer zone are culled from command emission.
380    pub fn build_display_list_with_viewport(
381        root: &LayoutNode,
382        viewport: Option<Rect>,
383    ) -> DisplayList {
384        let mut list = DisplayList::new();
385        let cull_rect = viewport.map(|vp| {
386            let buffer_y = 1200.0;
387            let buffer_x = 300.0;
388            Rect::new(
389                vp.x - buffer_x,
390                vp.y - buffer_y,
391                vp.width + buffer_x * 2.0,
392                vp.height + buffer_y * 2.0,
393            )
394        });
395        Self::paint_stacking_context_guarded(root, &mut list, cull_rect, 0);
396        list
397    }
398
399    /// Determines if an element establishes a new Stacking Context (without parent display context).
400    ///
401    /// For flex/grid item `z-index` awareness, tree traversals use
402    /// [`LayoutNode::establishes_stacking_context_in`].
403    #[inline]
404    pub fn establishes_stacking_context(node: &LayoutNode, is_root: bool) -> bool {
405        node.establishes_stacking_context_in(None, is_root)
406    }
407
408    /// Collects the border boxes of every cell in a table subtree.
409    fn collect_table_cells<'a>(node: &'a LayoutNode, out: &mut Vec<&'a LayoutNode>) {
410        if node.style.display == Display::TableCell {
411            out.push(node);
412            return;
413        }
414        for child in &node.children {
415            Self::collect_table_cells(child, out);
416        }
417    }
418
419    /// Paints the shared grid of a collapsed-border table once.
420    ///
421    /// Each cell paints its own border box, so adjacent rows would otherwise
422    /// draw the shared horizontal border twice (one row per side) and adjacent
423    /// columns would draw parallel strokes. In the collapsed model every
424    /// boundary is a single line snapped to whole device pixels, matching the
425    /// Chromium reference. Cell borders are suppressed separately.
426    fn paint_collapsed_table_grid(node: &LayoutNode, list: &mut DisplayList) {
427        if node.style.display != Display::Table
428            || node.style.border_collapse != BorderCollapse::Collapse
429        {
430            return;
431        }
432
433        if let Some(ref grid) = node.table_grid {
434            // CSS 2.1 §17.6.2: Draw collapsed horizontal border segments centered on grid lines
435            for r in 0..=grid.num_rows {
436                let y = grid.row_positions[r];
437                for c in 0..grid.num_cols {
438                    let edge = &grid.horizontal_edges[r][c];
439                    if edge.style == BorderStyle::Hidden
440                        || edge.style == BorderStyle::None
441                        || edge.width <= 0.0
442                    {
443                        continue;
444                    }
445                    let x0 = grid.col_positions[c];
446                    let x1 = grid.col_positions[c + 1];
447                    let w = (x1 - x0).max(1.0);
448                    let color = edge.color.unwrap_or(node.style.color);
449                    let thickness = edge.width.round().max(1.0);
450                    let draw_y = (y - 0.5 * thickness).round();
451                    list.push(DrawCommand::DrawRect {
452                        bounds: Rect::new(x0.round(), draw_y, w.round(), thickness),
453                        color,
454                    });
455                }
456            }
457
458            // CSS 2.1 §17.6.2: Draw collapsed vertical border segments centered on grid lines
459            for r in 0..grid.num_rows {
460                let y0 = grid.row_positions[r];
461                let y1 = grid.row_positions[r + 1];
462                let h = (y1 - y0).max(1.0);
463                for c in 0..=grid.num_cols {
464                    let edge = &grid.vertical_edges[r][c];
465                    if edge.style == BorderStyle::Hidden
466                        || edge.style == BorderStyle::None
467                        || edge.width <= 0.0
468                    {
469                        continue;
470                    }
471                    let x = grid.col_positions[c];
472                    let color = edge.color.unwrap_or(node.style.color);
473                    let thickness = edge.width.round().max(1.0);
474                    let draw_x = (x - 0.5 * thickness).round();
475                    list.push(DrawCommand::DrawRect {
476                        bounds: Rect::new(draw_x, y0.round(), thickness, h.round()),
477                        color,
478                    });
479                }
480            }
481            return;
482        }
483
484        let mut cells: Vec<&LayoutNode> = Vec::new();
485        Self::collect_table_cells(node, &mut cells);
486        cells.retain(|cell| {
487            cell.geometry.border_box.width > 0.0 && cell.geometry.border_box.height > 0.0
488        });
489        if cells.is_empty() {
490            return;
491        }
492
493        let mut stroke_width = 0.0f32;
494        let mut stroke_color: Option<Color> = None;
495        for cell in &cells {
496            let widths = cell.style.border_width;
497            let width = widths
498                .top
499                .max(widths.right)
500                .max(widths.bottom)
501                .max(widths.left);
502            if width > stroke_width {
503                stroke_width = width;
504                stroke_color = cell.style.border_color;
505            }
506        }
507        if stroke_width <= 0.0 {
508            return;
509        }
510        let color = stroke_color.unwrap_or(node.style.color);
511
512        let mut xs: Vec<f32> = Vec::new();
513        let mut ys: Vec<f32> = Vec::new();
514        for cell in &cells {
515            let b = cell.geometry.border_box;
516            xs.push(b.x);
517            xs.push(b.x + b.width);
518            ys.push(b.y);
519            ys.push(b.y + b.height);
520        }
521        let snap = |v: f32| v.round();
522        xs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
523        xs.dedup_by(|a, b| (*a - *b).abs() < 0.01);
524        ys.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
525        ys.dedup_by(|a, b| (*a - *b).abs() < 0.01);
526
527        let top = snap(*ys.first().unwrap_or(&0.0));
528        let bottom = snap(*ys.last().unwrap_or(&0.0));
529        let line_h = (bottom - top + 1.0).max(1.0);
530        let left = snap(node.geometry.border_box.x);
531        let right = snap(*xs.last().unwrap_or(&0.0));
532        let line_w = (right - left).max(1.0);
533        let thickness = stroke_width.round().max(1.0);
534
535        for x in xs {
536            let snapped = snap(x);
537            // The final right edge paints inside the table's right boundary.
538            let draw_x = if (snapped - right).abs() < 0.01 {
539                snapped - thickness
540            } else {
541                snapped
542            };
543            list.push(DrawCommand::DrawRect {
544                bounds: Rect::new(draw_x, top, thickness, line_h),
545                color,
546            });
547        }
548
549        for y in ys {
550            let snapped = snap(y);
551            list.push(DrawCommand::DrawRect {
552                bounds: Rect::new(left, snapped, line_w, thickness),
553                color,
554            });
555        }
556    }
557
558    /// Evaluates if an inline element or its descendants have paintable atomic/SVG non-text visual content.
559    fn inline_has_paintable_non_text_content(node: &LayoutNode) -> bool {
560        if !node.svg_items.is_empty()
561            || node.svg_path.is_some()
562            || node.image.is_some()
563            || node.scene_3d.is_some()
564        {
565            return true;
566        }
567        for c in &node.children {
568            if c.style.display != Display::Inline || Self::inline_has_paintable_non_text_content(c)
569            {
570                return true;
571            }
572        }
573        false
574    }
575
576    /// Maximum allowable recursion depth for stacking context and layout node display list composition.
577    pub const MAX_COMPOSITOR_DEPTH: usize = 1024;
578
579    /// Paints a stacking context according to the 7-layer CSS 2.1 Appendix E algorithm.
580    pub fn paint_stacking_context(node: &LayoutNode, list: &mut DisplayList) {
581        Self::paint_stacking_context_culled(node, list, None);
582    }
583
584    /// Paints a stacking context with optional spatial viewport culling.
585    pub fn paint_stacking_context_culled(
586        node: &LayoutNode,
587        list: &mut DisplayList,
588        cull: Option<Rect>,
589    ) {
590        Self::paint_stacking_context_guarded(node, list, cull, 0);
591    }
592
593    /// Paints a stacking context with optional spatial viewport culling and active recursion depth guard.
594    pub fn paint_stacking_context_guarded(
595        node: &LayoutNode,
596        list: &mut DisplayList,
597        cull: Option<Rect>,
598        depth: usize,
599    ) {
600        Self::paint_stacking_context_inner(node, list, cull, cull, &[], depth == 0, depth);
601        if depth == 0 {
602            Self::paint_top_layer_portals(node, list, cull);
603        }
604    }
605
606    fn collect_top_layer_portals<'a>(node: &'a LayoutNode, out: &mut Vec<&'a LayoutNode>) {
607        let mut stack: Vec<(&'a LayoutNode, usize)> = vec![(node, 0)];
608        while let Some((cur, depth)) = stack.pop() {
609            if depth > 0 && cur.is_top_layer {
610                out.push(cur);
611            }
612            if depth >= Self::MAX_COMPOSITOR_DEPTH {
613                continue;
614            }
615            for child in cur.children.iter().rev() {
616                if child.style.display == Display::None
617                    || child.style.content_visibility
618                        == strata_style::types::ContentVisibility::Hidden
619                {
620                    continue;
621                }
622                stack.push((child, depth + 1));
623            }
624        }
625    }
626
627    fn paint_top_layer_portals(node: &LayoutNode, list: &mut DisplayList, root_cull: Option<Rect>) {
628        let mut portals = Vec::new();
629        Self::collect_top_layer_portals(node, &mut portals);
630        for portal in portals {
631            Self::paint_stacking_context_inner(portal, list, root_cull, root_cull, &[], false, 1);
632        }
633    }
634
635    fn node_clip_scroll_step(node: &LayoutNode) -> Option<ClipScrollStep> {
636        let bounds = node.geometry.border_box;
637        let border_radius = node.style.border_radius;
638        let has_any_radius = border_radius.top_left > 0.0
639            || border_radius.top_right > 0.0
640            || border_radius.bottom_left > 0.0
641            || border_radius.bottom_right > 0.0;
642        let clips_overflow = node.style.overflow_x != Overflow::Visible
643            || node.style.overflow_y != Overflow::Visible;
644        let should_clip =
645            clips_overflow || (has_any_radius && (node.image.is_some() || node.scene_3d.is_some()));
646        let clip = if should_clip {
647            let clip_bounds = if clips_overflow
648                && node.geometry.padding_box.width > 0.0
649                && node.geometry.padding_box.height > 0.0
650            {
651                node.geometry.padding_box
652            } else {
653                bounds
654            };
655            Some((clip_bounds, border_radius))
656        } else {
657            None
658        };
659        let scroll_offset = (node.geometry.scroll_offset.x, node.geometry.scroll_offset.y);
660        let is_fixed_cb = node.style.establishes_fixed_containing_block();
661        let is_abs_cb = node.style.position != Position::Static || is_fixed_cb;
662
663        if clip.is_some()
664            || scroll_offset.0 != 0.0
665            || scroll_offset.1 != 0.0
666            || is_abs_cb
667            || is_fixed_cb
668        {
669            Some(ClipScrollStep {
670                clip,
671                scroll_offset,
672                is_abs_cb,
673                is_fixed_cb,
674            })
675        } else {
676            None
677        }
678    }
679
680    #[inline]
681    fn effective_steps(position: Position, steps: &[ClipScrollStep]) -> &[ClipScrollStep] {
682        match position {
683            Position::Fixed => match steps.iter().rposition(|s| s.is_fixed_cb) {
684                Some(idx) => &steps[..=idx],
685                None => &[],
686            },
687            Position::Absolute => match steps.iter().rposition(|s| s.is_abs_cb) {
688                Some(idx) => &steps[..=idx],
689                None => &[],
690            },
691            Position::Static | Position::Relative | Position::Sticky => steps,
692        }
693    }
694
695    fn push_clip_scroll_steps(steps: &[ClipScrollStep], list: &mut DisplayList) {
696        for step in steps {
697            if let Some((bounds, radius)) = step.clip {
698                list.push(DrawCommand::PushClip { bounds, radius });
699            }
700            if step.scroll_offset.0 != 0.0 || step.scroll_offset.1 != 0.0 {
701                let mat = strata_primitives::geom::Matrix4x4::translation(
702                    -step.scroll_offset.0,
703                    -step.scroll_offset.1,
704                    0.0,
705                );
706                list.push(DrawCommand::PushTransform { matrix: mat });
707            }
708        }
709    }
710
711    fn pop_clip_scroll_steps(steps: &[ClipScrollStep], list: &mut DisplayList) {
712        for step in steps.iter().rev() {
713            if step.scroll_offset.0 != 0.0 || step.scroll_offset.1 != 0.0 {
714                list.push(DrawCommand::PopTransform);
715            }
716            if step.clip.is_some() {
717                list.push(DrawCommand::PopClip);
718            }
719        }
720    }
721
722    fn cull_with_steps(base_cull: Option<Rect>, steps: &[ClipScrollStep]) -> Option<Rect> {
723        let mut current = base_cull;
724        for step in steps {
725            if let Some((clip_bounds, _)) = step.clip {
726                if clip_bounds.width > 0.0 && clip_bounds.height > 0.0 {
727                    if let Some(c) = current {
728                        current = Some(
729                            clip_bounds
730                                .intersect(c)
731                                .unwrap_or_else(|| Rect::new(0.0, 0.0, -1.0, -1.0)),
732                        );
733                    }
734                }
735            }
736        }
737        current
738    }
739
740    fn subtree_has_fixed_escape(node: &LayoutNode, depth: usize) -> bool {
741        if depth >= Self::MAX_COMPOSITOR_DEPTH
742            || node.style.display == Display::None
743            || node.is_top_layer
744        {
745            return false;
746        }
747        if node.style.position == Position::Fixed {
748            return true;
749        }
750        if node.style.establishes_fixed_containing_block() {
751            return false;
752        }
753        node.children
754            .iter()
755            .any(|c| Self::subtree_has_fixed_escape(c, depth + 1))
756    }
757
758    fn collect_hoisted_participants<'a>(
759        parent: &'a LayoutNode,
760        current_steps: &mut Vec<ClipScrollStep>,
761        negative_z: &mut Vec<HoistedParticipant<'a>>,
762        auto_or_zero_z: &mut Vec<HoistedParticipant<'a>>,
763        positive_z: &mut Vec<HoistedParticipant<'a>>,
764        depth: usize,
765    ) {
766        if depth >= Self::MAX_COMPOSITOR_DEPTH {
767            return;
768        }
769        let has_line_boxes = !parent.line_boxes.is_empty();
770        let parent_display = parent.style.display;
771
772        for child in &parent.children {
773            if child.is_top_layer
774                || child.style.display == Display::None
775                || child.style.content_visibility == strata_style::types::ContentVisibility::Hidden
776            {
777                continue;
778            }
779            if has_line_boxes
780                && (child.text.is_some()
781                    || (matches!(child.style.display, Display::Inline)
782                        && !Self::inline_has_paintable_non_text_content(child)))
783            {
784                continue;
785            }
786
787            if child.establishes_stacking_context_in(Some(parent_display), false) {
788                let z = child.style.z_index.unwrap_or(0);
789                let entry = HoistedParticipant {
790                    node: child,
791                    is_sc: true,
792                    steps: current_steps.clone(),
793                };
794                if z < 0 {
795                    negative_z.push(entry);
796                } else if z > 0 {
797                    positive_z.push(entry);
798                } else {
799                    auto_or_zero_z.push(entry);
800                }
801            } else {
802                if child.style.position != Position::Static {
803                    auto_or_zero_z.push(HoistedParticipant {
804                        node: child,
805                        is_sc: false,
806                        steps: current_steps.clone(),
807                    });
808                }
809                if !child.children.is_empty() {
810                    let step = Self::node_clip_scroll_step(child);
811                    let pushed = step.is_some();
812                    if let Some(s) = step {
813                        current_steps.push(s);
814                    }
815                    Self::collect_hoisted_participants(
816                        child,
817                        current_steps,
818                        negative_z,
819                        auto_or_zero_z,
820                        positive_z,
821                        depth + 1,
822                    );
823                    if pushed {
824                        current_steps.pop();
825                    }
826                }
827            }
828        }
829    }
830
831    #[allow(clippy::too_many_arguments)]
832    fn paint_stacking_context_inner(
833        node: &LayoutNode,
834        list: &mut DisplayList,
835        cull: Option<Rect>,
836        root_cull: Option<Rect>,
837        inherited_steps: &[ClipScrollStep],
838        is_root: bool,
839        depth: usize,
840    ) {
841        if depth >= Self::MAX_COMPOSITOR_DEPTH {
842            return;
843        }
844        if node.style.display == Display::None {
845            return;
846        }
847        if node.style.content_visibility == strata_style::types::ContentVisibility::Hidden {
848            return;
849        }
850
851        let node_eff_steps = Self::effective_steps(node.style.position, inherited_steps);
852        let base_cull = if node.style.position == Position::Fixed
853            && !inherited_steps.iter().any(|s| s.is_fixed_cb)
854        {
855            root_cull
856        } else {
857            Self::cull_with_steps(cull, node_eff_steps)
858        };
859
860        if let Some(c) = base_cull {
861            if (c.width < 0.0 || c.height < 0.0) && !Self::subtree_has_fixed_escape(node, depth) {
862                return;
863            }
864        }
865
866        let bounds = node.geometry.border_box;
867        let border_radius = node.style.border_radius;
868        let has_any_radius = border_radius.top_left > 0.0
869            || border_radius.top_right > 0.0
870            || border_radius.bottom_left > 0.0
871            || border_radius.bottom_right > 0.0;
872        let clips_overflow = node.style.overflow_x != Overflow::Visible
873            || node.style.overflow_y != Overflow::Visible;
874        let should_clip =
875            clips_overflow || (has_any_radius && (node.image.is_some() || node.scene_3d.is_some()));
876
877        let mut static_cull_empty = base_cull.is_some_and(|c| c.width < 0.0 || c.height < 0.0);
878
879        let child_cull = if clips_overflow
880            && bounds.width > 0.0
881            && bounds.height > 0.0
882            && node.style.position != Position::Fixed
883        {
884            match base_cull {
885                Some(c) => {
886                    if c.width < 0.0 || c.height < 0.0 {
887                        Some(c)
888                    } else {
889                        match bounds.intersect(c) {
890                            Some(ic) => Some(ic),
891                            None => {
892                                if !Self::subtree_has_fixed_escape(node, depth) {
893                                    return;
894                                }
895                                static_cull_empty = true;
896                                Some(Rect::new(0.0, 0.0, -1.0, -1.0))
897                            }
898                        }
899                    }
900                }
901                None => None,
902            }
903        } else {
904            base_cull
905        };
906
907        let is_visible = !static_cull_empty
908            && match base_cull {
909                Some(c) => {
910                    if node.style.position == Position::Fixed {
911                        true
912                    } else if bounds.width > 0.0 && bounds.height > 0.0 {
913                        bounds.intersect(c).is_some()
914                    } else {
915                        true
916                    }
917                }
918                None => true,
919            };
920
921        let has_isolation = node.style.isolation == Isolation::Isolate;
922        let has_blend_mode = node.style.mix_blend_mode != BlendMode::Normal;
923        let has_filter_cfg = node.style.filter.as_ref().is_some_and(|f| !f.is_empty());
924        let has_clip_path_cfg = node
925            .style
926            .clip_path
927            .as_ref()
928            .is_some_and(|cp| !cp.is_none());
929        let transform_matrix = if node.style.has_transform() {
930            Some(
931                node.style
932                    .compute_transform_matrix(bounds.width, bounds.height),
933            )
934        } else {
935            None
936        };
937        let has_opacity = node.style.opacity < 0.999;
938        let has_backdrop_cfg = node
939            .style
940            .backdrop_filter
941            .as_ref()
942            .is_some_and(|bf| !bf.is_empty());
943
944        let has_group_effect = has_isolation
945            || has_blend_mode
946            || has_filter_cfg
947            || has_clip_path_cfg
948            || transform_matrix.is_some()
949            || has_opacity
950            || has_backdrop_cfg;
951
952        let wrap_inherited_outside_group = has_group_effect
953            && (node.style.establishes_fixed_containing_block()
954                || !Self::subtree_has_fixed_escape(node, depth));
955
956        if wrap_inherited_outside_group {
957            Self::push_clip_scroll_steps(node_eff_steps, list);
958        }
959
960        if has_isolation {
961            list.push(DrawCommand::PushIsolation { isolate: true });
962        }
963        if has_blend_mode {
964            list.push(DrawCommand::PushBlendMode {
965                mode: node.style.mix_blend_mode,
966            });
967        }
968        let has_filter = if let Some(ref f) = node.style.filter {
969            if !f.is_empty() {
970                list.push(DrawCommand::PushFilter {
971                    bounds,
972                    filter: f.clone(),
973                });
974                true
975            } else {
976                false
977            }
978        } else {
979            false
980        };
981        let has_clip_path = if let Some(ref cp) = node.style.clip_path {
982            if !cp.is_none() {
983                list.push(DrawCommand::PushClipPath {
984                    bounds,
985                    clip_path: cp.clone(),
986                });
987                true
988            } else {
989                false
990            }
991        } else {
992            false
993        };
994        if let Some(mat) = transform_matrix {
995            list.push(DrawCommand::PushTransform { matrix: mat });
996        }
997        if has_opacity {
998            list.push(DrawCommand::PushOpacity {
999                alpha: node.style.opacity,
1000            });
1001        }
1002        let has_backdrop_filter = if let Some(ref bf) = node.style.backdrop_filter {
1003            if !bf.is_empty() {
1004                list.push(DrawCommand::PushBackdropFilter {
1005                    bounds,
1006                    radius: border_radius,
1007                    filter: bf.clone(),
1008                });
1009                true
1010            } else {
1011                false
1012            }
1013        } else {
1014            false
1015        };
1016
1017        // Build base clip/scroll step chain for hoisted descendants of this stacking context.
1018        let mut hoisted_base_steps: Vec<ClipScrollStep> = if wrap_inherited_outside_group {
1019            Vec::new()
1020        } else {
1021            node_eff_steps.to_vec()
1022        };
1023        let own_clip_bounds = if clips_overflow
1024            && node.geometry.padding_box.width > 0.0
1025            && node.geometry.padding_box.height > 0.0
1026        {
1027            node.geometry.padding_box
1028        } else {
1029            bounds
1030        };
1031        let own_is_fixed_cb = node.style.establishes_fixed_containing_block();
1032        let own_is_abs_cb = node.style.position != Position::Static || own_is_fixed_cb || is_root;
1033        let has_scroll_offset =
1034            node.geometry.scroll_offset.x != 0.0 || node.geometry.scroll_offset.y != 0.0;
1035        let own_clip_opt = if should_clip {
1036            Some((own_clip_bounds, border_radius))
1037        } else {
1038            None
1039        };
1040        if own_clip_opt.is_some() || has_scroll_offset || own_is_abs_cb || own_is_fixed_cb {
1041            hoisted_base_steps.push(ClipScrollStep {
1042                clip: own_clip_opt,
1043                scroll_offset: (node.geometry.scroll_offset.x, node.geometry.scroll_offset.y),
1044                is_abs_cb: own_is_abs_cb,
1045                is_fixed_cb: own_is_fixed_cb,
1046            });
1047        }
1048
1049        // Collect hoisted stacking participants across non-stacking-context descendants (CSS 2.1 Appendix E)
1050        let mut negative_z: Vec<HoistedParticipant<'_>> = Vec::new();
1051        let mut auto_or_zero_z: Vec<HoistedParticipant<'_>> = Vec::new();
1052        let mut positive_z: Vec<HoistedParticipant<'_>> = Vec::new();
1053        Self::collect_hoisted_participants(
1054            node,
1055            &mut hoisted_base_steps,
1056            &mut negative_z,
1057            &mut auto_or_zero_z,
1058            &mut positive_z,
1059            depth + 1,
1060        );
1061
1062        // Stable ascending z-index sort preserves DOM order on ties
1063        negative_z.sort_by_key(|p| p.node.style.z_index.unwrap_or(0));
1064        positive_z.sort_by_key(|p| p.node.style.z_index.unwrap_or(0));
1065
1066        // Direct in-flow static non-stacking-context children (Layers 3, 4, 5)
1067        let mut in_flow_blocks: Vec<&LayoutNode> = Vec::new();
1068        let mut floats: Vec<&LayoutNode> = Vec::new();
1069        let mut in_flow_inlines: Vec<&LayoutNode> = Vec::new();
1070
1071        if !static_cull_empty {
1072            let has_line_boxes = !node.line_boxes.is_empty();
1073            let parent_display = node.style.display;
1074            for child in &node.children {
1075                if child.is_top_layer
1076                    || child.style.display == Display::None
1077                    || child.style.content_visibility
1078                        == strata_style::types::ContentVisibility::Hidden
1079                {
1080                    continue;
1081                }
1082                if has_line_boxes
1083                    && (child.text.is_some()
1084                        || (matches!(child.style.display, Display::Inline)
1085                            && !Self::inline_has_paintable_non_text_content(child)))
1086                {
1087                    continue;
1088                }
1089                if child.establishes_stacking_context_in(Some(parent_display), false)
1090                    || child.style.position != Position::Static
1091                {
1092                    continue;
1093                }
1094                if let Some(c) = child_cull {
1095                    if child.geometry.border_box.y > c.y + c.height {
1096                        continue;
1097                    }
1098                    if child.geometry.border_box.height > 0.0
1099                        && child.geometry.border_box.y + child.geometry.border_box.height < c.y
1100                    {
1101                        continue;
1102                    }
1103                }
1104                if child.style.float != strata_style::types::Float::None {
1105                    floats.push(child);
1106                } else {
1107                    match child.style.display {
1108                        Display::Inline
1109                        | Display::InlineBlock
1110                        | Display::InlineFlex
1111                        | Display::InlineGrid => {
1112                            in_flow_inlines.push(child);
1113                        }
1114                        _ => {
1115                            in_flow_blocks.push(child);
1116                        }
1117                    }
1118                }
1119            }
1120        }
1121
1122        let inner_inherited_steps: &[ClipScrollStep] = if wrap_inherited_outside_group {
1123            &[]
1124        } else {
1125            node_eff_steps
1126        };
1127
1128        // Layer 1: Background and borders of the element establishing the stacking context
1129        if !inner_inherited_steps.is_empty() {
1130            Self::push_clip_scroll_steps(inner_inherited_steps, list);
1131        }
1132        if is_visible {
1133            Self::paint_node_box_decorations(node, list);
1134        }
1135        if !negative_z.is_empty() && !inner_inherited_steps.is_empty() {
1136            Self::pop_clip_scroll_steps(inner_inherited_steps, list);
1137        }
1138
1139        // Layer 2: Child stacking contexts with negative z-index
1140        let child_root_cull = if own_is_fixed_cb {
1141            child_cull
1142        } else {
1143            root_cull
1144        };
1145        for entry in &negative_z {
1146            Self::paint_stacking_context_inner(
1147                entry.node,
1148                list,
1149                root_cull,
1150                child_root_cull,
1151                &entry.steps,
1152                false,
1153                depth + 1,
1154            );
1155        }
1156
1157        if !negative_z.is_empty() && !inner_inherited_steps.is_empty() {
1158            Self::push_clip_scroll_steps(inner_inherited_steps, list);
1159        }
1160
1161        // Own content clip + replaced/text/SVG content + Layers 3..5 (static in-flow descendants)
1162        if should_clip && is_visible {
1163            list.push(DrawCommand::PushClip {
1164                bounds: own_clip_bounds,
1165                radius: border_radius,
1166            });
1167        }
1168        if is_visible {
1169            Self::paint_node_foreground_content(node, list, base_cull);
1170        }
1171
1172        if has_scroll_offset && !static_cull_empty {
1173            let mat = strata_primitives::geom::Matrix4x4::translation(
1174                -node.geometry.scroll_offset.x,
1175                -node.geometry.scroll_offset.y,
1176                0.0,
1177            );
1178            list.push(DrawCommand::PushTransform { matrix: mat });
1179        }
1180
1181        // Layer 3: In-flow, non-inline, non-positioned block descendants
1182        for child in in_flow_blocks {
1183            Self::paint_node_content_inner(child, list, child_cull, true, depth + 1);
1184        }
1185
1186        // Layer 4: Non-positioned floating descendants
1187        for child in floats {
1188            Self::paint_node_content_inner(child, list, child_cull, true, depth + 1);
1189        }
1190
1191        // Layer 5: In-flow inline-level descendants
1192        for child in in_flow_inlines {
1193            Self::paint_node_content_inner(child, list, child_cull, true, depth + 1);
1194        }
1195
1196        // Collapsed table boundaries paint once above cell content.
1197        if !static_cull_empty {
1198            Self::paint_collapsed_table_grid(node, list);
1199        }
1200
1201        if has_scroll_offset && !static_cull_empty {
1202            list.push(DrawCommand::PopTransform);
1203        }
1204        if should_clip && is_visible {
1205            list.push(DrawCommand::PopClip);
1206        }
1207        if !inner_inherited_steps.is_empty() {
1208            Self::pop_clip_scroll_steps(inner_inherited_steps, list);
1209        }
1210
1211        // Layer 6: Positioned descendants with z-index: auto and child stacking contexts with z-index: 0
1212        for entry in &auto_or_zero_z {
1213            if entry.is_sc {
1214                Self::paint_stacking_context_inner(
1215                    entry.node,
1216                    list,
1217                    root_cull,
1218                    child_root_cull,
1219                    &entry.steps,
1220                    false,
1221                    depth + 1,
1222                );
1223            } else {
1224                let eff = Self::effective_steps(entry.node.style.position, &entry.steps);
1225                let entry_cull = Self::cull_with_steps(child_root_cull, eff);
1226                if entry_cull.is_none_or(|c| c.width >= 0.0 && c.height >= 0.0) {
1227                    Self::push_clip_scroll_steps(eff, list);
1228                    Self::paint_node_content_inner(entry.node, list, entry_cull, true, depth + 1);
1229                    Self::pop_clip_scroll_steps(eff, list);
1230                }
1231            }
1232        }
1233
1234        // Layer 7: Child stacking contexts with positive z-index
1235        for entry in &positive_z {
1236            Self::paint_stacking_context_inner(
1237                entry.node,
1238                list,
1239                root_cull,
1240                child_root_cull,
1241                &entry.steps,
1242                false,
1243                depth + 1,
1244            );
1245        }
1246
1247        if has_backdrop_filter {
1248            list.push(DrawCommand::PopBackdropFilter);
1249        }
1250        if transform_matrix.is_some() {
1251            list.push(DrawCommand::PopTransform);
1252        }
1253        if has_clip_path {
1254            list.push(DrawCommand::PopClipPath);
1255        }
1256        if has_filter {
1257            list.push(DrawCommand::PopFilter);
1258        }
1259        if has_blend_mode {
1260            list.push(DrawCommand::PopBlendMode);
1261        }
1262        if has_isolation {
1263            list.push(DrawCommand::PopIsolation);
1264        }
1265        if has_opacity {
1266            list.push(DrawCommand::PopOpacity);
1267        }
1268        if wrap_inherited_outside_group {
1269            Self::pop_clip_scroll_steps(node_eff_steps, list);
1270        }
1271    }
1272
1273    fn paint_node_box_decorations(node: &LayoutNode, list: &mut DisplayList) {
1274        let bounds = node.geometry.border_box;
1275        let border_radius = node.style.border_radius;
1276        let has_any_radius = border_radius.top_left > 0.0
1277            || border_radius.top_right > 0.0
1278            || border_radius.bottom_left > 0.0
1279            || border_radius.bottom_right > 0.0;
1280        let has_any_border_width = node.style.border_width.top > 0.0
1281            || node.style.border_width.right > 0.0
1282            || node.style.border_width.bottom > 0.0
1283            || node.style.border_width.left > 0.0;
1284        let draw_border_separately = node.style.border_style != BorderStyle::None
1285            && node.style.border_style != BorderStyle::Hidden
1286            && has_any_border_width
1287            && node.style.border_color.is_some()
1288            && !(node.style.display == Display::TableCell
1289                && node.style.border_collapse == BorderCollapse::Collapse);
1290        let rounded_border_color = if draw_border_separately
1291            || node.style.border_style == BorderStyle::None
1292            || node.style.border_style == BorderStyle::Hidden
1293        {
1294            None
1295        } else {
1296            node.style.border_color
1297        };
1298
1299        // Outer Box Shadows (rendered behind background)
1300        for shadow in &node.style.box_shadow {
1301            if !shadow.inset {
1302                list.push(DrawCommand::DrawShadow {
1303                    bounds,
1304                    shadow: shadow.clone(),
1305                    border_radius,
1306                });
1307            }
1308        }
1309
1310        // Solid / Rounded Background
1311        if let Some(bg_color) = node.style.background_color {
1312            if has_any_radius {
1313                list.push(DrawCommand::DrawRoundedRect {
1314                    bounds,
1315                    color: bg_color,
1316                    border_radius,
1317                    border_width: node.style.border_width,
1318                    border_color: rounded_border_color,
1319                });
1320            } else if bg_color.a > 0 {
1321                list.push(DrawCommand::DrawRect {
1322                    bounds,
1323                    color: bg_color,
1324                });
1325            }
1326        }
1327
1328        // Gradient Background
1329        if let Some(ref grad) = node.style.background_gradient {
1330            match grad {
1331                strata_style::types::Gradient::Linear { angle_deg, stops } => {
1332                    list.push(DrawCommand::DrawLinearGradient {
1333                        bounds,
1334                        angle_deg: *angle_deg,
1335                        stops: stops.clone(),
1336                        border_radius,
1337                    });
1338                }
1339                strata_style::types::Gradient::Radial { center, stops } => {
1340                    list.push(DrawCommand::DrawRadialGradient {
1341                        bounds,
1342                        center: *center,
1343                        stops: stops.clone(),
1344                        border_radius,
1345                    });
1346                }
1347                strata_style::types::Gradient::Conic {
1348                    angle_deg,
1349                    center: _,
1350                    stops,
1351                } => {
1352                    list.push(DrawCommand::DrawLinearGradient {
1353                        bounds,
1354                        angle_deg: *angle_deg,
1355                        stops: stops.clone(),
1356                        border_radius,
1357                    });
1358                }
1359            }
1360        }
1361
1362        // Inset Box Shadows (rendered over background)
1363        for shadow in &node.style.box_shadow {
1364            if shadow.inset {
1365                list.push(DrawCommand::DrawInsetShadow {
1366                    bounds,
1367                    shadow: shadow.clone(),
1368                    border_radius,
1369                });
1370            }
1371        }
1372
1373        // Borders emitted independently so the style parser can resolve
1374        // solid, dashed, dotted, and double strokes.
1375        if draw_border_separately {
1376            if let Some(border_color) = node.style.border_color {
1377                list.push(DrawCommand::DrawBorder {
1378                    bounds,
1379                    widths: node.style.border_width,
1380                    color: border_color,
1381                    border_radius,
1382                    style: node.style.border_style,
1383                });
1384            }
1385        }
1386
1387        // CSS outlines sit at the outside edge of the border box.
1388        if node.style.outline_width > 0.0 && node.style.outline_style != BorderStyle::None {
1389            if let Some(outline_color) = node.style.outline_color {
1390                let offset = node.style.outline_offset;
1391                let outline_radius = BorderRadius {
1392                    top_left: (border_radius.top_left + offset).max(0.0),
1393                    top_right: (border_radius.top_right + offset).max(0.0),
1394                    bottom_left: (border_radius.bottom_left + offset).max(0.0),
1395                    bottom_right: (border_radius.bottom_right + offset).max(0.0),
1396                };
1397                list.push(DrawCommand::DrawBorder {
1398                    bounds: Rect::new(
1399                        bounds.x - offset,
1400                        bounds.y - offset,
1401                        bounds.width + offset * 2.0,
1402                        bounds.height + offset * 2.0,
1403                    ),
1404                    widths: EdgeInsets::all(node.style.outline_width),
1405                    color: outline_color,
1406                    border_radius: outline_radius,
1407                    style: node.style.outline_style,
1408                });
1409            }
1410        }
1411    }
1412
1413    fn paint_node_foreground_content(
1414        node: &LayoutNode,
1415        list: &mut DisplayList,
1416        cull: Option<Rect>,
1417    ) {
1418        let bounds = node.geometry.border_box;
1419
1420        // Embedded 3D viewport paints inside the content box at this exact CSS stacking-context layer.
1421        if let Some(ref handle) = node.scene_3d {
1422            let vp_bounds = if node.geometry.content_box.width > 0.0
1423                && node.geometry.content_box.height > 0.0
1424            {
1425                node.geometry.content_box
1426            } else {
1427                bounds
1428            };
1429            if vp_bounds.width > 0.0 && vp_bounds.height > 0.0 {
1430                // The payload is normally the `Arc<Scene3D>` itself, so this
1431                // is a refcount bump with no mesh copy.
1432                if let Ok(scene) =
1433                    std::sync::Arc::clone(&handle.0).downcast::<crate::scene3d::Scene3D>()
1434                {
1435                    list.push(DrawCommand::DrawViewport3D {
1436                        bounds: vp_bounds,
1437                        scene,
1438                    });
1439                } else if let Some(scene_arc) = handle
1440                    .0
1441                    .downcast_ref::<std::sync::Arc<crate::scene3d::Scene3D>>()
1442                {
1443                    list.push(DrawCommand::DrawViewport3D {
1444                        bounds: vp_bounds,
1445                        scene: std::sync::Arc::clone(scene_arc),
1446                    });
1447                } else if let Some(cmds) = handle
1448                    .0
1449                    .downcast_ref::<Vec<crate::canvas2d::CanvasCommand>>()
1450                {
1451                    list.push(DrawCommand::DrawCanvas2D {
1452                        bounds: vp_bounds,
1453                        commands: cmds.clone(),
1454                    });
1455                } else if let Some(cmds_arc) = handle
1456                    .0
1457                    .downcast_ref::<std::sync::Arc<Vec<crate::canvas2d::CanvasCommand>>>()
1458                {
1459                    list.push(DrawCommand::DrawCanvas2D {
1460                        bounds: vp_bounds,
1461                        commands: (**cmds_arc).clone(),
1462                    });
1463                }
1464            }
1465        }
1466
1467        // Replaced raster content paints inside the content box.
1468        if let Some(ref image) = node.image {
1469            let image_bounds = if node.geometry.content_box.width > 0.0
1470                && node.geometry.content_box.height > 0.0
1471            {
1472                node.geometry.content_box
1473            } else {
1474                bounds
1475            };
1476            list.push(DrawCommand::DrawImage {
1477                bounds: image_bounds,
1478                image: image.clone(),
1479            });
1480        }
1481
1482        // Text content on this node
1483        if !node.line_boxes.is_empty() {
1484            let mut fragments = Vec::new();
1485            for line in &node.line_boxes {
1486                if let Some(c) = cull {
1487                    if line.bounds.height > 0.0
1488                        && (line.bounds.y > c.y + c.height
1489                            || line.bounds.y + line.bounds.height < c.y)
1490                    {
1491                        continue;
1492                    }
1493                }
1494                fragments.extend(line.text_fragments.clone());
1495            }
1496            if !fragments.is_empty() {
1497                list.push(DrawCommand::DrawTextFragments { fragments });
1498            }
1499        } else if let Some(ref text) = node.text {
1500            let font_size = node.style.font_size;
1501            let line_height = node.style.line_height;
1502            let font_weight = node.style.font_weight;
1503            let color = node.style.color;
1504            let is_nowrap = matches!(
1505                node.style.white_space,
1506                strata_style::types::WhiteSpace::NoWrap | strata_style::types::WhiteSpace::Pre
1507            );
1508            let is_monospace = strata_layout::is_monospace_family(node.style.font_family);
1509            let text_align = node.style.text_align;
1510            let bounds_width = if node.geometry.content_box.width > 0.0 && !is_nowrap {
1511                Some(node.geometry.content_box.width)
1512            } else {
1513                None
1514            };
1515            let bounds_height = if node.geometry.content_box.height > 0.0 {
1516                Some(node.geometry.content_box.height)
1517            } else {
1518                None
1519            };
1520
1521            let scroll_x = node.geometry.scroll_offset.x;
1522            let align_offset = if is_nowrap
1523                && node.geometry.content_box.width > 0.0
1524                && scroll_x == 0.0
1525                && !matches!(
1526                    text_align,
1527                    strata_style::types::TextAlign::Left | strata_style::types::TextAlign::Justify
1528                ) {
1529                let (tw, _) = strata_layout::text::measure_text_bounds_styled_with_family(
1530                    text,
1531                    font_size,
1532                    line_height,
1533                    None,
1534                    is_monospace,
1535                    node.style.font_family,
1536                    font_weight,
1537                    node.style.font_style,
1538                );
1539                match text_align {
1540                    strata_style::types::TextAlign::Center => {
1541                        ((node.geometry.content_box.width - tw) / 2.0).max(0.0)
1542                    }
1543                    strata_style::types::TextAlign::Right => {
1544                        (node.geometry.content_box.width - tw).max(0.0)
1545                    }
1546                    _ => 0.0,
1547                }
1548            } else {
1549                0.0
1550            };
1551
1552            let clip_rect = if node.style.overflow_x != Overflow::Visible
1553                || node.style.overflow_y != Overflow::Visible
1554                || scroll_x != 0.0
1555            {
1556                let c = if node.geometry.content_box.width > 0.0
1557                    && node.geometry.content_box.height > 0.0
1558                {
1559                    node.geometry.content_box
1560                } else {
1561                    bounds
1562                };
1563                if c.width > 0.0 && c.height > 0.0 {
1564                    Some(c)
1565                } else {
1566                    None
1567                }
1568            } else {
1569                None
1570            };
1571
1572            if let Some(cr) = clip_rect {
1573                list.push(DrawCommand::PushClip {
1574                    bounds: cr,
1575                    radius: BorderRadius::all(0.0),
1576                });
1577            }
1578            list.push(DrawCommand::DrawText {
1579                origin: (
1580                    node.geometry.content_box.x + align_offset - scroll_x,
1581                    node.geometry.content_box.y,
1582                ),
1583                bounds_width,
1584                bounds_height,
1585                text_align,
1586                text: text.clone(),
1587                font_size,
1588                line_height,
1589                font_weight,
1590                color,
1591                is_monospace,
1592                font_family: node.style.font_family,
1593            });
1594            if clip_rect.is_some() {
1595                list.push(DrawCommand::PopClip);
1596            }
1597        }
1598
1599        // SVG Vector Path & Text content on this node
1600        if !node.svg_items.is_empty() {
1601            for item in &node.svg_items {
1602                let fill = if item.fill_is_current_color {
1603                    Some(node.style.color)
1604                } else {
1605                    item.fill_color
1606                };
1607                let stroke = if item.stroke_is_current_color {
1608                    Some(node.style.color)
1609                } else {
1610                    item.stroke_color.or_else(|| {
1611                        if fill.is_none() {
1612                            Some(node.style.color)
1613                        } else {
1614                            None
1615                        }
1616                    })
1617                };
1618                if let Some(ref svg_text) = item.text {
1619                    if !svg_text.content.is_empty() {
1620                        let scale_x = if item.view_box.0 > 0.0 {
1621                            bounds.width / item.view_box.0
1622                        } else {
1623                            1.0
1624                        };
1625                        let scale_y = if item.view_box.1 > 0.0 {
1626                            bounds.height / item.view_box.1
1627                        } else {
1628                            1.0
1629                        };
1630                        let avg_scale = ((scale_x + scale_y) * 0.5).max(0.01);
1631                        let font_size = (svg_text.font_size * avg_scale).max(1.0);
1632                        let text_color = fill.or(stroke).unwrap_or(node.style.color);
1633                        let est_w = svg_text.content.chars().count() as f32 * font_size * 0.56;
1634                        let anchor_dx = match svg_text.text_anchor {
1635                            strata_style::TextAlign::Center => -est_w * 0.5,
1636                            strata_style::TextAlign::Right => -est_w,
1637                            _ => 0.0,
1638                        };
1639                        let px = bounds.x + svg_text.x * scale_x + anchor_dx;
1640                        let py = bounds.y + svg_text.y * scale_y - font_size * 0.80;
1641                        list.push(DrawCommand::DrawText {
1642                            origin: (px, py),
1643                            bounds_width: None,
1644                            bounds_height: None,
1645                            text_align: strata_style::TextAlign::Left,
1646                            text: svg_text.content.clone(),
1647                            font_size,
1648                            line_height: font_size * 1.2,
1649                            font_weight: svg_text.font_weight,
1650                            color: text_color,
1651                            is_monospace: strata_layout::is_monospace_family(
1652                                node.style.font_family,
1653                            ),
1654                            font_family: node.style.font_family,
1655                        });
1656                    }
1657                }
1658                if !item.path_data.is_empty() {
1659                    list.push(DrawCommand::DrawSvgPath {
1660                        bounds,
1661                        path_data: item.path_data.clone(),
1662                        stroke_color: stroke,
1663                        fill_color: fill,
1664                        stroke_width: item.stroke_width,
1665                        stroke_linecap: item.stroke_linecap,
1666                        stroke_linejoin: item.stroke_linejoin,
1667                        stroke_dasharray: item.stroke_dasharray.clone(),
1668                        fill_rule: item.fill_rule,
1669                        view_box: item.view_box,
1670                    });
1671                }
1672            }
1673        } else if let Some(ref path_data) = node.svg_path {
1674            list.push(DrawCommand::DrawSvgPath {
1675                bounds,
1676                path_data: path_data.clone(),
1677                stroke_color: Some(node.style.color),
1678                fill_color: None,
1679                stroke_width: 2.0,
1680                stroke_linecap: strata_layout::StrokeLineCap::Round,
1681                stroke_linejoin: strata_layout::StrokeLineJoin::Round,
1682                stroke_dasharray: Vec::new(),
1683                fill_rule: strata_layout::FillRule::NonZero,
1684                view_box: (24.0, 24.0),
1685            });
1686        }
1687    }
1688
1689    /// Paints an in-flow non-stacking-context node and its recursive children.
1690    pub fn paint_node_content(node: &LayoutNode, list: &mut DisplayList) {
1691        Self::paint_node_content_culled(node, list, None);
1692    }
1693
1694    /// Paints an in-flow non-stacking-context node with optional spatial viewport culling.
1695    pub fn paint_node_content_culled(
1696        node: &LayoutNode,
1697        list: &mut DisplayList,
1698        cull: Option<Rect>,
1699    ) {
1700        Self::paint_node_content_guarded(node, list, cull, 0);
1701    }
1702
1703    /// Paints an in-flow non-stacking-context node with optional spatial viewport culling and active recursion depth guard.
1704    pub fn paint_node_content_guarded(
1705        node: &LayoutNode,
1706        list: &mut DisplayList,
1707        cull: Option<Rect>,
1708        depth: usize,
1709    ) {
1710        Self::paint_node_content_inner(node, list, cull, false, depth);
1711    }
1712
1713    fn paint_node_content_inner(
1714        node: &LayoutNode,
1715        list: &mut DisplayList,
1716        cull: Option<Rect>,
1717        skip_hoisted: bool,
1718        depth: usize,
1719    ) {
1720        if depth >= Self::MAX_COMPOSITOR_DEPTH {
1721            return;
1722        }
1723        if node.style.display == Display::None {
1724            return;
1725        }
1726        if node.style.content_visibility == strata_style::types::ContentVisibility::Hidden {
1727            return;
1728        }
1729
1730        let bounds = node.geometry.border_box;
1731        let clips_overflow = node.style.overflow_x != Overflow::Visible
1732            || node.style.overflow_y != Overflow::Visible;
1733        let border_radius = node.style.border_radius;
1734        let has_any_radius = border_radius.top_left > 0.0
1735            || border_radius.top_right > 0.0
1736            || border_radius.bottom_left > 0.0
1737            || border_radius.bottom_right > 0.0;
1738        let should_clip =
1739            clips_overflow || (has_any_radius && (node.image.is_some() || node.scene_3d.is_some()));
1740
1741        let child_cull = if clips_overflow
1742            && bounds.width > 0.0
1743            && bounds.height > 0.0
1744            && node.style.position != Position::Fixed
1745        {
1746            match cull {
1747                Some(c) => match bounds.intersect(c) {
1748                    Some(ic) => Some(ic),
1749                    None => return,
1750                },
1751                None => None,
1752            }
1753        } else {
1754            cull
1755        };
1756
1757        let is_visible = match cull {
1758            Some(c) => {
1759                if node.style.position == Position::Fixed {
1760                    true
1761                } else if bounds.width > 0.0 && bounds.height > 0.0 {
1762                    bounds.intersect(c).is_some()
1763                } else {
1764                    true
1765                }
1766            }
1767            None => true,
1768        };
1769
1770        if is_visible {
1771            Self::paint_node_box_decorations(node, list);
1772
1773            if should_clip {
1774                let clip_bounds = if clips_overflow
1775                    && node.geometry.padding_box.width > 0.0
1776                    && node.geometry.padding_box.height > 0.0
1777                {
1778                    node.geometry.padding_box
1779                } else {
1780                    bounds
1781                };
1782                list.push(DrawCommand::PushClip {
1783                    bounds: clip_bounds,
1784                    radius: border_radius,
1785                });
1786            }
1787
1788            Self::paint_node_foreground_content(node, list, cull);
1789        }
1790
1791        let has_scroll_offset =
1792            node.geometry.scroll_offset.x != 0.0 || node.geometry.scroll_offset.y != 0.0;
1793        if has_scroll_offset {
1794            let mat = strata_primitives::geom::Matrix4x4::translation(
1795                -node.geometry.scroll_offset.x,
1796                -node.geometry.scroll_offset.y,
1797                0.0,
1798            );
1799            list.push(DrawCommand::PushTransform { matrix: mat });
1800        }
1801
1802        let has_line_boxes = !node.line_boxes.is_empty();
1803        let parent_display = node.style.display;
1804        for child in &node.children {
1805            if child.is_top_layer || child.style.display == Display::None {
1806                continue;
1807            }
1808            if has_line_boxes
1809                && (child.text.is_some()
1810                    || (matches!(child.style.display, Display::Inline)
1811                        && !Self::inline_has_paintable_non_text_content(child)))
1812            {
1813                continue;
1814            }
1815
1816            let child_is_sc = child.establishes_stacking_context_in(Some(parent_display), false);
1817            if skip_hoisted && (child_is_sc || child.style.position != Position::Static) {
1818                continue;
1819            }
1820
1821            // In-flow child culling check: if child is strictly outside the cull rect, skip it
1822            if let Some(c) = child_cull {
1823                if child.style.position == Position::Static {
1824                    if child.geometry.border_box.y > c.y + c.height {
1825                        continue;
1826                    }
1827                    if child.geometry.border_box.height > 0.0
1828                        && child.geometry.border_box.y + child.geometry.border_box.height < c.y
1829                    {
1830                        continue;
1831                    }
1832                }
1833            }
1834
1835            if child_is_sc {
1836                Self::paint_stacking_context_guarded(child, list, child_cull, depth + 1);
1837            } else {
1838                Self::paint_node_content_inner(child, list, child_cull, skip_hoisted, depth + 1);
1839            }
1840        }
1841
1842        // Collapsed table boundaries paint once above cell content.
1843        Self::paint_collapsed_table_grid(node, list);
1844
1845        if has_scroll_offset {
1846            list.push(DrawCommand::PopTransform);
1847        }
1848
1849        if should_clip && is_visible {
1850            list.push(DrawCommand::PopClip);
1851        }
1852    }
1853}
1854
1855#[derive(Clone, Copy)]
1856struct ClipScrollStep {
1857    clip: Option<(Rect, BorderRadius)>,
1858    scroll_offset: (f32, f32),
1859    is_abs_cb: bool,
1860    is_fixed_cb: bool,
1861}
1862
1863struct HoistedParticipant<'a> {
1864    node: &'a LayoutNode,
1865    is_sc: bool,
1866    steps: Vec<ClipScrollStep>,
1867}