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
24pub struct RenderDiagnostics {
26 reported_warnings: RefCell<HashSet<&'static str>>,
27 live_modifier_slice_lookup_miss_count: Cell<usize>,
28}
29
30impl RenderDiagnostics {
31 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 pub fn claim_warning_once(&self, key: &'static str) -> bool {
41 self.reported_warnings.borrow_mut().insert(key)
42 }
43
44 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 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#[derive(Clone, Copy, Debug, PartialEq)]
69pub struct HitClip {
70 pub quad: [[f32; 2]; 4],
72 pub bounds: Rect,
74}
75
76pub struct SurfaceTarget {
79 pub pick: Rc<ScenePick>,
81 pub index: usize,
83 pub outer_clip_bounds: Option<Rect>,
85 pub outer_clips: Vec<HitClip>,
87}
88
89const WINDOW_BOUNDS_STEPS: u16 = 2;
90
91impl SurfaceTarget {
92 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#[derive(Clone, Copy)]
125pub struct SurfaceGeometry<'a> {
126 pub target: &'a Rc<SurfaceTarget>,
128 pub content_to_local: ProjectiveTransform,
130 pub clip_bounds: Option<Rect>,
133 pub clips: &'a [HitClip],
135}
136
137impl SurfaceGeometry<'_> {
138 pub fn window_bounds(&self, local: Rect) -> Option<Rect> {
140 self.target.window_bounds(&self.content_to_local, local)
141 }
142}
143
144#[derive(Clone, Copy)]
146pub struct HitGeometry<'a> {
147 pub rect: Rect,
149 pub quad: [[f32; 2]; 4],
151 pub local_bounds: Rect,
153 pub world_to_local: ProjectiveTransform,
155 pub hit_clip_bounds: Option<Rect>,
157 pub hit_clips: &'a [HitClip],
159 pub surface: Option<SurfaceGeometry<'a>>,
163}
164
165pub struct HitTargetSpec<'a> {
169 pub shape: Option<RoundedCornerShape>,
172 pub handlers: &'a Rc<ModifierNodeSlices>,
174}
175
176#[derive(Clone)]
178pub struct HitRegion {
179 pub node_id: NodeId,
181 pub capture_path: Vec<NodeId>,
184 pub rect: Rect,
186 pub quad: [[f32; 2]; 4],
188 pub local_bounds: Rect,
190 pub world_to_local: ProjectiveTransform,
192 pub shape: Option<RoundedCornerShape>,
194 pub handlers: Rc<ModifierNodeSlices>,
197 pub z_index: usize,
199 pub hit_clip_bounds: Option<Rect>,
201 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#[derive(Default)]
503struct HitList {
504 hits: Vec<HitRegion>,
505 buffers: Vec<HitBuffers>,
506 next_z: usize,
508 node_index: HashMap<NodeId, usize>,
510 stale: bool,
513}
514
515impl HitList {
516 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
571pub struct Scene {
573 store: SceneStore,
574 hits: RefCell<HitList>,
578 diagnostics: Rc<RenderDiagnostics>,
579 layer_moves: u64,
582 left_nodes: LeftNodes,
583}
584
585#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
588pub struct HitStorage {
589 pub hits_len: usize,
591 pub hits_capacity: usize,
593 pub node_index_len: usize,
595 pub node_index_capacity: usize,
597}
598
599impl Scene {
600 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 pub fn diagnostics(&self) -> &RenderDiagnostics {
615 self.diagnostics.as_ref()
616 }
617
618 pub fn store(&self) -> &SceneStore {
620 &self.store
621 }
622
623 pub fn follow(&mut self, events: RecordEvents) {
627 self.store.follow(events | RecordEvents::LEAVES);
628 }
629
630 #[cfg(feature = "window-damage")]
633 pub fn refresh_reach(&mut self) {
634 self.store.refresh_reach();
635 }
636
637 pub fn root_layer(&self) -> Option<LayerRef<'_>> {
639 self.store.root_layer()
640 }
641
642 #[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 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 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 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 pub fn hit_targets(&self) -> Vec<HitRegion> {
695 self.fresh_hits().hits.clone()
696 }
697
698 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 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 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 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;