Skip to main content

cranpose_render_common/
graph_scene.rs

1use std::{
2    cell::{Cell, Ref, RefCell},
3    rc::Rc,
4};
5
6use cranpose_core::{
7    MemoryApplier, NodeId,
8    collections::map::{HashMap, HashSet},
9};
10use cranpose_foundation::{MINIMUM_TOUCH_TARGET_SIZE, PointerEvent, PointerEventKind};
11use cranpose_ui::{LayoutNode, ModifierNodeSlices, SubcomposeLayoutNode};
12use cranpose_ui_graphics::{Point, PointerIcon, Rect, RoundedCornerShape, shared_sort, space::Ray};
13
14#[cfg(feature = "layer-tree")]
15use crate::graph::LayerNode;
16use crate::{
17    HitTestTarget, RenderScene, SceneUpdates,
18    graph::ProjectiveTransform,
19    left_nodes::LeftNodes,
20    scene_pick::ScenePick,
21    scene_store::{LayerRef, RecordEvents, SceneStore},
22};
23
24/// Counters and once-only warnings that a scene collects while it dispatches pointer events.
25pub struct RenderDiagnostics {
26    reported_warnings: RefCell<HashSet<&'static str>>,
27    live_modifier_slice_lookup_miss_count: Cell<usize>,
28}
29
30impl RenderDiagnostics {
31    /// Creates diagnostics with no warnings reported and no lookup misses counted.
32    pub fn new() -> Self {
33        Self {
34            reported_warnings: RefCell::new(HashSet::default()),
35            live_modifier_slice_lookup_miss_count: Cell::new(0),
36        }
37    }
38
39    /// Returns true the first time it is called with `key`, so that a warning is reported once.
40    pub fn claim_warning_once(&self, key: &'static str) -> bool {
41        self.reported_warnings.borrow_mut().insert(key)
42    }
43
44    /// Counts one pointer dispatch that fell back to the captured modifier slices because the live
45    /// node could not be found.
46    pub fn record_live_modifier_slice_lookup_miss(&self) {
47        self.live_modifier_slice_lookup_miss_count.set(
48            self.live_modifier_slice_lookup_miss_count
49                .get()
50                .saturating_add(1),
51        );
52    }
53
54    /// Number of pointer dispatches that did not find the live node and used the modifier slices
55    /// captured at build time instead.
56    pub fn live_modifier_slice_lookup_miss_count(&self) -> usize {
57        self.live_modifier_slice_lookup_miss_count.get()
58    }
59}
60
61impl Default for RenderDiagnostics {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67/// A clip that cuts a hit target, kept as a transformed rectangle.
68#[derive(Clone, Copy, Debug, PartialEq)]
69pub struct HitClip {
70    /// The clip rectangle after the layer transforms, as four corners in window space.
71    pub quad: [[f32; 2]; 4],
72    /// Axis-aligned bounds of `quad` in window coordinates.
73    pub bounds: Rect,
74}
75
76/// A mesh surface of a scene, as the hit targets on its content see it:
77/// the scene's pick, which surface it is, and the clips above it.
78pub struct SurfaceTarget {
79    /// Finds the surface and content point a window point shows.
80    pub pick: Rc<ScenePick>,
81    /// The surface's index in `pick`.
82    pub index: usize,
83    /// Axis-aligned bounds of the clips above the surface, in window space.
84    pub outer_clip_bounds: Option<Rect>,
85    /// The clips above the surface, as quads in window space.
86    pub outer_clips: Vec<HitClip>,
87}
88
89const WINDOW_BOUNDS_STEPS: u16 = 2;
90
91impl SurfaceTarget {
92    /// Where `local`, a rect of a target's own space into which
93    /// `content_to_local` maps the surface's content, shows in the window:
94    /// the bounds of a grid of its points in front of the eye; `None` when
95    /// none is.
96    pub fn window_bounds(
97        &self,
98        content_to_local: &ProjectiveTransform,
99        local: Rect,
100    ) -> Option<Rect> {
101        let local_to_content = content_to_local.inverse()?;
102        let steps = f32::from(WINDOW_BOUNDS_STEPS);
103        let grid = (0..=WINDOW_BOUNDS_STEPS)
104            .flat_map(|row| (0..=WINDOW_BOUNDS_STEPS).map(move |column| (row, column)));
105        grid.filter_map(|(row, column)| {
106            let point = Point::new(
107                local.x + local.width * f32::from(column) / steps,
108                local.y + local.height * f32::from(row) / steps,
109            );
110            let content = local_to_content.map_point(point);
111            self.pick.window_point(self.index, content)
112        })
113        .map(|point| Rect {
114            x: point.x,
115            y: point.y,
116            width: 0.0,
117            height: 0.0,
118        })
119        .reduce(|bounds, point| bounds.union(point))
120    }
121}
122
123/// Where a hit target on a mesh surface lies on the surface's content.
124#[derive(Clone, Copy)]
125pub struct SurfaceGeometry<'a> {
126    /// The surface the target is on.
127    pub target: &'a Rc<SurfaceTarget>,
128    /// Maps the surface's content into the node's local space.
129    pub content_to_local: ProjectiveTransform,
130    /// Axis-aligned bounds of the clips within the surface, in content
131    /// space, or `None` when none clips.
132    pub clip_bounds: Option<Rect>,
133    /// The clips within the surface, as quads in content space.
134    pub clips: &'a [HitClip],
135}
136
137impl SurfaceGeometry<'_> {
138    /// Where `local`, a rect of the target's own space, shows in the window.
139    pub fn window_bounds(&self, local: Rect) -> Option<Rect> {
140        self.target.window_bounds(&self.content_to_local, local)
141    }
142}
143
144/// Geometry for a hit target, borrowing the clip chain until the sink records it.
145#[derive(Clone, Copy)]
146pub struct HitGeometry<'a> {
147    /// Axis-aligned bounds of `quad` in window coordinates.
148    pub rect: Rect,
149    /// The node's rectangle after the layer transforms, as four corners in window space.
150    pub quad: [[f32; 2]; 4],
151    /// The node's own rectangle in its local space.
152    pub local_bounds: Rect,
153    /// Maps window coordinates into the node's local space.
154    pub world_to_local: ProjectiveTransform,
155    /// Axis-aligned bounds of the ancestors' clips in window space, or `None` when none clips.
156    pub hit_clip_bounds: Option<Rect>,
157    /// Clips of the ancestors that cut the target, as transformed quads in window space.
158    pub hit_clips: &'a [HitClip],
159    /// For a target on a mesh surface, where it lies on the surface's
160    /// content. The window-space fields above then hold the surface's flat
161    /// stand-in, exact only on a flat mesh; the surface decides the hit.
162    pub surface: Option<SurfaceGeometry<'a>>,
163}
164
165/// What a hit target answers with: the shape that narrows its bounds, and the
166/// node's modifier slices, which hold the pointer handlers it dispatches to
167/// and the pointer icon it asks for while hovered.
168pub struct HitTargetSpec<'a> {
169    /// Narrows the target's rectangle to a rounded shape, so a point in a
170    /// corner cutout misses it.
171    pub shape: Option<RoundedCornerShape>,
172    /// The node's slices, shared by the target rather than copied.
173    pub handlers: &'a Rc<ModifierNodeSlices>,
174}
175
176/// A hit target in window space: the node's geometry, clips and pointer handlers.
177#[derive(Clone)]
178pub struct HitRegion {
179    /// The layout node that owns the target.
180    pub node_id: NodeId,
181    /// Nodes that keep receiving the move, up and cancel events of a gesture that starts here: this
182    /// node first, then its pointer-input ancestors from the nearest outward.
183    pub capture_path: Vec<NodeId>,
184    /// Axis-aligned bounds of `quad` in window coordinates.
185    pub rect: Rect,
186    /// The node's rectangle after the layer transforms, as four corners in window space.
187    pub quad: [[f32; 2]; 4],
188    /// The node's own rectangle in its local space.
189    pub local_bounds: Rect,
190    /// Maps window coordinates into the node's local space.
191    pub world_to_local: ProjectiveTransform,
192    /// Rounded shape that narrows the target's rectangle, or `None` for a plain rectangle.
193    pub shape: Option<RoundedCornerShape>,
194    /// The node's modifier slices, shared with the scene: its pointer
195    /// handlers and pointer icon.
196    pub handlers: Rc<ModifierNodeSlices>,
197    /// Draw order of the target. A larger value is drawn later and is hit first.
198    pub z_index: usize,
199    /// Axis-aligned bounds of the ancestors' clips in window space, or `None` when none clips.
200    pub hit_clip_bounds: Option<Rect>,
201    /// Clips of the ancestors that cut this target, as transformed quads in window space.
202    pub hit_clips: Vec<HitClip>,
203    surface: Option<Rc<SurfaceRegion>>,
204    diagnostics: Rc<RenderDiagnostics>,
205}
206
207struct SurfaceRegion {
208    target: Rc<SurfaceTarget>,
209    content_to_local: ProjectiveTransform,
210    clip_bounds: Option<Rect>,
211    clips: Vec<HitClip>,
212}
213
214impl SurfaceRegion {
215    fn local_point(&self, window: Point) -> Option<Point> {
216        let target = &self.target;
217        if target
218            .outer_clip_bounds
219            .is_some_and(|clip| !clip.contains(window.x, window.y))
220            || !target
221                .outer_clips
222                .iter()
223                .all(|clip| point_in_quad(window, clip.quad))
224        {
225            return None;
226        }
227        self.local_in(target.pick.content_point(window, target.index)?)
228    }
229
230    fn local_point_along(&self, ray: Ray) -> Option<Point> {
231        let (index, hit) = self.target.pick.nearest_along(ray)?;
232        (index == self.target.index)
233            .then(|| self.local_in(hit.point))
234            .flatten()
235    }
236
237    fn local_in(&self, content: Point) -> Option<Point> {
238        if self
239            .clip_bounds
240            .is_some_and(|clip| !clip.contains(content.x, content.y))
241            || !self
242                .clips
243                .iter()
244                .all(|clip| point_in_quad(content, clip.quad))
245        {
246            return None;
247        }
248        self.content_to_local.map_point_in_front(content)
249    }
250
251    fn drag_point(&self, event: &PointerEvent) -> Option<Point> {
252        let target = &self.target;
253        let content = match event.ray {
254            Some(ray) => target.pick.drag_point_along(ray, target.index)?,
255            None => target
256                .pick
257                .drag_point(event.global_position, target.index)?,
258        };
259        Some(self.content_to_local.map_point(content))
260    }
261}
262
263struct HitRegionInit<'a> {
264    node_id: NodeId,
265    capture_path: Vec<NodeId>,
266    geometry: HitGeometry<'a>,
267    clip_buffer: Vec<HitClip>,
268    shape: Option<RoundedCornerShape>,
269    handlers: Rc<ModifierNodeSlices>,
270    z_index: usize,
271    diagnostics: Rc<RenderDiagnostics>,
272}
273
274impl Default for HitRegionInit<'_> {
275    fn default() -> Self {
276        Self {
277            node_id: NodeId(0),
278            capture_path: Vec::new(),
279            geometry: HitGeometry {
280                rect: Rect {
281                    x: 0.0,
282                    y: 0.0,
283                    width: 0.0,
284                    height: 0.0,
285                },
286                quad: [[0.0, 0.0]; 4],
287                local_bounds: Rect {
288                    x: 0.0,
289                    y: 0.0,
290                    width: 0.0,
291                    height: 0.0,
292                },
293                world_to_local: ProjectiveTransform::identity(),
294                hit_clip_bounds: None,
295                hit_clips: &[],
296                surface: None,
297            },
298            clip_buffer: Vec::new(),
299            shape: None,
300            handlers: Rc::default(),
301            z_index: 0,
302            diagnostics: Rc::new(RenderDiagnostics::new()),
303        }
304    }
305}
306
307impl HitRegion {
308    fn with_diagnostics(init: HitRegionInit<'_>) -> Self {
309        let HitRegionInit {
310            node_id,
311            capture_path,
312            geometry,
313            clip_buffer: mut hit_clips,
314            shape,
315            handlers,
316            z_index,
317            diagnostics,
318        } = init;
319        let HitGeometry {
320            rect,
321            quad,
322            local_bounds,
323            world_to_local,
324            hit_clip_bounds,
325            hit_clips: clips,
326            surface,
327        } = geometry;
328        hit_clips.extend_from_slice(clips);
329        Self {
330            node_id,
331            capture_path,
332            rect,
333            quad,
334            local_bounds,
335            world_to_local,
336            shape,
337            handlers,
338            z_index,
339            hit_clip_bounds,
340            hit_clips,
341            surface: surface.map(|surface| {
342                Rc::new(SurfaceRegion {
343                    target: Rc::clone(surface.target),
344                    content_to_local: surface.content_to_local,
345                    clip_bounds: surface.clip_bounds,
346                    clips: surface.clips.to_vec(),
347                })
348            }),
349            diagnostics,
350        }
351    }
352
353    fn contains(&self, x: f32, y: f32) -> bool {
354        if let Some(surface) = &self.surface {
355            return surface
356                .local_point(Point { x, y })
357                .is_some_and(|local| self.contains_local(local));
358        }
359        if !self.rect.contains(x, y) {
360            return false;
361        }
362
363        if let Some(clip_bounds) = self.hit_clip_bounds
364            && !clip_bounds.contains(x, y)
365        {
366            return false;
367        }
368
369        let point = Point { x, y };
370        if !point_in_quad(point, self.quad) {
371            return false;
372        }
373
374        for clip in &self.hit_clips {
375            if !point_in_quad(point, clip.quad) {
376                return false;
377            }
378        }
379
380        let Some(local_point) = self.world_to_local.map_point_in_front(point) else {
381            return false;
382        };
383        self.contains_local(local_point)
384    }
385
386    fn contains_local(&self, local_point: Point) -> bool {
387        if let Some(shape) = self.shape {
388            point_in_rounded_rect(local_point, self.local_bounds, shape)
389        } else {
390            self.local_bounds.contains(local_point.x, local_point.y)
391        }
392    }
393
394    fn reach_distance(&self, x: f32, y: f32) -> Option<f32> {
395        if self.handlers.pointer_inputs().is_empty() || self.surface.is_some() {
396            return None;
397        }
398        if let Some(clip_bounds) = self.hit_clip_bounds
399            && !clip_bounds.contains(x, y)
400        {
401            return None;
402        }
403        let grow_x = ((MINIMUM_TOUCH_TARGET_SIZE - self.rect.width) / 2.0).max(0.0);
404        let grow_y = ((MINIMUM_TOUCH_TARGET_SIZE - self.rect.height) / 2.0).max(0.0);
405        if grow_x <= 0.0 && grow_y <= 0.0 {
406            return None;
407        }
408        let right = self.rect.x + self.rect.width;
409        let bottom = self.rect.y + self.rect.height;
410        let in_reach = x >= self.rect.x - grow_x
411            && x <= right + grow_x
412            && y >= self.rect.y - grow_y
413            && y <= bottom + grow_y;
414        if !in_reach {
415            return None;
416        }
417        let dx = (self.rect.x - x).max(x - right).max(0.0);
418        let dy = (self.rect.y - y).max(y - bottom).max(0.0);
419        Some(dx * dx + dy * dy)
420    }
421
422    fn localize_event(&self, event: &PointerEvent) -> PointerEvent {
423        let local = match &self.surface {
424            Some(surface) => surface
425                .drag_point(event)
426                .unwrap_or_else(|| self.world_to_local.map_point(event.global_position)),
427            None => self.world_to_local.map_point(event.global_position),
428        };
429        event.copy_with_local_position(Point {
430            x: local.x - self.local_bounds.x,
431            y: local.y - self.local_bounds.y,
432        })
433    }
434
435    fn dispatch_modifier_slices(&self, modifier_slices: &ModifierNodeSlices, event: PointerEvent) {
436        if should_skip_consumed_event(&event) {
437            return;
438        }
439
440        modifier_slices.dispatch_pointer_event(self.localize_event(&event));
441    }
442
443    fn live_modifier_slices(&self, applier: &mut MemoryApplier) -> Option<Rc<ModifierNodeSlices>> {
444        if let Ok(modifier_slices) =
445            applier.with_node::<LayoutNode, _>(self.node_id, |node| node.modifier_slices_snapshot())
446        {
447            return Some(modifier_slices);
448        }
449
450        applier
451            .with_node::<SubcomposeLayoutNode, _>(self.node_id, |node| {
452                node.modifier_slices_snapshot()
453            })
454            .ok()
455    }
456}
457
458fn is_terminal_pointer_event(kind: PointerEventKind) -> bool {
459    matches!(kind, PointerEventKind::Up | PointerEventKind::Cancel)
460}
461
462fn should_skip_consumed_event(event: &PointerEvent) -> bool {
463    event.is_consumed() && !is_terminal_pointer_event(event.kind)
464}
465
466impl HitTestTarget for HitRegion {
467    fn node_id(&self) -> NodeId {
468        self.node_id
469    }
470
471    fn pointer_icon(&self) -> Option<PointerIcon> {
472        self.handlers.pointer_icon().cloned()
473    }
474
475    fn capture_path(&self) -> Vec<NodeId> {
476        self.capture_path.clone()
477    }
478
479    fn dispatch(&self, event: PointerEvent) {
480        self.dispatch_modifier_slices(&self.handlers, event);
481    }
482
483    fn dispatch_with_applier(&self, applier: &mut MemoryApplier, event: PointerEvent) {
484        if let Some(modifier_slices) = self.live_modifier_slices(applier) {
485            self.dispatch_modifier_slices(modifier_slices.as_ref(), event);
486            return;
487        }
488
489        self.diagnostics.record_live_modifier_slice_lookup_miss();
490        self.dispatch_modifier_slices(&self.handlers, event);
491    }
492}
493
494#[derive(Default)]
495struct HitBuffers {
496    hit_clips: Vec<HitClip>,
497    capture_path: Vec<NodeId>,
498}
499
500// The hit targets of a scene's records in draw order, the last drawn at the
501// end, and the storage the next collection of them reuses.
502#[derive(Default)]
503struct HitList {
504    hits: Vec<HitRegion>,
505    buffers: Vec<HitBuffers>,
506    // The draw order index the next pushed target receives.
507    next_z: usize,
508    // Where in `hits` the target of each node lies.
509    node_index: HashMap<NodeId, usize>,
510    // The records changed a target since the list was collected: the next
511    // query collects it again.
512    stale: bool,
513}
514
515impl HitList {
516    // Removes the targets, releases their handlers and keeps their storage.
517    fn clear(&mut self) {
518        self.buffers.clear();
519        for hit in self.hits.drain(..) {
520            let mut buffers = HitBuffers {
521                hit_clips: hit.hit_clips,
522                capture_path: hit.capture_path,
523            };
524            buffers.hit_clips.clear();
525            buffers.capture_path.clear();
526            self.buffers.push(buffers);
527        }
528        self.node_index.clear();
529        self.next_z = 0;
530    }
531}
532
533pub(crate) struct HitTargets<'a> {
534    list: &'a mut HitList,
535    diagnostics: &'a Rc<RenderDiagnostics>,
536}
537
538impl HitTargets<'_> {
539    pub(crate) fn push(
540        &mut self,
541        node_id: NodeId,
542        capture_path: &[NodeId],
543        geometry: HitGeometry<'_>,
544        target: HitTargetSpec<'_>,
545    ) {
546        let HitTargetSpec { shape, handlers } = target;
547        if handlers.pointer_inputs().is_empty() && handlers.pointer_icon().is_none() {
548            return;
549        }
550        let list = &mut *self.list;
551        let mut buffers = list.buffers.pop().unwrap_or_default();
552        buffers.capture_path.extend_from_slice(capture_path);
553
554        let z_index = list.next_z;
555        list.next_z += 1;
556        let hit_index = list.hits.len();
557        list.hits.push(HitRegion::with_diagnostics(HitRegionInit {
558            node_id,
559            capture_path: buffers.capture_path,
560            geometry,
561            clip_buffer: buffers.hit_clips,
562            shape,
563            handlers: Rc::clone(handlers),
564            z_index,
565            diagnostics: Rc::clone(self.diagnostics),
566        }));
567        list.node_index.insert(node_id, hit_index);
568    }
569}
570
571/// The records a window draws together with the hit targets built from them.
572pub struct Scene {
573    store: SceneStore,
574    // Collected from the store when a query first needs them after it
575    // changed: a frame that moves a target and takes no pointer input does
576    // not walk the store for targets.
577    hits: RefCell<HitList>,
578    diagnostics: Rc<RenderDiagnostics>,
579    // The updates that moved a layer with no layout pass, and the rebuilds,
580    // which may have.
581    layer_moves: u64,
582    left_nodes: LeftNodes,
583}
584
585/// How many hit targets a [`Scene`] holds and has room for, and the same for
586/// its index of them by node, for debugging memory use.
587#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
588pub struct HitStorage {
589    /// Hit targets held.
590    pub hits_len: usize,
591    /// Room reserved for hit targets.
592    pub hits_capacity: usize,
593    /// Nodes indexed.
594    pub node_index_len: usize,
595    /// Room reserved in the node index.
596    pub node_index_capacity: usize,
597}
598
599impl Scene {
600    /// Creates an empty scene with no records and no hit targets.
601    pub fn new() -> Self {
602        let mut store = SceneStore::new();
603        store.follow(RecordEvents::LEAVES);
604        Self {
605            left_nodes: LeftNodes::default(),
606            store,
607            hits: RefCell::default(),
608            diagnostics: Rc::new(RenderDiagnostics::new()),
609            layer_moves: 0,
610        }
611    }
612
613    /// The diagnostics shared by the scene and its hit targets.
614    pub fn diagnostics(&self) -> &RenderDiagnostics {
615        self.diagnostics.as_ref()
616    }
617
618    /// The records the scene draws.
619    pub fn store(&self) -> &SceneStore {
620        &self.store
621    }
622
623    /// Keeps the changes of the kinds in `events` for the scene's readers
624    /// from the next update on, beside the leaves the scene reads itself;
625    /// see [`SceneStore::follow`].
626    pub fn follow(&mut self, events: RecordEvents) {
627        self.store.follow(events | RecordEvents::LEAVES);
628    }
629
630    /// Works out the reach of the records a change left stale; see
631    /// [`SceneStore::refresh_reach`].
632    #[cfg(feature = "window-damage")]
633    pub fn refresh_reach(&mut self) {
634        self.store.refresh_reach();
635    }
636
637    /// The root record, `None` while the scene is empty.
638    pub fn root_layer(&self) -> Option<LayerRef<'_>> {
639        self.store.root_layer()
640    }
641
642    /// Writes the layer tree `root` describes in place of the scene's
643    /// records. The hit targets follow it.
644    #[cfg(feature = "layer-tree")]
645    pub fn describe(&mut self, root: &LayerNode) {
646        self.store.describe(root);
647        self.hits.get_mut().stale = true;
648        self.layer_moves += 1;
649    }
650
651    /// Runs `edit` on the scene's records in a new update. The hit targets
652    /// follow them.
653    pub fn edit_store(&mut self, edit: impl FnOnce(&mut SceneStore)) {
654        self.store.begin_update();
655        edit(&mut self.store);
656        self.store.finish_update();
657        self.hits.get_mut().stale = true;
658        self.layer_moves += 1;
659    }
660
661    /// Lowers the layout tree below `root` again from the applier, its records
662    /// reusing the scene's storage. The hit targets follow it.
663    pub fn rebuild_from_applier(&mut self, applier: &MemoryApplier, root: NodeId) {
664        self.hits.get_mut().stale = true;
665        self.layer_moves += 1;
666        if crate::scene_builder::rebuild_from_applier(applier, root, &mut self.store) {
667            crate::scene_builder::publish_space(applier, &self.store);
668        }
669    }
670
671    // The hit targets, collected from the records first when they changed since
672    // they were.
673    fn fresh_hits(&self) -> Ref<'_, HitList> {
674        if self.hits.borrow().stale {
675            let mut list = self.hits.borrow_mut();
676            list.clear();
677            list.stale = false;
678            if let Some(root) = self.store.root_layer() {
679                crate::hit_graph::collect_hits_from_graph(
680                    root,
681                    ProjectiveTransform::identity(),
682                    &mut HitTargets {
683                        list: &mut list,
684                        diagnostics: &self.diagnostics,
685                    },
686                    None,
687                );
688            }
689        }
690        self.hits.borrow()
691    }
692
693    /// The hit targets in draw order, the last drawn at the end.
694    pub fn hit_targets(&self) -> Vec<HitRegion> {
695        self.fresh_hits().hits.clone()
696    }
697
698    /// How much storage the hit targets take.
699    pub fn hit_storage(&self) -> HitStorage {
700        let list = self.hits.borrow();
701        HitStorage {
702            hits_len: list.hits.len(),
703            hits_capacity: list.hits.capacity(),
704            node_index_len: list.node_index.len(),
705            node_index_capacity: list.node_index.capacity(),
706        }
707    }
708
709    /// Applies content and layer-property changes to the scene's records
710    /// in place and returns `true`, or rebuilds the scene and returns
711    /// `false`: for empty updates, an empty scene or an update that cannot
712    /// be applied in place. The hit targets follow the records when the
713    /// update changed a hit target or the geometry above one: each updated
714    /// layer compares its hit state, and the layers beneath one built again,
715    /// before and after.
716    pub fn update_from_applier(
717        &mut self,
718        applier: &MemoryApplier,
719        root: NodeId,
720        updates: SceneUpdates<'_>,
721    ) -> bool {
722        let report = crate::scene_builder::update_from_applier(applier, &mut self.store, updates);
723        if updates.is_empty() || !report.applied() {
724            self.rebuild_from_applier(applier, root);
725            return false;
726        }
727        crate::scene_builder::publish_space(applier, &self.store);
728        if report.hit_graph_dirty {
729            self.hits.get_mut().stale = true;
730        }
731        self.layer_moves += u64::from(report.layers_moved);
732        true
733    }
734
735    // Adds an interactive target in draw order, ignoring targets that neither
736    // handle a pointer nor name a pointer icon.
737    pub(crate) fn push_hit(
738        &mut self,
739        node_id: NodeId,
740        capture_path: &[NodeId],
741        geometry: HitGeometry<'_>,
742        target: HitTargetSpec<'_>,
743    ) {
744        HitTargets {
745            list: self.hits.get_mut(),
746            diagnostics: &self.diagnostics,
747        }
748        .push(node_id, capture_path, geometry, target);
749    }
750
751    // Removes all hit targets and releases their handlers while retaining
752    // their storage.
753    fn clear_hits(&mut self) {
754        let list = self.hits.get_mut();
755        list.clear();
756        list.stale = false;
757    }
758}
759
760impl Default for Scene {
761    fn default() -> Self {
762        Self::new()
763    }
764}
765
766impl RenderScene for Scene {
767    type HitTarget = HitRegion;
768
769    fn clear(&mut self) {
770        self.store.clear();
771        self.clear_hits();
772    }
773
774    fn trim(&mut self) -> bool {
775        crate::scene_builder::trim_dirty_room();
776        let rebuild = self.store.trim();
777        if rebuild {
778            self.clear();
779            self.store.trim();
780        }
781        rebuild
782    }
783
784    fn hit_test(&self, x: f32, y: f32) -> Vec<Self::HitTarget> {
785        let list = self.fresh_hits();
786        let mut hit_indices: Vec<usize> = list
787            .hits
788            .iter()
789            .enumerate()
790            .filter_map(|(index, hit)| hit.contains(x, y).then_some(index))
791            .collect();
792
793        shared_sort::sort_positions(&mut hit_indices, &mut |a, b| {
794            list.hits[b].z_index.cmp(&list.hits[a].z_index)
795        });
796        hit_indices
797            .into_iter()
798            .map(|index| list.hits[index].clone())
799            .collect()
800    }
801
802    fn hit_test_near(&self, x: f32, y: f32) -> Option<Self::HitTarget> {
803        self.fresh_hits()
804            .hits
805            .iter()
806            .filter_map(|hit| hit.reach_distance(x, y).map(|distance| (distance, hit)))
807            .min_by(|(near, hit), (other_near, other)| {
808                near.total_cmp(other_near)
809                    .then_with(|| other.z_index.cmp(&hit.z_index))
810            })
811            .map(|(_, hit)| hit.clone())
812    }
813
814    fn find_target(&self, node_id: NodeId) -> Option<Self::HitTarget> {
815        let list = self.fresh_hits();
816        list.node_index
817            .get(&node_id)
818            .and_then(|&index| list.hits.get(index))
819            .cloned()
820    }
821
822    fn hit_test_ray(&self, scene: NodeId, ray: Ray) -> Vec<Self::HitTarget> {
823        let list = self.fresh_hits();
824        let mut hit: Vec<&HitRegion> = list
825            .hits
826            .iter()
827            .filter(|hit| {
828                hit.surface.as_ref().is_some_and(|surface| {
829                    surface.target.pick.scene() == Some(scene)
830                        && surface
831                            .local_point_along(ray)
832                            .is_some_and(|local| hit.contains_local(local))
833                })
834            })
835            .collect();
836        shared_sort::sort_by(&mut hit, |a, b| b.z_index.cmp(&a.z_index));
837        hit.into_iter().cloned().collect()
838    }
839
840    fn surface_windows(&self, visit: &mut dyn FnMut(NodeId, ProjectiveTransform)) {
841        let Some(root_layer) = self.store.root_layer() else {
842            return;
843        };
844        let root = ProjectiveTransform::identity();
845        crate::space::for_each_window_eye(root_layer, root, &mut |_, view, to_window| {
846            for seen in &view.surfaces {
847                if let (Some(node_id), Some(content)) = (
848                    seen.layer.node_id(),
849                    view.content_to_window(seen, to_window),
850                ) {
851                    visit(node_id, content);
852                }
853            }
854        });
855    }
856
857    fn surface_window_bounds(&self, node_id: NodeId) -> Option<Rect> {
858        let list = self.fresh_hits();
859        let hit = list.hits.get(*list.node_index.get(&node_id)?)?;
860        let surface = hit.surface.as_ref()?;
861        surface
862            .target
863            .window_bounds(&surface.content_to_local, hit.local_bounds)
864    }
865
866    fn node_window_bounds(&self, visit: &mut dyn FnMut(NodeId, Rect)) {
867        let Some(root) = self.store.root_layer() else {
868            return;
869        };
870        let mut surfaces = HashMap::default();
871        self.surface_windows(&mut |node_id, content| {
872            surfaces.insert(node_id, content);
873        });
874        crate::node_window_bounds::for_each_node_window_bounds(
875            root,
876            ProjectiveTransform::identity(),
877            &surfaces,
878            visit,
879        );
880    }
881
882    fn layer_moves(&self) -> u64 {
883        self.layer_moves
884    }
885
886    fn draws(&self, node: NodeId) -> bool {
887        self.store.record_of(node).is_some()
888    }
889
890    fn drawn_parent(&self, node: NodeId) -> Option<NodeId> {
891        self.store.drawn_parent(node)
892    }
893
894    fn read_left_nodes(&mut self, left: &mut Vec<NodeId>) -> bool {
895        self.left_nodes.read(&self.store, left)
896    }
897}
898
899fn point_in_rounded_rect(point: Point, rect: Rect, shape: RoundedCornerShape) -> bool {
900    if !rect.contains(point.x, point.y) {
901        return false;
902    }
903
904    let local_x = point.x - rect.x;
905    let local_y = point.y - rect.y;
906    let radii = shape.resolve(rect.width, rect.height);
907    let tl = radii.top_left;
908    let tr = radii.top_right;
909    let bl = radii.bottom_left;
910    let br = radii.bottom_right;
911
912    if local_x < tl && local_y < tl {
913        let dx = tl - local_x;
914        let dy = tl - local_y;
915        return dx * dx + dy * dy <= tl * tl;
916    }
917
918    if local_x > rect.width - tr && local_y < tr {
919        let dx = local_x - (rect.width - tr);
920        let dy = tr - local_y;
921        return dx * dx + dy * dy <= tr * tr;
922    }
923
924    if local_x < bl && local_y > rect.height - bl {
925        let dx = bl - local_x;
926        let dy = local_y - (rect.height - bl);
927        return dx * dx + dy * dy <= bl * bl;
928    }
929
930    if local_x > rect.width - br && local_y > rect.height - br {
931        let dx = local_x - (rect.width - br);
932        let dy = local_y - (rect.height - br);
933        return dx * dx + dy * dy <= br * br;
934    }
935
936    true
937}
938
939fn point_in_quad(point: Point, quad: [[f32; 2]; 4]) -> bool {
940    point_in_triangle(point, quad[0], quad[1], quad[3])
941        || point_in_triangle(point, quad[0], quad[3], quad[2])
942}
943
944fn point_in_triangle(point: Point, a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> bool {
945    let d1 = triangle_sign(point, a, b);
946    let d2 = triangle_sign(point, b, c);
947    let d3 = triangle_sign(point, c, a);
948    let has_negative = d1 < -f32::EPSILON || d2 < -f32::EPSILON || d3 < -f32::EPSILON;
949    let has_positive = d1 > f32::EPSILON || d2 > f32::EPSILON || d3 > f32::EPSILON;
950    !(has_negative && has_positive)
951}
952
953fn triangle_sign(point: Point, a: [f32; 2], b: [f32; 2]) -> f32 {
954    (point.x - b[0]) * (a[1] - b[1]) - (a[0] - b[0]) * (point.y - b[1])
955}
956
957#[cfg(test)]
958#[path = "tests/graph_scene_tests.rs"]
959mod tests;