Skip to main content

cranpose_render_common/
scene_pick.rs

1use std::cell::Cell;
2
3use cranpose_core::NodeId;
4use cranpose_ui_graphics::{
5    Point, Rect, Size,
6    space::{Camera, Mat4, MeshSurface, Ray, SurfaceHit, Vec3},
7};
8
9use crate::{
10    graph::ProjectiveTransform,
11    scene_store::LayerRef,
12    space::{EyeView, SpaceTree},
13};
14
15const PAST_DOORWAY: f32 = 1.0e-4;
16
17/// Finds which mesh surface of a scene a window point, or any ray, shows,
18/// and the point of the surface's content there: the nearest surface along
19/// the ray in the space the window's eye stands in, or behind a doorway the
20/// ray meets first, in the spaces the eye sees.
21pub struct ScenePick {
22    scene: Option<NodeId>,
23    camera: Camera,
24    size: Size,
25    window_to_scene: ProjectiveTransform,
26    scene_to_window: ProjectiveTransform,
27    surfaces: Vec<PickSurface>,
28    seen: Vec<PickSpace>,
29    scenes: Vec<NodeId>,
30    seen_scenes: Vec<NodeId>,
31    last: Cell<Option<LastPick>>,
32}
33
34struct PickSpace {
35    through: Option<usize>,
36    to_door: Mat4,
37}
38
39impl PickSpace {
40    fn meet(&self, ray: Ray) -> Option<f32> {
41        let origin = self.to_door.transform_point(ray.origin);
42        let direction = self.to_door.transform_vector(ray.direction);
43        if direction.z.abs() < f32::EPSILON {
44            return None;
45        }
46        let distance = -origin.z / direction.z;
47        let at = origin + direction * distance;
48        let inside = (0.0..=1.0).contains(&at.x) && (0.0..=1.0).contains(&at.y);
49        (inside && distance > 0.0).then_some(distance)
50    }
51}
52
53type LastPick = (Point, Option<(usize, SurfaceHit)>);
54
55struct PickSurface {
56    node_id: Option<NodeId>,
57    surface: MeshSurface,
58    // The rect of its content in its layer, which the mesh's texture
59    // spans. The pick's content points lie in the layer.
60    content: Rect,
61    seen: usize,
62    held: Cell<Option<u32>>,
63}
64
65impl PickSurface {
66    // The content point `point`, from the corner of the texture, in the
67    // surface's layer.
68    fn in_layer(&self, point: Point) -> Point {
69        Point::new(point.x + self.content.x, point.y + self.content.y)
70    }
71
72    // Where `ray` meets the surface, its content point in the layer.
73    fn cast(&self, ray: Ray) -> Option<SurfaceHit> {
74        let mut hit = self.surface.cast(ray, self.content.size())?;
75        hit.point = self.in_layer(hit.point);
76        Some(hit)
77    }
78}
79
80impl ScenePick {
81    /// The pick of the scene that `layer` shows, with `to_window` mapping
82    /// the layer to the window; `None` when the layer shows no scene. Its
83    /// surfaces are those the window's eye sees.
84    pub fn of(layer: LayerRef<'_>, to_window: ProjectiveTransform) -> Option<Self> {
85        // A hit walk asks every layer: one that opens no scene stops here,
86        // before any transform work.
87        let tree = SpaceTree::of(layer)?;
88        // The scene fills its layer's bounds.
89        let bounds = layer.local_bounds();
90        let to_window = ProjectiveTransform::translation(bounds.x, bounds.y).then(to_window);
91        let window_to_scene = to_window.inverse()?;
92        let view = EyeView::of(&tree, bounds.size());
93        let seen_scenes = view
94            .seen
95            .iter()
96            .filter_map(|seen| tree.cells[seen.cell].layer.node_id())
97            .collect();
98        let seen = view
99            .seen
100            .iter()
101            .map(|space| PickSpace {
102                through: space.through,
103                to_door: space
104                    .door
105                    .and_then(|door| door.quad.inverse())
106                    .unwrap_or(Mat4::IDENTITY),
107            })
108            .collect();
109        let surfaces = view
110            .surfaces
111            .into_iter()
112            .map(|seen| PickSurface {
113                node_id: seen.layer.node_id(),
114                surface: seen.surface,
115                content: seen.content,
116                seen: seen.seen,
117                held: Cell::new(None),
118            })
119            .collect();
120        Some(Self {
121            scene: layer.node_id(),
122            camera: view.camera,
123            size: view.size,
124            window_to_scene,
125            scene_to_window: to_window,
126            surfaces,
127            seen,
128            scenes: tree
129                .cells
130                .iter()
131                .filter_map(|cell| cell.layer.node_id())
132                .collect(),
133            seen_scenes,
134            last: Cell::new(None),
135        })
136    }
137
138    /// The node of the scene the window shows.
139    pub fn scene(&self) -> Option<NodeId> {
140        self.scene
141    }
142
143    /// Whether `layer` shows one of this scene's spaces, a scene behind one
144    /// of its doorways, whose surfaces this pick finds.
145    pub fn holds_scene(&self, layer: LayerRef<'_>) -> bool {
146        layer
147            .node_id()
148            .is_some_and(|node_id| self.scenes.contains(&node_id))
149    }
150
151    /// Whether the eye sees the space of the scene `layer` shows, through
152    /// the doorways before it.
153    pub fn sees_scene(&self, layer: LayerRef<'_>) -> bool {
154        layer
155            .node_id()
156            .is_some_and(|node_id| self.seen_scenes.contains(&node_id))
157    }
158
159    /// The index among the scene's surfaces of the surface layer `layer`.
160    pub fn index_of(&self, layer: LayerRef<'_>) -> Option<usize> {
161        let node_id = layer.node_id()?;
162        self.surfaces
163            .iter()
164            .position(|surface| surface.node_id == Some(node_id))
165    }
166
167    /// The content point of surface `index` that the window point shows,
168    /// when that surface is the nearest one there.
169    pub fn content_point(&self, window: Point, index: usize) -> Option<Point> {
170        let (nearest, hit) = self.nearest(window)?;
171        (nearest == index).then_some(hit.point)
172    }
173
174    /// The surface `ray`, in the space the window's eye stands in, meets
175    /// first, by its index, and where.
176    pub fn nearest_along(&self, ray: Ray) -> Option<(usize, SurfaceHit)> {
177        self.nearest_in(ray, 0, f32::NEG_INFINITY)
178    }
179
180    /// The content point of surface `index` under the window point for a
181    /// gesture that surface holds: where the ray meets it, or past its edge,
182    /// where the ray meets the plane of the triangle it last met.
183    pub fn drag_point(&self, window: Point, index: usize) -> Option<Point> {
184        self.drag_point_along(self.ray(window)?, index)
185    }
186
187    /// [`Self::drag_point`] for a ray in the space the window's eye stands
188    /// in.
189    pub fn drag_point_along(&self, ray: Ray, index: usize) -> Option<Point> {
190        let target = self.surfaces.get(index)?;
191        if let Some(hit) = target.cast(ray) {
192            target.held.set(Some(hit.triangle));
193            return Some(hit.point);
194        }
195        target
196            .surface
197            .cast_plane(ray, target.held.get()?, target.content.size())
198            .map(|point| target.in_layer(point))
199    }
200
201    /// Where the content point `content` of surface `index` shows in the
202    /// window, also for a surface behind a doorway; `None` when it lies
203    /// nearer than the camera's near plane or behind the eye.
204    pub fn window_point(&self, index: usize, content: Point) -> Option<Point> {
205        let target = self.surfaces.get(index)?;
206        let from_corner = Point::new(content.x - target.content.x, content.y - target.content.y);
207        let at = target
208            .surface
209            .point_at(from_corner, target.content.size())?;
210        let shown = self.camera.project(at, self.size)?;
211        Some(self.scene_to_window.map_point(shown))
212    }
213
214    /// Where `point`, in the space the window's eye stands in, shows in the
215    /// window; `None` behind the eye.
216    pub fn window_point_of(&self, point: Vec3) -> Option<Point> {
217        let shown = self.camera.project(point, self.size)?;
218        Some(self.scene_to_window.map_point(shown))
219    }
220
221    fn ray(&self, window: Point) -> Option<Ray> {
222        let local = self.window_to_scene.map_point(window);
223        self.camera.ray(local, self.size)
224    }
225
226    fn nearest(&self, window: Point) -> Option<(usize, SurfaceHit)> {
227        if let Some((point, nearest)) = self.last.get()
228            && point == window
229        {
230            return nearest;
231        }
232        let nearest = self.ray(window).and_then(|ray| self.nearest_along(ray));
233        if let Some((index, hit)) = nearest {
234            self.surfaces[index].held.set(Some(hit.triangle));
235        }
236        self.last.set(Some((window, nearest)));
237        nearest
238    }
239
240    fn nearest_in(&self, ray: Ray, seen: usize, beyond: f32) -> Option<(usize, SurfaceHit)> {
241        let surface = self
242            .surfaces
243            .iter()
244            .enumerate()
245            .filter(|(_, target)| target.seen == seen)
246            .filter_map(|(index, target)| {
247                target
248                    .cast(ray)
249                    .filter(|hit| hit.distance > beyond)
250                    .map(|hit| (index, hit))
251            })
252            .min_by(|(_, a), (_, b)| a.distance.total_cmp(&b.distance));
253        let doorway = self
254            .seen
255            .iter()
256            .enumerate()
257            .filter(|(_, space)| space.through == Some(seen))
258            .filter_map(|(index, space)| {
259                space
260                    .meet(ray)
261                    .filter(|distance| *distance > beyond)
262                    .map(|distance| (index, distance))
263            })
264            .min_by(|(_, a), (_, b)| a.total_cmp(b));
265        let Some((door, distance)) = doorway.filter(|(_, distance)| {
266            surface.is_none_or(|(_, hit)| *distance <= hit.distance * (1.0 + PAST_DOORWAY))
267        }) else {
268            return surface;
269        };
270        self.nearest_in(ray, door, distance * (1.0 + PAST_DOORWAY))
271            .or(surface)
272    }
273}