1use pax_engine::api::LocalProperty;
2use std::iter;
3use std::rc::Rc;
4
5use crate::common::{native_surface_opacity, patch_if_needed};
6use kurbo::Affine;
7use pax_engine::*;
8use pax_message::{AnyCreatePatch, FramePatch};
9use pax_runtime::api as pax_runtime_api;
10use pax_runtime::api::{
11 bez_path_to_svg_path_data, borrow, borrow_mut, use_RefCell, Layer, Property, RenderContext,
12};
13use pax_runtime::{
14 BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
15};
16use_RefCell!();
17
18#[pax]
61#[engine_import_path("pax_engine")]
62#[primitive("pax_std::core::mask::MaskInstance")]
63pub struct Mask {
64 pub alpha: Property<bool>,
66 pub feather: Property<f64>,
68}
69
70pub struct MaskInstance {
72 base: BaseInstance,
73}
74
75#[cfg(test)]
76mod tests;
77
78impl MaskInstance {
79 fn alpha_settings(node: &ExpandedNode) -> (bool, f64) {
80 node.with_properties_unwrapped(|p: &mut Mask| {
81 (p.alpha.local().get(), p.feather.local().get().max(0.0))
82 })
83 }
84
85 fn collect_alpha_paints(
86 node: &ExpandedNode,
87 inherited_scope_count: usize,
88 paints: &mut Vec<pax_runtime_api::AlphaMaskPaint>,
89 ) {
90 let relative_opacity = node
91 .computed_opacity_scopes
92 .get()
93 .iter()
94 .skip(inherited_scope_count)
95 .fold(1.0, |alpha, scope| alpha * scope.opacity as f64);
96 paints.extend(
97 borrow!(node.instance_node)
98 .resolve_alpha_mask_paints(node)
99 .into_iter()
100 .map(|mut paint| {
101 if let Some((_, opacity)) = paint.composition.as_mut() {
102 *opacity *= relative_opacity as f32;
103 } else {
104 paint.opacity *= relative_opacity;
105 }
106 paint
107 }),
108 );
109 for child in node.children.get().iter().rev() {
110 Self::collect_alpha_paints(child, inherited_scope_count, paints);
111 }
112 }
113 fn sync_mask_source_layout(expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
114 let children = expanded_node.children.get();
115 let mounted_children = borrow!(expanded_node.mounted_children);
116 let children_changed = children.len() != mounted_children.len()
117 || children
118 .iter()
119 .zip(mounted_children.iter())
120 .any(|(child, mounted)| !Rc::ptr_eq(child, mounted));
121 drop(mounted_children);
122
123 let needs_parent_binding = children.iter().any(|child| {
124 borrow!(child.render_parent)
125 .upgrade()
126 .is_none_or(|parent| !Rc::ptr_eq(&parent, expanded_node))
127 });
128
129 if children_changed || needs_parent_binding {
130 expanded_node.attach_children(children.clone(), context, &expanded_node.parent_frame);
131 }
132
133 for child in children {
134 Self::sync_mask_source_layout(&child, context);
135 }
136 }
137
138 fn refresh_mask_source_layout(expanded_node: &ExpandedNode, context: &Rc<RuntimeContext>) {
139 let mask_source = {
140 let sidecar_children = borrow!(expanded_node.sidecar_children);
141 sidecar_children.first().cloned()
142 };
143 if let Some(mask_source) = mask_source {
144 Self::sync_mask_source_layout(&mask_source, context);
145 }
146 }
147
148 fn mark_canvas_descendants_dirty(expanded_node: &ExpandedNode, context: &Rc<RuntimeContext>) {
149 for child in expanded_node.children.get().iter() {
150 if borrow!(child.instance_node).base().flags().layer == Layer::Canvas {
151 context.mark_canvas_node_dirty(child.id);
152 context.set_canvas_dirty(child.occlusion.get().render_layer_id);
153 }
154 Self::mark_canvas_descendants_dirty(child, context);
155 }
156 }
157
158 fn resolve_mask_path(expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
159 let mask_source = {
160 let sidecar_children = borrow!(expanded_node.sidecar_children);
161 sidecar_children.first().cloned()
162 };
163 let Some(mask_source) = mask_source else {
164 return None;
165 };
166 Self::resolve_subtree_coverage_path(&mask_source)
167 }
168
169 fn resolve_subtree_coverage_path(expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
170 let mut coverage = kurbo::BezPath::new();
171 if let Some(path) =
172 borrow!(expanded_node.instance_node).resolve_coverage_path(expanded_node)
173 {
174 coverage.extend(path.elements().iter().copied());
175 }
176 for child in expanded_node.children.get().iter() {
177 if let Some(path) = Self::resolve_subtree_coverage_path(child) {
178 coverage.extend(path.elements().iter().copied());
179 }
180 }
181
182 if coverage.elements().is_empty() {
183 None
184 } else {
185 Some(coverage)
186 }
187 }
188
189 fn watch_mask_source(
190 owner: &Rc<ExpandedNode>,
191 source: &Rc<ExpandedNode>,
192 context: &Rc<RuntimeContext>,
193 ) -> LocalProperty<()> {
194 let mut deps = vec![
195 source.children.untyped(),
196 source.transform_and_bounds.untyped(),
197 source.computed_opacity.untyped(),
198 source.computed_opacity_scopes.untyped(),
199 ];
200 deps.extend(
201 borrow!(source.properties_scope)
202 .values()
203 .cloned()
204 .map(|v| v.get_untyped_property().clone()),
205 );
206 let weak_owner = Rc::downgrade(owner);
207 let weak_source = Rc::downgrade(source);
208 let weak_context = Rc::downgrade(context);
209 let child_watches: RefCell<Vec<(pax_runtime::ExpandedNodeIdentifier, LocalProperty<()>)>> =
210 RefCell::new(Vec::new());
211 let watcher = LocalProperty::computed_with_name(
212 move || {
213 let (Some(owner), Some(source), Some(context)) = (
214 weak_owner.upgrade(),
215 weak_source.upgrade(),
216 weak_context.upgrade(),
217 ) else {
218 return;
219 };
220 let children = source.children.get();
221 let mut watches = borrow_mut!(child_watches);
222 let unchanged = children.len() == watches.len()
223 && children
224 .iter()
225 .zip(watches.iter())
226 .all(|(child, (id, _))| child.id == *id);
227 if !unchanged {
228 let mut previous = std::mem::take(&mut *watches);
232 *watches = children
233 .iter()
234 .map(|child| {
235 let watch = previous
236 .iter()
237 .position(|(id, _)| *id == child.id)
238 .map(|i| previous.swap_remove(i).1)
239 .unwrap_or_else(|| {
240 Self::watch_mask_source(&owner, child, &context)
241 });
242 (child.id, watch)
243 })
244 .collect();
245 }
246 owner.changed_listener.invalidate();
247 },
248 &deps,
249 "mask source invalidation",
250 );
251 context.register_expanded_node_effect_property_named(owner, &watcher, "mask source");
252 watcher
253 }
254
255 fn mask_path_for_layer(
256 mask_path: &kurbo::BezPath,
257 expanded_node: &ExpandedNode,
258 layer: usize,
259 context: &RuntimeContext,
260 ) -> kurbo::BezPath {
261 Self::mask_transform_for_layer(expanded_node, layer, context) * mask_path.clone()
262 }
263
264 fn mask_transform_for_layer(
265 expanded_node: &ExpandedNode,
266 layer: usize,
267 context: &RuntimeContext,
268 ) -> Affine {
269 let Some(owner_id) = context.get_layer_scroller_owner(layer) else {
270 return Affine::IDENTITY;
271 };
272 let Some(owner) = context.get_expanded_node_by_eid(owner_id) else {
273 return Affine::IDENTITY;
274 };
275 let owner_inverse = Affine::from(owner.transform_and_bounds.get().transform.inverse());
276 let mut layer_transform = owner_inverse;
277
278 if owner.is_descendant_of(&expanded_node.id) {
283 if let Some(state) = context.get_scroller_surface_state(owner_id.to_u32()) {
284 let scroll_x = if state.presentation_scroll_x.is_finite() {
285 state.presentation_scroll_x
286 } else {
287 state.scroll_x
288 };
289 let scroll_y = if state.presentation_scroll_y.is_finite() {
290 state.presentation_scroll_y
291 } else {
292 state.scroll_y
293 };
294 layer_transform = Affine::translate((scroll_x, scroll_y)) * layer_transform;
295 }
296 }
297
298 layer_transform
299 }
300
301 fn layer_clip_is_handled_by_scroller_dom(
302 expanded_node: &ExpandedNode,
303 layer: usize,
304 context: &RuntimeContext,
305 ) -> bool {
306 if Self::alpha_settings(expanded_node).0 {
307 return false;
309 }
310 let Some(owner_id) = context.get_layer_scroller_owner(layer) else {
311 return false;
312 };
313 let Some(owner) = context.get_expanded_node_by_eid(owner_id) else {
314 return false;
315 };
316
317 owner.is_descendant_of(&expanded_node.id)
322 }
323}
324
325impl InstanceNode for MaskInstance {
326 fn supports_alpha_source_render(&self) -> bool {
327 true
328 }
329
330 fn instantiate(args: InstantiationArgs) -> Rc<Self>
331 where
332 Self: Sized,
333 {
334 Rc::new(Self {
335 base: BaseInstance::new(
336 args,
337 InstanceFlags {
338 invisible_to_slot: false,
339 invisible_to_raycasting: true,
340 layer: Layer::DontCare,
341 is_component: false,
342 is_slot: false,
343 },
344 ),
345 })
346 }
347
348 fn handle_mount(
349 self: Rc<Self>,
350 expanded_node: &Rc<ExpandedNode>,
351 context: &Rc<RuntimeContext>,
352 ) {
353 let id = expanded_node.id.to_u32();
354 if !expanded_node.is_render_source() {
355 context.enqueue_native_message(pax_message::NativeMessage::FrameCreate(
356 AnyCreatePatch {
357 id,
358 parent_frame: expanded_node.parent_frame.get().map(|v| v.to_u32()),
359 render_layer_id: 0,
360 },
361 ));
362 }
363
364 let env = Rc::clone(&expanded_node.stack);
365 let children = borrow!(self.base().get_instance_children());
366 if children.len() != 2 {
367 log::warn!(
368 "Mask expects exactly 2 direct children, got {}",
369 children.len()
370 );
371 }
372 let this_mask_prop = LocalProperty::new(Some(expanded_node.id));
373
374 let mut itr = children.iter().cloned();
375 if let Some(content_child) = itr.next() {
376 let content = expanded_node.generate_children(
377 iter::once((content_child, Rc::clone(&env))),
378 context,
379 &this_mask_prop,
380 true,
381 );
382 expanded_node.children.set(content);
383 } else {
384 expanded_node.children.set(Vec::new());
385 }
386
387 if let Some(mask_child) = itr.next() {
388 let sidecar = expanded_node.create_children_detached(
389 iter::once((mask_child, Rc::clone(&env))),
390 context,
391 &Rc::downgrade(expanded_node),
392 );
393 let sidecar = expanded_node.attach_sidecar_children(
394 sidecar,
395 context,
396 &expanded_node.parent_frame,
397 );
398 for child in sidecar.iter() {
399 child.mount_as_render_source(expanded_node, context);
400 }
401 }
402
403 let weak_self_ref = Rc::downgrade(expanded_node);
404 let context = Rc::clone(context);
405 let last_patch = Rc::new(RefCell::new(FramePatch {
406 id,
407 ..Default::default()
408 }));
409
410 let mut deps = vec![
411 expanded_node.transform_and_bounds.untyped(),
412 expanded_node.computed_opacity.untyped(),
413 expanded_node.occlusion.untyped(),
414 ];
415 expanded_node.with_properties_unwrapped(|p: &mut Mask| {
416 deps.extend([p.alpha.untyped(), p.feather.untyped()]);
417 });
418 if let Some(mask_child) = borrow!(expanded_node.sidecar_children).first() {
419 Self::sync_mask_source_layout(mask_child, &context);
420 let watcher = Self::watch_mask_source(expanded_node, mask_child, &context);
423 borrow_mut!(expanded_node.subscriptions).push(watcher);
424 }
425
426 expanded_node
427 .changed_listener
428 .replace_with(LocalProperty::computed(
429 move || {
430 let Some(expanded_node) = weak_self_ref.upgrade() else {
431 return;
432 };
433
434 Self::refresh_mask_source_layout(&expanded_node, &context);
435 if Self::alpha_settings(&expanded_node).0 {
436 Self::mark_canvas_descendants_dirty(&expanded_node, &context);
437 }
438 let clip_path = if Self::alpha_settings(&expanded_node).0 {
439 String::new()
440 } else {
441 Self::resolve_mask_path(&expanded_node)
442 .map(|path| bez_path_to_svg_path_data(&path))
443 .unwrap_or_default()
444 };
445
446 let mut old_state = borrow_mut!(last_patch);
447 let mut patch = FramePatch {
448 id,
449 ..Default::default()
450 };
451 let computed_tab = expanded_node.transform_and_bounds.get();
452 let (width, height) = computed_tab.bounds;
453
454 let updates = [
455 patch_if_needed(
456 &mut old_state.clip_content,
457 &mut patch.clip_content,
458 !clip_path.is_empty(),
459 ),
460 patch_if_needed(&mut old_state.size_x, &mut patch.size_x, width),
461 patch_if_needed(&mut old_state.size_y, &mut patch.size_y, height),
462 patch_if_needed(
463 &mut old_state.transform,
464 &mut patch.transform,
465 computed_tab.transform.coeffs().to_vec(),
466 ),
467 patch_if_needed(&mut old_state.clip_path, &mut patch.clip_path, clip_path),
468 patch_if_needed(
469 &mut old_state.opacity,
470 &mut patch.opacity,
471 native_surface_opacity(&expanded_node, &context),
472 ),
473 patch_if_needed(
474 &mut old_state.parent_frame,
475 &mut patch.parent_frame,
476 expanded_node.parent_frame.get().map(|v| v.to_u32()),
477 ),
478 patch_if_needed(
479 &mut old_state.z_index,
480 &mut patch.z_index,
481 expanded_node.occlusion.get().z_index,
482 ),
483 ];
484
485 if updates.into_iter().any(|updated| updated) {
486 if !expanded_node.is_render_source() {
487 context.enqueue_native_message(
488 pax_message::NativeMessage::FrameUpdate(patch),
489 );
490 }
491 Self::mark_canvas_descendants_dirty(&expanded_node, &context);
492 }
493 },
494 &deps,
495 ));
496 }
497
498 fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
499 let sources = std::mem::take(&mut *borrow_mut!(expanded_node.sidecar_children));
500 for source in sources {
501 source.recurse_unmount(context);
502 }
503 expanded_node
504 .changed_listener
505 .replace_with(LocalProperty::default());
506 if !expanded_node.is_render_source() {
507 context.enqueue_native_message(pax_message::NativeMessage::FrameDelete(
508 expanded_node.id.to_u32(),
509 ));
510 }
511 }
512
513 fn handle_pre_render(
514 &self,
515 expanded_node: &ExpandedNode,
516 rtc: &Rc<RuntimeContext>,
517 rcs: &mut dyn RenderContext,
518 ) {
519 let layers = rcs.layers();
520 let has_dirty_layer = (0..layers).any(|layer| rtc.is_canvas_dirty(&layer));
521 if rcs.alpha_source_layer().is_none() && !has_dirty_layer {
522 return;
523 }
524
525 Self::refresh_mask_source_layout(expanded_node, rtc);
526 let (alpha, feather) = Self::alpha_settings(expanded_node);
527 let mask_path = (!alpha)
530 .then(|| Self::resolve_mask_path(expanded_node))
531 .flatten();
532 if mask_path.is_none() && !alpha {
533 return;
534 }
535 let mut paints = Vec::new();
536 if alpha && !rcs.supports_alpha_source_capture() {
537 if let Some(source) = borrow!(expanded_node.sidecar_children).first() {
538 Self::collect_alpha_paints(
541 source,
542 expanded_node.computed_opacity_scopes.get().len(),
543 &mut paints,
544 );
545 }
546 }
547
548 #[cfg(debug_assertions)]
549 let mut applied_layers = 0;
550 #[cfg(debug_assertions)]
551 let mut scroller_dom_layers = 0;
552
553 let source_layer = rcs.alpha_source_layer();
554 for layer in
555 source_layer.map_or_else(|| (0..layers).collect::<Vec<_>>(), |layer| vec![layer])
556 {
557 if source_layer.is_none() && !rtc.is_canvas_dirty(&layer) {
558 continue;
559 }
560 if source_layer.is_none()
561 && Self::layer_clip_is_handled_by_scroller_dom(expanded_node, layer, rtc)
562 {
563 #[cfg(debug_assertions)]
564 {
565 scroller_dom_layers += 1;
566 }
567 continue;
568 }
569 if !rcs.begin_node(
572 layer,
573 expanded_node.id.to_u32(),
574 expanded_node.occlusion.get().z_index,
575 0,
576 ) {
577 continue;
578 }
579 rcs.save(layer);
580 if alpha && rcs.supports_alpha_source_capture() {
581 let mapping = if source_layer.is_some() {
582 Affine::IDENTITY
583 } else {
584 Self::mask_transform_for_layer(expanded_node, layer, rtc)
585 };
586 rcs.begin_alpha_source(
587 layer,
588 mapping,
589 expanded_node.computed_opacity_scopes.get().len(),
590 feather,
591 );
592 if let Some(source) = borrow!(expanded_node.sidecar_children).first().cloned() {
593 source.recurse_render_alpha_source(rtc, rcs);
594 }
595 rcs.end_alpha_source(layer);
596 } else if alpha {
597 let mapping = Self::mask_transform_for_layer(expanded_node, layer, rtc);
598 let mut layer_paints = paints.clone();
599 for paint in &mut layer_paints {
600 paint.transform = mapping * paint.transform;
601 }
602 rcs.clip_alpha(layer, &layer_paints, feather);
603 } else if let Some(path) = &mask_path {
604 rcs.clip(
605 layer,
606 if source_layer.is_some() {
607 path.clone()
608 } else {
609 Self::mask_path_for_layer(path, expanded_node, layer, rtc)
610 },
611 );
612 }
613 let _ = rcs.end_node(layer, expanded_node.id.to_u32());
614 #[cfg(debug_assertions)]
615 {
616 applied_layers += 1;
617 }
618 }
619
620 #[cfg(debug_assertions)]
621 log::trace!(
622 "mask clip pre_render: node={}, total_layers={}, applied_layers={}, scroller_dom_layers={}",
623 expanded_node.id.to_u32(),
624 layers,
625 applied_layers,
626 scroller_dom_layers,
627 );
628 }
629
630 fn handle_post_render(
631 &self,
632 expanded_node: &ExpandedNode,
633 rtc: &Rc<RuntimeContext>,
634 rcs: &mut dyn RenderContext,
635 ) {
636 let layers = rcs.layers();
637 let has_dirty_layer = (0..layers).any(|layer| rtc.is_canvas_dirty(&layer));
638 if rcs.alpha_source_layer().is_none() && !has_dirty_layer {
639 return;
640 }
641 if !Self::alpha_settings(expanded_node).0
642 && Self::resolve_mask_path(expanded_node).is_none()
643 {
644 return;
645 }
646
647 #[cfg(debug_assertions)]
648 let mut restored_layers = 0;
649 #[cfg(debug_assertions)]
650 let mut scroller_dom_layers = 0;
651
652 let source_layer = rcs.alpha_source_layer();
653 for layer in
654 source_layer.map_or_else(|| (0..layers).collect::<Vec<_>>(), |layer| vec![layer])
655 {
656 if source_layer.is_none() && !rtc.is_canvas_dirty(&layer) {
657 continue;
658 }
659 if source_layer.is_none()
660 && Self::layer_clip_is_handled_by_scroller_dom(expanded_node, layer, rtc)
661 {
662 #[cfg(debug_assertions)]
663 {
664 scroller_dom_layers += 1;
665 }
666 continue;
667 }
668 rcs.restore(layer);
669 #[cfg(debug_assertions)]
670 {
671 restored_layers += 1;
672 }
673 }
674
675 #[cfg(debug_assertions)]
676 log::trace!(
677 "mask clip post_render: node={}, total_layers={}, restored_layers={}, scroller_dom_layers={}",
678 expanded_node.id.to_u32(),
679 layers,
680 restored_layers,
681 scroller_dom_layers,
682 );
683 }
684
685 fn resolve_effect_clip_path(&self, expanded_node: &ExpandedNode) -> Option<kurbo::BezPath> {
686 if Self::alpha_settings(expanded_node).0 {
689 None
690 } else {
691 Self::resolve_mask_path(expanded_node)
692 }
693 }
694
695 fn clips_content(&self, expanded_node: &ExpandedNode) -> bool {
696 !Self::alpha_settings(expanded_node).0 && Self::resolve_mask_path(expanded_node).is_some()
697 }
698
699 fn resolve_debug(
700 &self,
701 f: &mut std::fmt::Formatter,
702 _expanded_node: Option<&ExpandedNode>,
703 ) -> std::fmt::Result {
704 f.debug_struct("Mask").finish()
705 }
706
707 fn base(&self) -> &BaseInstance {
708 &self.base
709 }
710}