1use std::sync::Arc;
18
19use cranpose_core::NodeId;
20use cranpose_ui_graphics::{
21 Rect, Size,
22 space::{Camera, EyeWorld, LayerSpace, Light, Mat4, MeshSurface, Scene3d, Vec3},
23};
24
25use crate::{graph::ProjectiveTransform, scene_store::LayerRef};
26
27const BACK_THROUGH_DOORWAY: f32 = 1.0e-4;
28
29const SMALLEST_OPENING: f32 = 0.25;
30
31pub const DOORWAY_NEAR: f32 = 1.0 / 1024.0;
36
37pub struct Cell<'a> {
39 pub layer: LayerRef<'a>,
41 pub scene: &'a Scene3d,
43 pub parent: Option<usize>,
45 pub hole: Option<(usize, Rect)>,
49 pub doorway: Mat4,
52 pub to_parent: Mat4,
54}
55
56pub struct Placed<'a> {
58 pub layer: LayerRef<'a>,
60 pub surface: MeshSurface,
62 pub cell: usize,
64 pub content: Rect,
67}
68
69type Host = (usize, ProjectiveTransform);
70
71pub struct SpaceTree<'a> {
74 pub cells: Vec<Cell<'a>>,
76 pub surfaces: Vec<Placed<'a>>,
78}
79
80pub struct EyeView<'a> {
84 pub camera: Camera,
86 pub size: Size,
88 pub cell: usize,
90 pub seen: Vec<SeenSpace>,
93 pub surfaces: Vec<SeenSurface<'a>>,
95}
96
97pub struct SeenSpace {
99 pub cell: usize,
101 pub through: Option<usize>,
104 pub depth: u8,
108 pub to_eye: Mat4,
110 pub light: Option<Light>,
112 pub door: Option<SeenDoor>,
114}
115
116#[derive(Clone, Copy, Debug, PartialEq)]
118pub struct SeenDoor {
119 pub quad: Mat4,
121 pub away: f32,
123 pub clip: [f32; 4],
126 pub opening: Rect,
129}
130
131pub struct SeenSurface<'a> {
133 pub layer: LayerRef<'a>,
135 pub surface: MeshSurface,
137 pub content: Rect,
139 pub seen: usize,
141}
142
143impl<'a> SpaceTree<'a> {
144 pub fn of(scene_layer: LayerRef<'a>) -> Option<Self> {
147 let scene = scene_of(scene_layer)?;
148 let mut tree = Self {
149 cells: Vec::new(),
150 surfaces: Vec::new(),
151 };
152 tree.open(scene_layer, scene, None);
153 Some(tree)
154 }
155
156 pub fn holds_scene(&self, layer: LayerRef<'_>) -> bool {
158 layer.node_id().is_some()
159 && self
160 .cells
161 .iter()
162 .any(|cell| cell.layer.node_id() == layer.node_id())
163 }
164
165 pub fn cell_along(&self, path: &[usize]) -> usize {
168 let mut cell = 0;
169 for &node in path {
170 let next = self.cells.iter().position(|inner| {
171 inner.parent == Some(cell) && inner.layer.node_id() == Some(NodeId(node))
172 });
173 match next {
174 Some(next) => cell = next,
175 None => break,
176 }
177 }
178 cell
179 }
180
181 pub fn to_root(&self, cell: usize) -> Mat4 {
183 let mut transform = Mat4::IDENTITY;
184 let mut at = Some(cell);
185 while let Some(index) = at {
186 let cell = &self.cells[index];
187 transform = transform.then(&cell.to_parent);
188 at = cell.parent;
189 }
190 transform
191 }
192
193 fn open(
194 &mut self,
195 layer: LayerRef<'a>,
196 scene: &'a Scene3d,
197 place: Option<(usize, Mat4, Option<Host>)>,
198 ) {
199 let index = self.cells.len();
200 let cell = match place {
201 None => Cell {
202 layer,
203 scene,
204 parent: None,
205 hole: None,
206 doorway: Mat4::IDENTITY,
207 to_parent: Mat4::IDENTITY,
208 },
209 Some((parent, frame, host)) => {
210 let rect = layer.local_bounds();
211 Cell {
212 layer,
213 scene,
214 parent: Some(parent),
215 hole: host
216 .map(|(surface, to_content)| (surface, to_content.bounds_for_rect(rect))),
217 doorway: Mat4::scaling(Vec3::new(rect.width, rect.height, 1.0))
218 .then(&Mat4::translation(Vec3::new(rect.x, rect.y, 0.0)))
219 .then(&frame),
220 to_parent: scene.camera.doorway(rect).then(&frame),
221 }
222 }
223 };
224 self.cells.push(cell);
225 self.children(layer, &Mat4::IDENTITY, (index, None));
226 }
227
228 fn children(&mut self, layer: LayerRef<'a>, frame: &Mat4, (cell, host): (usize, Option<Host>)) {
229 for child in layer.children() {
230 if !child.has_space() {
231 continue;
232 }
233 let to_parent = child.transform_to_parent();
234 let child_frame = embed(to_parent).then(frame);
235 let child_host =
236 host.map(|(surface, to_content)| (surface, to_parent.then(to_content)));
237 match child.graphics_layer().space.as_deref() {
238 Some(LayerSpace::Scene(scene)) => {
239 self.open(child, scene, Some((cell, child_frame, child_host)));
240 }
241 Some(LayerSpace::Surface(surface)) => {
242 self.surface(child, surface, &child_frame, cell);
243 }
244 Some(LayerSpace::Transform(transform)) => {
245 self.children(child, &transform.then(&child_frame), (cell, None));
246 }
247 None => self.children(child, &child_frame, (cell, child_host)),
248 }
249 }
250 }
251
252 fn surface(&mut self, layer: LayerRef<'a>, surface: &MeshSurface, frame: &Mat4, cell: usize) {
253 let content = layer.local_bounds();
254 let placed = surface.placed_by(frame);
255 let to_scene = placed.content_to_scene(content.size());
256 let index = self.surfaces.len();
257 self.surfaces.push(Placed {
258 layer,
259 surface: placed,
260 cell,
261 content,
262 });
263 if let Some(to_scene) = to_scene {
264 let to_content = ProjectiveTransform::translation(-content.x, -content.y);
267 self.children(
268 layer,
269 &embed(to_content).then(&to_scene),
270 (cell, Some((index, to_content))),
271 );
272 }
273 }
274}
275
276#[derive(Clone, Copy, PartialEq, Eq)]
277enum Through {
278 Inward,
279 Outward,
280}
281
282impl<'a> EyeView<'a> {
283 pub fn of(tree: &SpaceTree<'a>, size: Size) -> Self {
287 let root = tree.cells[0].scene;
288 let cell = root
289 .eye
290 .as_ref()
291 .map_or(0, |eye| tree.cell_along(&eye.doorways));
292 let mut view = Self {
293 camera: root.camera,
294 size,
295 cell,
296 seen: vec![SeenSpace {
297 cell,
298 through: None,
299 depth: 0,
300 to_eye: Mat4::IDENTITY,
301 light: tree.cells[cell].scene.light,
302 door: None,
303 }],
304 surfaces: Vec::new(),
305 };
306 view.look_through(tree, (0, None), Rect::from_size(size));
307 let mut seen_of = vec![None; tree.cells.len()];
308 for (index, seen) in view.seen.iter().enumerate() {
309 seen_of[seen.cell] = Some(index);
310 }
311 for placed in &tree.surfaces {
312 let Some(seen) = seen_of[placed.cell] else {
313 continue;
314 };
315 view.surfaces.push(SeenSurface {
316 layer: placed.layer,
317 surface: placed.surface.placed_by(&view.seen[seen].to_eye),
318 content: placed.content,
319 seen,
320 });
321 }
322 view
323 }
324
325 fn look_through(
326 &mut self,
327 tree: &SpaceTree<'a>,
328 (seen, came_from): (usize, Option<usize>),
329 opening: Rect,
330 ) {
331 let (cell, to_eye) = (self.seen[seen].cell, self.seen[seen].to_eye);
332 for (inner, space) in tree.cells.iter().enumerate() {
333 if space.parent != Some(cell) || Some(inner) == came_from {
334 continue;
335 }
336 let inner_to_eye = space.to_parent.then(&to_eye);
337 let quad = space.doorway.then(&to_eye);
338 self.through(
339 tree,
340 (seen, inner, inner_to_eye),
341 (quad, Through::Inward),
342 opening,
343 );
344 }
345 let space = &tree.cells[cell];
346 if let Some(outer) = space.parent.filter(|outer| Some(*outer) != came_from)
347 && let Some(from_parent) = space.to_parent.inverse()
348 {
349 let outer_to_eye = from_parent.then(&to_eye);
350 let quad = space.doorway.then(&outer_to_eye);
351 self.through(
352 tree,
353 (seen, outer, outer_to_eye),
354 (quad, Through::Outward),
355 opening,
356 );
357 }
358 }
359
360 fn through(
361 &mut self,
362 tree: &SpaceTree<'a>,
363 (seen, cell, to_eye): (usize, usize, Mat4),
364 (quad, through): (Mat4, Through),
365 opening: Rect,
366 ) {
367 let Some(depth) = self.seen[seen].depth.checked_add(1) else {
368 return;
369 };
370 let corner = quad.transform_point(Vec3::ZERO);
371 let Some(normal) = quad.transform_vector(Vec3::new(0.0, 0.0, 1.0)).normalized() else {
372 return;
373 };
374 let side = normal.dot(self.camera.eye() - corner);
375 let (facing, away, clip) = match through {
378 Through::Inward => (side < 0.0, 1.0, plane(normal, corner, 0.0)),
379 Through::Outward => {
380 let margin = BACK_THROUGH_DOORWAY * normal.dot(corner).abs().max(1.0);
381 (side > 0.0, -1.0, plane(-normal, corner, margin))
382 }
383 };
384 let shown = facing
385 .then(|| self.opening(&quad))
386 .flatten()
387 .and_then(|shown| shown.intersect(opening))
388 .filter(|shown| shown.width * shown.height >= SMALLEST_OPENING);
389 let Some(shown) = shown else {
390 return;
391 };
392 let light = tree.cells[cell].scene.light.map(|light| Light {
393 direction: to_eye.transform_vector(light.direction),
394 ..light
395 });
396 self.seen.push(SeenSpace {
397 cell,
398 through: Some(seen),
399 depth,
400 to_eye,
401 light,
402 door: Some(SeenDoor {
403 quad,
404 away,
405 clip,
406 opening: shown,
407 }),
408 });
409 let index = self.seen.len() - 1;
410 self.look_through(tree, (index, Some(self.seen[seen].cell)), shown);
411 }
412
413 fn opening(&self, quad: &Mat4) -> Option<Rect> {
414 let to_camera = quad.then(&self.camera.view);
415 let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
416 .map(|(u, v)| to_camera.transform_point(Vec3::new(u, v, 0.0)));
417 let near = self.camera.near() * DOORWAY_NEAR;
418 let (mut low, mut high) = (
419 (f32::INFINITY, f32::INFINITY),
420 (f32::NEG_INFINITY, f32::NEG_INFINITY),
421 );
422 let mut any = false;
423 let mut show = |point: Vec3| {
424 let scale = self.camera.focal_length / point.z;
425 let (x, y) = (
426 self.size.width * 0.5 + point.x * scale,
427 self.size.height * 0.5 + point.y * scale,
428 );
429 low = (low.0.min(x), low.1.min(y));
430 high = (high.0.max(x), high.1.max(y));
431 any = true;
432 };
433 for (index, &from) in corners.iter().enumerate() {
434 let to = corners[(index + 1) % corners.len()];
435 if from.z >= near {
436 show(from);
437 }
438 if (from.z >= near) != (to.z >= near) {
439 show(from + (to - from) * ((near - from.z) / (to.z - from.z)));
440 }
441 }
442 any.then_some(Rect {
443 x: low.0,
444 y: low.1,
445 width: high.0 - low.0,
446 height: high.1 - low.1,
447 })
448 }
449
450 pub fn build_world(&self, tree: &SpaceTree<'_>, world: &mut EyeWorld) {
454 if let Some(window_scene) = tree.cells[0].layer.node_id() {
455 world.set_window_scene(window_scene.0);
456 }
457 let walked = tree.walked_to(self.cell);
458 let base = world.add_space(Arc::clone(&walked), Mat4::IDENTITY);
459 let mut spaces = vec![(self.cell, base, Mat4::IDENTITY)];
460 let own = &tree.cells[self.cell];
461 if let Some(outer) = own.parent
462 && let Some(from_parent) = own.to_parent.inverse()
463 {
464 let path: Arc<[usize]> = Arc::from(&walked[..walked.len().saturating_sub(1)]);
465 let index = world.add_space(path, from_parent);
466 world.add_doorway((index, base), own.doorway.then(&from_parent));
467 spaces.push((outer, index, from_parent));
468 }
469 for (inner, space) in tree.cells.iter().enumerate() {
470 let (Some(cell), Some(node)) = (space.parent, space.layer.node_id()) else {
471 continue;
472 };
473 if cell != self.cell {
474 continue;
475 }
476 let path: Arc<[usize]> = walked.iter().copied().chain([node.0]).collect();
477 let index = world.add_space(path, space.to_parent);
478 world.add_doorway((base, index), space.doorway);
479 spaces.push((inner, index, space.to_parent));
480 }
481 for (surface_index, placed) in tree.surfaces.iter().enumerate() {
482 let Some(&(_, space, to_base)) =
483 spaces.iter().find(|(cell, _, _)| *cell == placed.cell)
484 else {
485 continue;
486 };
487 if !placed.surface.solid {
488 continue;
489 }
490 let holes = tree.cells.iter().filter_map(|cell| {
491 cell.hole
492 .filter(|(host, _)| *host == surface_index)
493 .map(|(_, rect)| rect)
494 });
495 world.add_solid(
496 (space, Arc::clone(&placed.surface.mesh)),
497 placed.surface.transform.then(&to_base),
498 (placed.content.size(), holes),
499 );
500 }
501 }
502}
503
504impl SpaceTree<'_> {
505 fn walked_to(&self, cell: usize) -> Arc<[usize]> {
506 let mut path = Vec::new();
507 let mut at = cell;
508 while let Some(parent) = self.cells[at].parent {
509 if let Some(node) = self.cells[at].layer.node_id() {
510 path.push(node.0);
511 }
512 at = parent;
513 }
514 path.reverse();
515 Arc::from(path)
516 }
517}
518
519fn plane(normal: Vec3, point: Vec3, margin: f32) -> [f32; 4] {
520 [normal.x, normal.y, normal.z, -normal.dot(point) - margin]
521}
522
523pub fn embed(transform: ProjectiveTransform) -> Mat4 {
526 let [[a, b, c], [d, e, f], [g, h, i]] = transform.matrix();
527 Mat4::from_rows([
528 [a, b, 0.0, c],
529 [d, e, 0.0, f],
530 [0.0, 0.0, 1.0, 0.0],
531 [g, h, 0.0, i],
532 ])
533}
534
535pub fn scene_of(layer: LayerRef<'_>) -> Option<&Scene3d> {
537 match layer.graphics_layer().space.as_deref()? {
538 LayerSpace::Scene(scene) => Some(scene),
539 LayerSpace::Surface(_) | LayerSpace::Transform(_) => None,
540 }
541}
542
543pub fn for_each_window_eye(
548 layer: LayerRef<'_>,
549 to_window: ProjectiveTransform,
550 visit: &mut dyn FnMut(&SpaceTree<'_>, &EyeView<'_>, ProjectiveTransform),
551) {
552 for_each_window_scene(layer, to_window, &mut |scene_layer, to_window| {
553 let Some(tree) = SpaceTree::of(scene_layer) else {
554 return;
555 };
556 let rect = scene_layer.local_bounds();
557 let view = EyeView::of(&tree, rect.size());
558 visit(
559 &tree,
560 &view,
561 ProjectiveTransform::translation(rect.x, rect.y).then(to_window),
562 );
563 });
564}
565
566impl EyeView<'_> {
567 pub fn content_to_window(
571 &self,
572 seen: &SeenSurface<'_>,
573 to_window: ProjectiveTransform,
574 ) -> Option<ProjectiveTransform> {
575 let content = seen.content;
576 seen.surface
577 .content_transform(&self.camera, self.size, content.size())
578 .map(|shown| {
579 ProjectiveTransform::translation(-content.x, -content.y)
580 .then(shown)
581 .then(to_window)
582 })
583 }
584}
585
586pub fn for_each_window_scene<'a>(
590 layer: LayerRef<'a>,
591 to_window: ProjectiveTransform,
592 visit: &mut dyn FnMut(LayerRef<'a>, ProjectiveTransform),
593) {
594 if scene_of(layer).is_some() {
595 visit(layer, to_window);
596 return;
597 }
598 for child in layer.children() {
599 if child.has_space() {
600 for_each_window_scene(child, child.transform_to_parent().then(to_window), visit);
601 }
602 }
603}