Skip to main content

pax_std/
common.rs

1use kurbo::{Affine, Shape};
2pub use pax_engine::api::Size;
3use pax_message::AppleLiquidGlassPatch;
4use pax_runtime::api as pax_runtime_api;
5use pax_runtime::api::RenderContext;
6use pax_runtime::{ExpandedNode, RuntimeContext};
7
8// Resolves Pax units against bounds into a kurbo point.
9pub(crate) fn to_kurbo_point(x: Size, y: Size, bounds: (f64, f64)) -> kurbo::Point {
10    let x = x.evaluate(bounds, pax_engine::api::Axis::X);
11    let y = y.evaluate(bounds, pax_engine::api::Axis::Y);
12    kurbo::Point { x, y }
13}
14
15// Writes a patch field only when the new value differs from cached old state.
16pub fn patch_if_needed<T: PartialEq + Clone>(
17    old_state: &mut Option<T>,
18    patch: &mut Option<T>,
19    new_value: T,
20) -> bool {
21    if !old_state.as_ref().is_some_and(|v| v == &new_value) {
22        *patch = Some(new_value.clone());
23        *old_state = Some(new_value);
24        true
25    } else {
26        false
27    }
28}
29
30// Writes inherited liquid-glass scope changes, including explicit clears.
31pub fn patch_liquid_glass_if_needed(
32    old_state: &mut Option<Option<AppleLiquidGlassPatch>>,
33    patch: &mut Option<Option<AppleLiquidGlassPatch>>,
34    expanded_node: &ExpandedNode,
35) -> bool {
36    patch_if_needed(
37        old_state,
38        patch,
39        expanded_node
40            .liquid_glass_scope
41            .get()
42            .map(|scope| scope.to_message()),
43    )
44}
45
46// Converts computed world opacity into the relative opacity expected by native hosts.
47pub fn native_surface_opacity(expanded_node: &ExpandedNode, context: &RuntimeContext) -> f64 {
48    let opacity = expanded_node.computed_opacity.get().clamp(0.0, 1.0);
49    let Some(parent_frame_id) = expanded_node.parent_frame.get() else {
50        return opacity;
51    };
52    let Some(parent_frame) = context.get_expanded_node_by_eid(parent_frame_id) else {
53        return opacity;
54    };
55    let parent_opacity = parent_frame.computed_opacity.get().clamp(0.0, 1.0);
56    if parent_opacity <= f64::EPSILON {
57        0.0
58    } else {
59        (opacity / parent_opacity).clamp(0.0, 1.0)
60    }
61}
62
63// Resolves the transform a canvas primitive should use inside its owning canvas surface.
64pub fn canvas_surface_transform(expanded_node: &ExpandedNode, context: &RuntimeContext) -> Affine {
65    let transform = Affine::from(expanded_node.transform_and_bounds.get().transform);
66    let own_layer = expanded_node.occlusion.get().render_layer_id;
67    let mut parent_frame_id = expanded_node.parent_frame.get();
68    while let Some(current_parent_frame_id) = parent_frame_id {
69        let Some(parent_frame) = context.get_expanded_node_by_eid(current_parent_frame_id) else {
70            break;
71        };
72        if parent_frame.occlusion.get().render_layer_id != own_layer {
73            // Descendant canvas layers can be mounted into browser-owned scroller hosts whose DOM
74            // coordinate space is local to the owning ancestor frame, not to the root canvas. We
75            // originally tried compensating at the scroller traversal layer, but retained
76            // vector/image nodes still carried world-space transforms into those nested surfaces.
77            // Walk up to the nearest ancestor on a different render layer so nested same-layer
78            // groups still localize into the browser-hosted canvas that actually owns them.
79            return Affine::from(parent_frame.transform_and_bounds.get().transform.inverse())
80                * transform;
81        }
82        parent_frame_id = parent_frame.parent_frame.get();
83    }
84    transform
85}
86
87fn canvas_surface_bounds_for_transform(
88    transform: Affine,
89    local_bounds: kurbo::Rect,
90) -> kurbo::Rect {
91    const TILE_CULL_BOUNDS_PAD: f64 = 64.0;
92    (transform * local_bounds.to_path(0.1))
93        .bounding_box()
94        .inflate(TILE_CULL_BOUNDS_PAD, TILE_CULL_BOUNDS_PAD)
95}
96
97// Values a primitive needs after the render context has selected live tile surfaces.
98pub struct CanvasNodeRenderScope {
99    pub layer_id: usize,
100    pub node_id: u32,
101    pub surface_transform: Affine,
102    pub bounds: (f64, f64),
103}
104
105// Begin a bounded retained vector/image node.
106//
107// The render context owns tile selection and stale-node removal, but `pax-std`
108// owns deriving conservative canvas-space coverage from an expanded node.
109pub fn begin_bounded_canvas_node(
110    rc: &mut dyn RenderContext,
111    expanded_node: &ExpandedNode,
112    context: &RuntimeContext,
113) -> Option<CanvasNodeRenderScope> {
114    let bounds = expanded_node.transform_and_bounds.get().bounds;
115    begin_canvas_node_with_local_bounds(
116        rc,
117        expanded_node,
118        context,
119        kurbo::Rect::new(0.0, 0.0, bounds.0, bounds.1),
120    )
121}
122
123// Begin a retained vector/image node using explicit local-space coverage.
124//
125// Most primitives are bounded by their layout rectangle and use
126// `begin_bounded_canvas_node`. Paths may intentionally draw outside that
127// rectangle, so their tile coverage follows their actual geometry instead.
128pub(crate) fn begin_canvas_node_with_local_bounds(
129    rc: &mut dyn RenderContext,
130    expanded_node: &ExpandedNode,
131    context: &RuntimeContext,
132    local_coverage_bounds: kurbo::Rect,
133) -> Option<CanvasNodeRenderScope> {
134    let layer_id = expanded_node.occlusion.get().render_layer_id;
135    let node_id = expanded_node.id.to_u32();
136    let tab = expanded_node.transform_and_bounds.get();
137    let surface_transform = canvas_surface_transform(expanded_node, context);
138    let coverage_bounds =
139        canvas_surface_bounds_for_transform(surface_transform, local_coverage_bounds);
140
141    if !rc.begin_node_with_bounds(
142        layer_id,
143        node_id,
144        expanded_node.occlusion.get().z_index,
145        coverage_bounds,
146        context.canvas_node_light_mask(expanded_node.id),
147    ) {
148        if rc.take_clean_skipped_node(layer_id, node_id) {
149            context.clear_canvas_node_dirty(&expanded_node.id);
150        }
151        return None;
152    }
153
154    Some(CanvasNodeRenderScope {
155        layer_id,
156        node_id,
157        surface_transform,
158        bounds: tab.bounds,
159    })
160}
161/// Extracts fill and stroke alpha with the same local geometry as visible paint.
162pub(crate) fn alpha_mask_paints(
163    node: &pax_runtime::ExpandedNode,
164    path: kurbo::BezPath,
165    fill: pax_runtime_api::Fill,
166    stroke: pax_runtime_api::Stroke,
167) -> Vec<pax_runtime_api::AlphaMaskPaint> {
168    use pax_runtime_api::drawing::stroke_utils::stroked_outline_path;
169    let transform = kurbo::Affine::from(node.transform_and_bounds.get().transform);
170    let opacity = node.computed_opacity.get();
171    let mut paints = Vec::new();
172    if fill.coverage_alpha_0_1() > f64::EPSILON {
173        paints.push(pax_runtime_api::AlphaMaskPaint {
174            path: path.clone(),
175            transform,
176            fill,
177            opacity,
178        });
179    }
180    if let Some(path) = stroked_outline_path(&path, &stroke) {
181        paints.push(pax_runtime_api::AlphaMaskPaint {
182            path,
183            transform,
184            fill: pax_runtime_api::Fill::Solid(stroke.color.get()),
185            opacity,
186        });
187    }
188    paints
189}