Skip to main content

cranpose_render_common/
graph.rs

1use std::{collections::HashSet, mem::size_of, rc::Rc};
2
3use cranpose_core::NodeId;
4use cranpose_foundation::PointerEvent;
5use cranpose_ui::{
6    GraphicsLayer, Point, Rect, RenderEffect, RoundedCornerShape, TextLayoutOptions, TextStyle,
7    text::AnnotatedString,
8};
9use cranpose_ui_graphics::{BlendMode, ColorFilter, DrawPrimitive, ShadowPrimitive};
10
11use crate::{raster_cache::LayerRasterCacheHashes, style_shared::DrawPlacement};
12
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub struct ProjectiveTransform {
15    matrix: [[f32; 3]; 3],
16}
17
18impl ProjectiveTransform {
19    pub const fn identity() -> Self {
20        Self {
21            matrix: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
22        }
23    }
24
25    pub fn translation(tx: f32, ty: f32) -> Self {
26        Self {
27            matrix: [[1.0, 0.0, tx], [0.0, 1.0, ty], [0.0, 0.0, 1.0]],
28        }
29    }
30
31    /// Uniform scale about the origin (device-scale root transform: render
32    /// graphs stay in logical dp; density applies at execution).
33    pub fn uniform_scale(scale: f32) -> Self {
34        Self {
35            matrix: [[scale, 0.0, 0.0], [0.0, scale, 0.0], [0.0, 0.0, 1.0]],
36        }
37    }
38
39    pub fn from_rect_to_quad(rect: Rect, quad: [[f32; 2]; 4]) -> Self {
40        if rect.width.abs() <= f32::EPSILON || rect.height.abs() <= f32::EPSILON {
41            return Self::translation(quad[0][0], quad[0][1]);
42        }
43
44        if let Some(axis_aligned) = axis_aligned_rect_from_quad(quad) {
45            let scale_x = axis_aligned.width / rect.width;
46            let scale_y = axis_aligned.height / rect.height;
47            return Self {
48                matrix: [
49                    [scale_x, 0.0, axis_aligned.x - rect.x * scale_x],
50                    [0.0, scale_y, axis_aligned.y - rect.y * scale_y],
51                    [0.0, 0.0, 1.0],
52                ],
53            };
54        }
55
56        let source = [
57            [rect.x, rect.y],
58            [rect.x + rect.width, rect.y],
59            [rect.x, rect.y + rect.height],
60            [rect.x + rect.width, rect.y + rect.height],
61        ];
62        let Some(coefficients) = solve_homography(source, quad) else {
63            return Self::identity();
64        };
65
66        Self {
67            matrix: [
68                [coefficients[0], coefficients[1], coefficients[2]],
69                [coefficients[3], coefficients[4], coefficients[5]],
70                [coefficients[6], coefficients[7], 1.0],
71            ],
72        }
73    }
74
75    /// Returns the composed transform that applies `self` first and `next` second.
76    pub fn then(self, next: Self) -> Self {
77        Self {
78            matrix: multiply_matrices(next.matrix, self.matrix),
79        }
80    }
81
82    pub fn inverse(self) -> Option<Self> {
83        let m = self.matrix;
84        let a = m[0][0];
85        let b = m[0][1];
86        let c = m[0][2];
87        let d = m[1][0];
88        let e = m[1][1];
89        let f = m[1][2];
90        let g = m[2][0];
91        let h = m[2][1];
92        let i = m[2][2];
93
94        let cofactor00 = e * i - f * h;
95        let cofactor01 = -(d * i - f * g);
96        let cofactor02 = d * h - e * g;
97        let cofactor10 = -(b * i - c * h);
98        let cofactor11 = a * i - c * g;
99        let cofactor12 = -(a * h - b * g);
100        let cofactor20 = b * f - c * e;
101        let cofactor21 = -(a * f - c * d);
102        let cofactor22 = a * e - b * d;
103
104        let determinant = a * cofactor00 + b * cofactor01 + c * cofactor02;
105        if determinant.abs() <= f32::EPSILON {
106            return None;
107        }
108        let inverse_determinant = 1.0 / determinant;
109
110        Some(Self {
111            matrix: [
112                [
113                    cofactor00 * inverse_determinant,
114                    cofactor10 * inverse_determinant,
115                    cofactor20 * inverse_determinant,
116                ],
117                [
118                    cofactor01 * inverse_determinant,
119                    cofactor11 * inverse_determinant,
120                    cofactor21 * inverse_determinant,
121                ],
122                [
123                    cofactor02 * inverse_determinant,
124                    cofactor12 * inverse_determinant,
125                    cofactor22 * inverse_determinant,
126                ],
127            ],
128        })
129    }
130
131    pub fn matrix(self) -> [[f32; 3]; 3] {
132        self.matrix
133    }
134
135    pub fn map_point(self, point: Point) -> Point {
136        let x = point.x;
137        let y = point.y;
138        let w = self.matrix[2][0] * x + self.matrix[2][1] * y + self.matrix[2][2];
139        let safe_w = if w.abs() <= f32::EPSILON { 1.0 } else { w };
140
141        Point {
142            x: (self.matrix[0][0] * x + self.matrix[0][1] * y + self.matrix[0][2]) / safe_w,
143            y: (self.matrix[1][0] * x + self.matrix[1][1] * y + self.matrix[1][2]) / safe_w,
144        }
145    }
146
147    pub fn map_rect(self, rect: Rect) -> [[f32; 2]; 4] {
148        [
149            self.map_point(Point {
150                x: rect.x,
151                y: rect.y,
152            }),
153            self.map_point(Point {
154                x: rect.x + rect.width,
155                y: rect.y,
156            }),
157            self.map_point(Point {
158                x: rect.x,
159                y: rect.y + rect.height,
160            }),
161            self.map_point(Point {
162                x: rect.x + rect.width,
163                y: rect.y + rect.height,
164            }),
165        ]
166        .map(|point| [point.x, point.y])
167    }
168
169    pub fn bounds_for_rect(self, rect: Rect) -> Rect {
170        quad_bounds(self.map_rect(rect))
171    }
172}
173
174fn axis_aligned_rect_from_quad(quad: [[f32; 2]; 4]) -> Option<Rect> {
175    let top_left = quad[0];
176    let top_right = quad[1];
177    let bottom_left = quad[2];
178    let bottom_right = quad[3];
179    let x_epsilon = 1e-4;
180    let y_epsilon = 1e-4;
181
182    if (top_left[1] - top_right[1]).abs() > y_epsilon
183        || (bottom_left[1] - bottom_right[1]).abs() > y_epsilon
184        || (top_left[0] - bottom_left[0]).abs() > x_epsilon
185        || (top_right[0] - bottom_right[0]).abs() > x_epsilon
186    {
187        return None;
188    }
189
190    Some(Rect {
191        x: top_left[0],
192        y: top_left[1],
193        width: top_right[0] - top_left[0],
194        height: bottom_left[1] - top_left[1],
195    })
196}
197
198impl Default for ProjectiveTransform {
199    fn default() -> Self {
200        Self::identity()
201    }
202}
203
204#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
205pub struct IsolationReasons {
206    pub explicit_offscreen: bool,
207    pub shape_clip: bool,
208    pub effect: bool,
209    pub backdrop: bool,
210    pub group_opacity: bool,
211    pub blend_mode: bool,
212}
213
214impl IsolationReasons {
215    pub fn has_any(self) -> bool {
216        self.explicit_offscreen
217            || self.shape_clip
218            || self.effect
219            || self.backdrop
220            || self.group_opacity
221            || self.blend_mode
222    }
223}
224
225#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
226pub enum CachePolicy {
227    #[default]
228    None,
229    Auto,
230}
231
232#[derive(Clone)]
233pub struct HitTestNode {
234    pub shape: Option<RoundedCornerShape>,
235    pub click_actions: Vec<Rc<dyn Fn(Point)>>,
236    pub pointer_inputs: Vec<Rc<dyn Fn(PointerEvent)>>,
237    pub clip: Option<Rect>,
238}
239
240#[derive(Clone, Debug, PartialEq)]
241pub struct DrawPrimitiveNode {
242    pub primitive: DrawPrimitive,
243    pub clip: Option<Rect>,
244}
245
246#[derive(Clone, Debug, PartialEq)]
247pub struct TextPrimitiveNode {
248    pub node_id: NodeId,
249    pub rect: Rect,
250    /// Shared so the renderer can hand the same allocation to every draw it
251    /// emits for this node instead of deep-copying the string once per emit.
252    pub text: Rc<AnnotatedString>,
253    pub text_style: TextStyle,
254    pub font_size: f32,
255    pub layout_options: TextLayoutOptions,
256    pub clip: Option<Rect>,
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
260pub enum PrimitivePhase {
261    BeforeChildren,
262    AfterChildren,
263}
264
265#[derive(Clone, Debug, PartialEq)]
266pub enum PrimitiveNode {
267    Draw(DrawPrimitiveNode),
268    Text(Box<TextPrimitiveNode>),
269}
270
271#[derive(Clone, Debug, PartialEq)]
272pub struct PrimitiveEntry {
273    pub phase: PrimitivePhase,
274    pub node: PrimitiveNode,
275}
276
277#[derive(Clone)]
278pub struct LayerNode {
279    pub node_id: Option<NodeId>,
280    pub local_bounds: Rect,
281    pub transform_to_parent: ProjectiveTransform,
282    pub content_offset: Point,
283    pub motion_context_animated: bool,
284    pub translated_content_context: bool,
285    pub translated_content_offset: Point,
286    /// Window-space origin this layer's children are placed from, and the
287    /// accumulated ancestor graphics-layer translation, captured during the
288    /// full per-frame scene build. Read back when a dirty subtree is rebuilt in
289    /// isolation (`update_scene_from_applier`) so a scrolling field's window
290    /// origin stays live during a fling even though the ancestor chain is not
291    /// re-walked from the root. Defaults to the identity origin.
292    pub scene_children_origin: Point,
293    pub scene_children_layer_translation: Point,
294    pub graphics_layer: GraphicsLayer,
295    pub clip_to_bounds: bool,
296    pub shadow_clip: Option<Rect>,
297    pub hit_test: Option<HitTestNode>,
298    pub has_hit_targets: bool,
299    /// Whether this subtree publishes live window origins (a text field's
300    /// popup anchor, a scroll container's viewport rect). Those sinks are
301    /// written during a full lowering, so the scroll fast path may translate
302    /// a retained subtree in place only when this is false.
303    pub has_origin_sinks: bool,
304    pub isolation: IsolationReasons,
305    pub cache_policy: CachePolicy,
306    pub cache_hashes: LayerRasterCacheHashes,
307    pub cache_hashes_valid: bool,
308    pub children: Vec<RenderNode>,
309}
310
311impl Default for LayerNode {
312    fn default() -> Self {
313        Self {
314            node_id: None,
315            local_bounds: Rect {
316                x: 0.0,
317                y: 0.0,
318                width: 0.0,
319                height: 0.0,
320            },
321            transform_to_parent: ProjectiveTransform::identity(),
322            content_offset: Point::default(),
323            motion_context_animated: false,
324            translated_content_context: false,
325            translated_content_offset: Point::default(),
326            scene_children_origin: Point::default(),
327            scene_children_layer_translation: Point::default(),
328            graphics_layer: GraphicsLayer::default(),
329            clip_to_bounds: false,
330            shadow_clip: None,
331            hit_test: None,
332            has_hit_targets: false,
333            has_origin_sinks: false,
334            isolation: IsolationReasons::default(),
335            cache_policy: CachePolicy::None,
336            cache_hashes: LayerRasterCacheHashes::default(),
337            cache_hashes_valid: false,
338            children: Vec::new(),
339        }
340    }
341}
342
343impl LayerNode {
344    pub fn clip_rect(&self) -> Option<Rect> {
345        (self.clip_to_bounds || self.graphics_layer.clip).then_some(self.local_bounds)
346    }
347
348    pub fn effect(&self) -> Option<&RenderEffect> {
349        self.graphics_layer.render_effect.as_ref()
350    }
351
352    pub fn backdrop(&self) -> Option<&RenderEffect> {
353        self.graphics_layer.backdrop_effect.as_ref()
354    }
355
356    pub fn opacity(&self) -> f32 {
357        self.graphics_layer.alpha
358    }
359
360    pub fn blend_mode(&self) -> BlendMode {
361        self.graphics_layer.blend_mode
362    }
363
364    pub fn color_filter(&self) -> Option<ColorFilter> {
365        self.graphics_layer.color_filter
366    }
367
368    pub fn target_content_hash(&self) -> u64 {
369        if self.cache_hashes_valid {
370            self.cache_hashes.target_content
371        } else {
372            crate::graph_hash::layer_raster_cache_hashes(self).target_content
373        }
374    }
375
376    pub fn motion_source_content_hash(&self) -> u64 {
377        crate::graph_hash::layer_motion_source_content_hash(self)
378    }
379
380    pub fn effect_hash(&self) -> u64 {
381        if self.cache_hashes_valid {
382            self.cache_hashes.effect
383        } else {
384            crate::graph_hash::layer_raster_cache_hashes(self).effect
385        }
386    }
387
388    pub fn recompute_raster_cache_hashes(&mut self) {
389        crate::graph_hash::recompute_layer_raster_cache_hashes(self);
390    }
391}
392
393#[derive(Clone)]
394pub enum RenderNode {
395    Primitive(PrimitiveEntry),
396    /// A whole draw command's primitives as one node. A heavy canvas records
397    /// thousands of primitives per frame; wrapping each in its own
398    /// [`RenderNode`] made the graph rebuild move every one of them twice and
399    /// free seventeen thousand nodes per frame on a stress scene. The run
400    /// keeps the recorded vector intact — semantically it is exactly that
401    /// many consecutive `Primitive` draw entries with no per-primitive clip.
402    DrawRun(DrawRunNode),
403    Layer(Box<LayerNode>),
404}
405
406/// Stable identity of the draw command a run was recorded from: the layout
407/// node owning the command, the command's index in that node's command list,
408/// and which placement pass produced this run (a `WithContent` command emits
409/// one run per placement, so the pair alone is not unique). Rendering does
410/// not read it yet; it is the key under which retained recording state lives
411/// as retention moves up to the draw-command recorder, and it must survive
412/// recording, graph construction, normalized-scene creation, and renderer
413/// cache lookup unchanged.
414#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
415pub struct DrawCommandId {
416    pub node_id: NodeId,
417    pub command_index: u32,
418    pub placement: DrawPlacement,
419}
420
421#[derive(Clone, Debug, PartialEq)]
422pub struct DrawRunNode {
423    pub phase: PrimitivePhase,
424    /// Which draw command recorded these primitives. `None` only for runs
425    /// with no per-command provenance (hand-built tests).
426    pub command: Option<DrawCommandId>,
427    /// Shared, not owned: the recording registry keyed by [`DrawCommandId`]
428    /// keeps a handle to the same buffer, so its capacity survives this
429    /// node being dropped on the next rebuild and the command re-records
430    /// into it instead of growing a fresh vector. Nothing mutates a run's
431    /// primitives after construction, which is what makes sharing sound.
432    pub primitives: std::rc::Rc<Vec<DrawPrimitive>>,
433    /// Content facts consumers keep asking per frame, answered once at
434    /// construction. Surface planning used to rescan every primitive of
435    /// every run per frame to learn "does it contain text?" — for a
436    /// 17k-primitive game canvas with no text, that was two full walks per
437    /// frame that could never early-exit.
438    pub summary: DrawRunSummary,
439    /// The command's verified retained/dynamic span structure for the frame
440    /// this node was built, in primitive space. A renderer that retains by
441    /// identity draws the run span by span — retained spans from slots
442    /// keyed (command, slot), dynamic spans from `primitives` — instead of
443    /// walking the whole vector. `None` means no verification ran or
444    /// nothing was retained: the run is all ordinary primitives.
445    pub replay: Option<Box<cranpose_ui_graphics::CommandReplayFrame>>,
446}
447
448impl DrawRunNode {
449    pub fn new(phase: PrimitivePhase, primitives: Vec<DrawPrimitive>) -> Self {
450        Self::for_command(phase, None, primitives)
451    }
452
453    pub fn for_command(
454        phase: PrimitivePhase,
455        command: Option<DrawCommandId>,
456        primitives: Vec<DrawPrimitive>,
457    ) -> Self {
458        Self::for_command_shared(phase, command, std::rc::Rc::new(primitives))
459    }
460
461    pub fn for_command_shared(
462        phase: PrimitivePhase,
463        command: Option<DrawCommandId>,
464        primitives: std::rc::Rc<Vec<DrawPrimitive>>,
465    ) -> Self {
466        Self::for_command_replayed(phase, command, primitives, None)
467    }
468
469    pub fn for_command_replayed(
470        phase: PrimitivePhase,
471        command: Option<DrawCommandId>,
472        primitives: std::rc::Rc<Vec<DrawPrimitive>>,
473        replay: Option<Box<cranpose_ui_graphics::CommandReplayFrame>>,
474    ) -> Self {
475        debug_assert!(
476            replay.as_ref().is_none_or(|frame| {
477                frame.fallback.is_some()
478                    || !frame.spans.iter().any(|span| {
479                        matches!(
480                            span,
481                            cranpose_ui_graphics::FrameSpan::Retained {
482                                capture: false,
483                                range,
484                                ..
485                            } if range.1 <= range.0
486                        )
487                    })
488            }),
489            "a replay frame with bypassed spans must own its fallback recording"
490        );
491        let mut summary = DrawRunSummary::scan(&primitives);
492        if replay.as_ref().is_some_and(|frame| {
493            frame
494                .spans
495                .iter()
496                .any(|span| matches!(span, cranpose_ui_graphics::FrameSpan::Retained { .. }))
497        }) {
498            summary.has_non_shadow = true;
499        }
500        Self {
501            phase,
502            command,
503            primitives,
504            summary,
505            replay,
506        }
507    }
508}
509
510/// One-pass discriminant census of a draw run, recursing through `Blend`
511/// wrappers the same way the per-primitive predicates it replaces did.
512#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
513pub struct DrawRunSummary {
514    /// Any `Text` primitive, including inside `Blend` — glyph masks want
515    /// rigid snapping.
516    pub has_text: bool,
517    pub has_shadow: bool,
518    /// Any primitive besides `Shadow` (direct drawable content).
519    pub has_non_shadow: bool,
520    /// Any `Image` or `Text`, including inside `Blend` — content that
521    /// resamples badly on a fractionally offset surface.
522    pub has_pixel_sensitive: bool,
523}
524
525impl DrawRunSummary {
526    pub fn scan(primitives: &[DrawPrimitive]) -> Self {
527        fn unwrap_blend(mut primitive: &DrawPrimitive) -> &DrawPrimitive {
528            while let DrawPrimitive::Blend {
529                primitive: inner, ..
530            } = primitive
531            {
532                primitive = inner;
533            }
534            primitive
535        }
536        let mut summary = Self::default();
537        for primitive in primitives {
538            if matches!(primitive, DrawPrimitive::Shadow(_)) {
539                summary.has_shadow = true;
540                continue;
541            }
542            summary.has_non_shadow = true;
543            match unwrap_blend(primitive) {
544                DrawPrimitive::Text(_) => {
545                    summary.has_text = true;
546                    summary.has_pixel_sensitive = true;
547                }
548                DrawPrimitive::Image { .. } => summary.has_pixel_sensitive = true,
549                _ => {}
550            }
551        }
552        summary
553    }
554}
555
556#[derive(Clone)]
557pub struct RenderGraph {
558    pub root: LayerNode,
559}
560
561impl RenderGraph {
562    pub fn new(mut root: LayerNode) -> Self {
563        root.recompute_raster_cache_hashes();
564        Self { root }
565    }
566
567    pub fn node_count(&self) -> usize {
568        fn count_layer(layer: &LayerNode) -> usize {
569            1 + layer
570                .children
571                .iter()
572                .map(|child| match child {
573                    RenderNode::Primitive(_) => 1,
574                    RenderNode::DrawRun(run) => run.primitives.len(),
575                    RenderNode::Layer(child_layer) => count_layer(child_layer),
576                })
577                .sum::<usize>()
578        }
579
580        count_layer(&self.root)
581    }
582
583    pub fn heap_bytes(&self) -> usize {
584        layer_heap_bytes(&self.root)
585    }
586
587    pub fn retained_visual_observation_nodes(&self) -> HashSet<NodeId> {
588        fn collect(layer: &LayerNode, nodes: &mut HashSet<NodeId>) {
589            if let Some(node_id) = layer.node_id {
590                nodes.insert(node_id);
591            }
592            for child in &layer.children {
593                match child {
594                    RenderNode::DrawRun(run) => {
595                        if let Some(command) = run.command {
596                            nodes.insert(command.node_id);
597                        }
598                    }
599                    RenderNode::Layer(child) => collect(child, nodes),
600                    RenderNode::Primitive(_) => {}
601                }
602            }
603        }
604
605        let mut nodes = HashSet::new();
606        collect(&self.root, &mut nodes);
607        nodes
608    }
609}
610
611fn layer_heap_bytes(layer: &LayerNode) -> usize {
612    layer.hit_test.as_ref().map_or(0, hit_test_heap_bytes)
613        + size_of::<RenderNode>() * layer.children.capacity()
614        + layer
615            .children
616            .iter()
617            .map(render_node_heap_bytes)
618            .sum::<usize>()
619}
620
621fn render_node_heap_bytes(node: &RenderNode) -> usize {
622    match node {
623        RenderNode::Primitive(entry) => primitive_entry_heap_bytes(entry),
624        RenderNode::DrawRun(run) => {
625            size_of::<DrawPrimitive>() * run.primitives.capacity()
626                + run
627                    .primitives
628                    .iter()
629                    .map(draw_primitive_heap_bytes)
630                    .sum::<usize>()
631        }
632        RenderNode::Layer(layer) => size_of::<LayerNode>() + layer_heap_bytes(layer),
633    }
634}
635
636fn primitive_entry_heap_bytes(entry: &PrimitiveEntry) -> usize {
637    match &entry.node {
638        PrimitiveNode::Draw(draw) => draw_primitive_heap_bytes(&draw.primitive),
639        PrimitiveNode::Text(text) => {
640            size_of::<TextPrimitiveNode>() + annotated_string_heap_bytes(&text.text)
641        }
642    }
643}
644
645fn draw_primitive_heap_bytes(primitive: &DrawPrimitive) -> usize {
646    match primitive {
647        DrawPrimitive::Content
648        | DrawPrimitive::Rect { .. }
649        | DrawPrimitive::RoundRect { .. }
650        | DrawPrimitive::Arc { .. } => 0,
651        DrawPrimitive::Blend { primitive, .. } => {
652            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(primitive)
653        }
654        DrawPrimitive::Image { .. } => 0,
655        DrawPrimitive::Text(text) => {
656            size_of::<cranpose_ui_graphics::TextPrimitive>()
657                + text.text.len()
658                + text
659                    .style
660                    .font_family
661                    .as_ref()
662                    .map_or(0, |family| family.capacity())
663        }
664        DrawPrimitive::Shadow(shadow) => shadow_primitive_heap_bytes(shadow),
665    }
666}
667
668fn shadow_primitive_heap_bytes(shadow: &ShadowPrimitive) -> usize {
669    match shadow {
670        ShadowPrimitive::Drop { shape, .. } => {
671            size_of::<DrawPrimitive>() + draw_primitive_heap_bytes(shape)
672        }
673        ShadowPrimitive::Inner { fill, cutout, .. } => {
674            size_of::<DrawPrimitive>() * 2
675                + draw_primitive_heap_bytes(fill)
676                + draw_primitive_heap_bytes(cutout)
677        }
678    }
679}
680
681fn annotated_string_heap_bytes(text: &AnnotatedString) -> usize {
682    text.text.capacity()
683        + text.span_styles.capacity() * size_of::<usize>() * 2
684        + text.paragraph_styles.capacity() * size_of::<usize>() * 2
685        + text.string_annotations.capacity() * size_of::<usize>() * 2
686        + text.link_annotations.capacity() * size_of::<usize>() * 2
687        + text
688            .string_annotations
689            .iter()
690            .map(|annotation| {
691                annotation.item.tag.capacity() + annotation.item.annotation.capacity()
692            })
693            .sum::<usize>()
694        + text
695            .link_annotations
696            .iter()
697            .map(|annotation| match &annotation.item {
698                cranpose_ui::text::LinkAnnotation::Url(url) => url.capacity(),
699                cranpose_ui::text::LinkAnnotation::Clickable { tag, .. } => tag.capacity(),
700            })
701            .sum::<usize>()
702}
703
704fn hit_test_heap_bytes(hit_test: &HitTestNode) -> usize {
705    hit_test.click_actions.capacity() * size_of::<Rc<dyn Fn(Point)>>()
706        + hit_test.pointer_inputs.capacity() * size_of::<Rc<dyn Fn(PointerEvent)>>()
707}
708
709pub fn quad_bounds(quad: [[f32; 2]; 4]) -> Rect {
710    let mut min_x = f32::INFINITY;
711    let mut min_y = f32::INFINITY;
712    let mut max_x = f32::NEG_INFINITY;
713    let mut max_y = f32::NEG_INFINITY;
714
715    for [x, y] in quad {
716        min_x = min_x.min(x);
717        min_y = min_y.min(y);
718        max_x = max_x.max(x);
719        max_y = max_y.max(y);
720    }
721
722    Rect {
723        x: min_x,
724        y: min_y,
725        width: (max_x - min_x).max(0.0),
726        height: (max_y - min_y).max(0.0),
727    }
728}
729
730fn multiply_matrices(lhs: [[f32; 3]; 3], rhs: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
731    let mut out = [[0.0; 3]; 3];
732    for row in 0..3 {
733        for col in 0..3 {
734            out[row][col] =
735                lhs[row][0] * rhs[0][col] + lhs[row][1] * rhs[1][col] + lhs[row][2] * rhs[2][col];
736        }
737    }
738    out
739}
740
741fn solve_homography(source: [[f32; 2]; 4], target: [[f32; 2]; 4]) -> Option<[f32; 8]> {
742    let mut matrix = [[0.0f32; 9]; 8];
743    for (index, (src, dst)) in source.into_iter().zip(target).enumerate() {
744        let row = index * 2;
745        let x = src[0];
746        let y = src[1];
747        let u = dst[0];
748        let v = dst[1];
749
750        matrix[row] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
751        matrix[row + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
752    }
753
754    for pivot in 0..8 {
755        let mut pivot_row = pivot;
756        let mut pivot_value = matrix[pivot][pivot].abs();
757        let mut candidate = pivot + 1;
758        while candidate < 8 {
759            let candidate_value = matrix[candidate][pivot].abs();
760            if candidate_value > pivot_value {
761                pivot_row = candidate;
762                pivot_value = candidate_value;
763            }
764            candidate += 1;
765        }
766
767        if pivot_value <= f32::EPSILON {
768            return None;
769        }
770
771        if pivot_row != pivot {
772            matrix.swap(pivot, pivot_row);
773        }
774
775        let divisor = matrix[pivot][pivot];
776        let mut col = pivot;
777        while col < 9 {
778            matrix[pivot][col] /= divisor;
779            col += 1;
780        }
781
782        for row in 0..8 {
783            if row == pivot {
784                continue;
785            }
786            let factor = matrix[row][pivot];
787            if factor.abs() <= f32::EPSILON {
788                continue;
789            }
790            let mut col = pivot;
791            while col < 9 {
792                matrix[row][col] -= factor * matrix[pivot][col];
793                col += 1;
794            }
795        }
796    }
797
798    let mut solution = [0.0f32; 8];
799    for index in 0..8 {
800        solution[index] = matrix[index][8];
801    }
802    Some(solution)
803}
804
805#[cfg(test)]
806mod tests {
807    use cranpose_ui_graphics::{Brush, Color, DrawPrimitive};
808
809    use super::*;
810
811    fn test_layer(local_bounds: Rect, children: Vec<RenderNode>) -> LayerNode {
812        LayerNode {
813            local_bounds,
814            children,
815            ..Default::default()
816        }
817    }
818
819    #[test]
820    fn projective_transform_translation_maps_points() {
821        let transform = ProjectiveTransform::translation(7.0, -3.5);
822        let mapped = transform.map_point(Point { x: 2.0, y: 4.0 });
823        assert!((mapped.x - 9.0).abs() < 1e-6);
824        assert!((mapped.y - 0.5).abs() < 1e-6);
825    }
826
827    #[test]
828    fn projective_transform_then_composes_in_parent_order() {
829        let child = ProjectiveTransform::translation(4.0, 2.0);
830        let parent = ProjectiveTransform::translation(10.0, -1.0);
831        let composed = child.then(parent);
832        let mapped = composed.map_point(Point { x: 1.0, y: 1.0 });
833        assert!((mapped.x - 15.0).abs() < 1e-6);
834        assert!((mapped.y - 2.0).abs() < 1e-6);
835    }
836
837    #[test]
838    fn homography_maps_rect_corners_to_target_quad() {
839        let rect = Rect {
840            x: 0.0,
841            y: 0.0,
842            width: 20.0,
843            height: 10.0,
844        };
845        let quad = [[5.0, 7.0], [25.0, 6.0], [7.0, 20.0], [28.0, 21.0]];
846        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
847        let mapped = transform.map_rect(rect);
848        for (expected, actual) in quad.into_iter().zip(mapped) {
849            assert!((expected[0] - actual[0]).abs() < 1e-4);
850            assert!((expected[1] - actual[1]).abs() < 1e-4);
851        }
852    }
853
854    #[test]
855    fn axis_aligned_rect_to_quad_keeps_exact_affine_matrix() {
856        let rect = Rect {
857            x: 2.0,
858            y: 3.0,
859            width: 20.0,
860            height: 10.0,
861        };
862        let quad = [[12.0, 9.0], [32.0, 9.0], [12.0, 19.0], [32.0, 19.0]];
863        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
864
865        assert_eq!(
866            transform.matrix(),
867            [[1.0, 0.0, 10.0], [0.0, 1.0, 6.0], [0.0, 0.0, 1.0]]
868        );
869    }
870
871    #[test]
872    fn axis_aligned_rect_to_quad_keeps_exact_axis_aligned_scale() {
873        let rect = Rect {
874            x: 4.0,
875            y: 6.0,
876            width: 10.0,
877            height: 8.0,
878        };
879        let quad = [[20.0, 18.0], [50.0, 18.0], [20.0, 42.0], [50.0, 42.0]];
880        let transform = ProjectiveTransform::from_rect_to_quad(rect, quad);
881
882        assert_eq!(
883            transform.matrix(),
884            [[3.0, 0.0, 8.0], [0.0, 3.0, 0.0], [0.0, 0.0, 1.0]]
885        );
886    }
887
888    #[test]
889    fn retained_visual_observation_nodes_collect_layers_and_command_owners() {
890        let bounds = Rect {
891            x: 0.0,
892            y: 0.0,
893            width: 20.0,
894            height: 20.0,
895        };
896        let command = |node_id| DrawCommandId {
897            node_id,
898            command_index: 0,
899            placement: DrawPlacement::Behind,
900        };
901        let mut child = test_layer(
902            bounds,
903            vec![RenderNode::DrawRun(DrawRunNode::for_command(
904                PrimitivePhase::BeforeChildren,
905                Some(command(17)),
906                Vec::new(),
907            ))],
908        );
909        child.node_id = Some(13);
910        let mut root = test_layer(
911            bounds,
912            vec![
913                RenderNode::DrawRun(DrawRunNode::for_command(
914                    PrimitivePhase::BeforeChildren,
915                    Some(command(9)),
916                    Vec::new(),
917                )),
918                RenderNode::DrawRun(DrawRunNode::new(PrimitivePhase::BeforeChildren, Vec::new())),
919                RenderNode::Layer(Box::new(child)),
920            ],
921        );
922
923        root.node_id = Some(5);
924
925        assert_eq!(
926            RenderGraph::new(root).retained_visual_observation_nodes(),
927            HashSet::from([5, 9, 13, 17])
928        );
929    }
930
931    #[test]
932    fn render_graph_new_recomputes_manual_layer_hashes() {
933        let primitive = PrimitiveEntry {
934            phase: PrimitivePhase::BeforeChildren,
935            node: PrimitiveNode::Draw(DrawPrimitiveNode {
936                primitive: DrawPrimitive::Rect {
937                    rect: Rect {
938                        x: 1.0,
939                        y: 2.0,
940                        width: 8.0,
941                        height: 6.0,
942                    },
943                    brush: Brush::solid(Color::WHITE),
944                    stroke: None,
945                },
946                clip: None,
947            }),
948        };
949        let mut root = test_layer(
950            Rect {
951                x: 0.0,
952                y: 0.0,
953                width: 20.0,
954                height: 20.0,
955            },
956            vec![RenderNode::Primitive(primitive)],
957        );
958        root.graphics_layer.render_effect = Some(RenderEffect::blur(3.0));
959        let mut expected = root.clone();
960        expected.recompute_raster_cache_hashes();
961
962        let graph = RenderGraph::new(root);
963        assert_eq!(
964            graph.root.target_content_hash(),
965            expected.target_content_hash()
966        );
967        assert_eq!(graph.root.effect_hash(), expected.effect_hash());
968    }
969
970    #[test]
971    fn motion_source_content_hash_ignores_translated_content_offset() {
972        let primitive = PrimitiveEntry {
973            phase: PrimitivePhase::BeforeChildren,
974            node: PrimitiveNode::Draw(DrawPrimitiveNode {
975                primitive: DrawPrimitive::Rect {
976                    rect: Rect {
977                        x: 1.0,
978                        y: 2.0,
979                        width: 8.0,
980                        height: 6.0,
981                    },
982                    brush: Brush::solid(Color::WHITE),
983                    stroke: None,
984                },
985                clip: None,
986            }),
987        };
988        let mut base = test_layer(
989            Rect {
990                x: 0.0,
991                y: 0.0,
992                width: 20.0,
993                height: 20.0,
994            },
995            vec![RenderNode::Primitive(primitive)],
996        );
997        base.translated_content_context = true;
998        base.translated_content_offset = Point::new(0.0, -24.0);
999        base.recompute_raster_cache_hashes();
1000
1001        let mut moved = base.clone();
1002        moved.translated_content_offset = Point::new(0.0, -72.0);
1003        moved.recompute_raster_cache_hashes();
1004
1005        assert_ne!(base.target_content_hash(), moved.target_content_hash());
1006        assert_eq!(
1007            base.motion_source_content_hash(),
1008            moved.motion_source_content_hash()
1009        );
1010    }
1011}