1use std::sync::Arc;
18
19use cranpose_core::NodeId;
20use cranpose_ui_graphics::{
21 Rect, Size,
22 space::{Camera, EyeWorld, LayerSpace, Light, Mat4, MeshSurface, MeshSurfaces, 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)>,
50 pub doorway: Mat4,
53 pub to_parent: Mat4,
55}
56
57pub struct Placed<'a> {
59 pub layer: LayerRef<'a>,
61 pub surface: MeshSurface,
63 pub mesh: usize,
66 pub cell: usize,
68 pub content: Rect,
71}
72
73type Host = (usize, ProjectiveTransform);
74
75pub struct SpaceTree<'a> {
78 pub cells: Vec<Cell<'a>>,
80 pub surfaces: Vec<Placed<'a>>,
83}
84
85pub struct EyeView<'a> {
89 pub camera: Camera,
91 pub size: Size,
93 pub cell: usize,
95 pub seen: Vec<SeenSpace>,
98 pub surfaces: Vec<SeenSurface<'a>>,
101}
102
103pub struct SeenSpace {
105 pub cell: usize,
107 pub through: Option<usize>,
110 pub depth: u8,
114 pub to_eye: Mat4,
116 pub light: Option<Light>,
118 pub door: Option<SeenDoor>,
120}
121
122#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct SeenDoor {
125 pub quad: Mat4,
127 pub away: f32,
129 pub clip: [f32; 4],
132 pub opening: Rect,
135}
136
137pub struct SeenSurface<'a> {
139 pub layer: LayerRef<'a>,
141 pub surface: MeshSurface,
143 pub mesh: usize,
145 pub content: Rect,
147 pub seen: usize,
149}
150
151trait Walker<'a> {
154 fn open(
158 &mut self,
159 layer: LayerRef<'a>,
160 scene: &'a Scene3d,
161 place: Option<(usize, Mat4, Option<Host>)>,
162 ) -> Option<usize>;
163
164 fn surface(
167 &mut self,
168 layer: LayerRef<'a>,
169 surfaces: &MeshSurfaces,
170 frame: &Mat4,
171 cell: usize,
172 ) -> (usize, Option<Mat4>);
173}
174
175fn walk<'a>(
177 walker: &mut impl Walker<'a>,
178 layer: LayerRef<'a>,
179 frame: &Mat4,
180 (cell, host): (usize, Option<Host>),
181) {
182 for child in layer.children() {
183 if !child.has_space() {
184 continue;
185 }
186 let to_parent = child.transform_to_parent();
187 let child_frame = embed(to_parent).then(frame);
188 let child_host = host.map(|(surface, to_content)| (surface, to_parent.then(to_content)));
189 match child.graphics_layer().space.as_deref() {
190 Some(LayerSpace::Scene(scene)) => {
191 let place = Some((cell, child_frame, child_host));
192 if let Some(inner) = walker.open(child, scene, place) {
193 walk(walker, child, &Mat4::IDENTITY, (inner, None));
194 }
195 }
196 Some(LayerSpace::Surface(surfaces)) => {
197 let content = child.local_bounds();
198 let (index, to_scene) = walker.surface(child, surfaces, &child_frame, cell);
199 if let Some(to_scene) = to_scene {
200 let to_content = ProjectiveTransform::translation(-content.x, -content.y);
203 walk(
204 walker,
205 child,
206 &embed(to_content).then(&to_scene),
207 (cell, Some((index, to_content))),
208 );
209 }
210 }
211 Some(LayerSpace::Transform(transform)) => {
212 walk(walker, child, &transform.then(&child_frame), (cell, None));
213 }
214 None => walk(walker, child, &child_frame, (cell, child_host)),
215 }
216 }
217}
218
219impl<'a> Walker<'a> for SpaceTree<'a> {
220 fn open(
221 &mut self,
222 layer: LayerRef<'a>,
223 scene: &'a Scene3d,
224 place: Option<(usize, Mat4, Option<Host>)>,
225 ) -> Option<usize> {
226 let index = self.cells.len();
227 let cell = match place {
228 None => Cell {
229 layer,
230 scene,
231 parent: None,
232 hole: None,
233 doorway: Mat4::IDENTITY,
234 to_parent: Mat4::IDENTITY,
235 },
236 Some((parent, frame, host)) => {
237 let rect = layer.local_bounds();
238 Cell {
239 layer,
240 scene,
241 parent: Some(parent),
242 hole: host
243 .map(|(surface, to_content)| (surface, to_content.bounds_for_rect(rect))),
244 doorway: Mat4::scaling(Vec3::new(rect.width, rect.height, 1.0))
245 .then(&Mat4::translation(Vec3::new(rect.x, rect.y, 0.0)))
246 .then(&frame),
247 to_parent: scene.camera.doorway(rect).then(&frame),
248 }
249 }
250 };
251 self.cells.push(cell);
252 Some(index)
253 }
254
255 fn surface(
256 &mut self,
257 layer: LayerRef<'a>,
258 surfaces: &MeshSurfaces,
259 frame: &Mat4,
260 cell: usize,
261 ) -> (usize, Option<Mat4>) {
262 let content = layer.local_bounds();
263 let index = self.surfaces.len();
264 for (mesh, surface) in surfaces.iter().enumerate() {
265 self.surfaces.push(Placed {
266 layer,
267 surface: surface.placed_by(frame),
268 mesh,
269 cell,
270 content,
271 });
272 }
273 let to_scene = self.surfaces[index]
274 .surface
275 .content_to_scene(content.size());
276 (index, to_scene)
277 }
278}
279
280impl<'a> SpaceTree<'a> {
281 pub fn of(scene_layer: LayerRef<'a>) -> Option<Self> {
284 let scene = scene_of(scene_layer)?;
285 let mut tree = Self {
286 cells: Vec::new(),
287 surfaces: Vec::new(),
288 };
289 let index = tree.open(scene_layer, scene, None)?;
290 walk(&mut tree, scene_layer, &Mat4::IDENTITY, (index, None));
291 Some(tree)
292 }
293
294 pub fn holds_scene(&self, layer: LayerRef<'_>) -> bool {
296 layer.node_id().is_some()
297 && self
298 .cells
299 .iter()
300 .any(|cell| cell.layer.node_id() == layer.node_id())
301 }
302
303 pub fn cell_along(&self, path: &[usize]) -> usize {
306 let mut cell = 0;
307 for &node in path {
308 let next = self.cells.iter().position(|inner| {
309 inner.parent == Some(cell) && inner.layer.node_id() == Some(NodeId(node))
310 });
311 match next {
312 Some(next) => cell = next,
313 None => break,
314 }
315 }
316 cell
317 }
318
319 pub fn to_root(&self, cell: usize) -> Mat4 {
321 let mut transform = Mat4::IDENTITY;
322 let mut at = Some(cell);
323 while let Some(index) = at {
324 let cell = &self.cells[index];
325 transform = transform.then(&cell.to_parent);
326 at = cell.parent;
327 }
328 transform
329 }
330}
331
332pub struct MeshVisit<'v> {
334 pub node: Option<NodeId>,
336 pub mesh: usize,
338 pub surface: &'v MeshSurface,
340 pub to_frame: Mat4,
343}
344
345struct Meshes<'f> {
347 visit: &'f mut dyn FnMut(&MeshVisit<'_>),
348}
349
350impl<'a> Walker<'a> for Meshes<'_> {
351 fn open(
352 &mut self,
353 _layer: LayerRef<'a>,
354 _scene: &'a Scene3d,
355 _place: Option<(usize, Mat4, Option<Host>)>,
356 ) -> Option<usize> {
357 None
358 }
359
360 fn surface(
361 &mut self,
362 layer: LayerRef<'a>,
363 surfaces: &MeshSurfaces,
364 frame: &Mat4,
365 _cell: usize,
366 ) -> (usize, Option<Mat4>) {
367 for (mesh, surface) in surfaces.iter().enumerate() {
368 (self.visit)(&MeshVisit {
369 node: layer.node_id(),
370 mesh,
371 surface,
372 to_frame: surface.transform.then(frame),
373 });
374 }
375 let to_scene = surfaces
376 .owner()
377 .placed_by(frame)
378 .content_to_scene(layer.local_bounds().size());
379 (0, to_scene)
380 }
381}
382
383pub fn visit_meshes(layer: LayerRef<'_>, visit: &mut dyn FnMut(&MeshVisit<'_>)) {
387 walk(&mut Meshes { visit }, layer, &Mat4::IDENTITY, (0, None));
388}
389
390pub fn layer_of_node(layer: LayerRef<'_>, node: NodeId) -> Option<LayerRef<'_>> {
392 if layer.node_id() == Some(node) {
393 return Some(layer);
394 }
395 layer
396 .children()
397 .find_map(|child| layer_of_node(child, node))
398}
399
400#[derive(Clone, Copy, PartialEq, Eq)]
401enum Through {
402 Inward,
403 Outward,
404}
405
406impl<'a> EyeView<'a> {
407 pub fn of(tree: &SpaceTree<'a>, size: Size) -> Self {
411 let root = tree.cells[0].scene;
412 let cell = root
413 .eye
414 .as_ref()
415 .map_or(0, |eye| tree.cell_along(&eye.doorways));
416 let mut view = Self {
417 camera: root.camera,
418 size,
419 cell,
420 seen: vec![SeenSpace {
421 cell,
422 through: None,
423 depth: 0,
424 to_eye: Mat4::IDENTITY,
425 light: tree.cells[cell].scene.light,
426 door: None,
427 }],
428 surfaces: Vec::new(),
429 };
430 view.look_through(tree, (0, None), Rect::from_size(size));
431 let mut seen_of = vec![None; tree.cells.len()];
432 for (index, seen) in view.seen.iter().enumerate() {
433 seen_of[seen.cell] = Some(index);
434 }
435 for placed in &tree.surfaces {
436 let Some(seen) = seen_of[placed.cell] else {
437 continue;
438 };
439 view.surfaces.push(SeenSurface {
440 layer: placed.layer,
441 surface: placed.surface.placed_by(&view.seen[seen].to_eye),
442 mesh: placed.mesh,
443 content: placed.content,
444 seen,
445 });
446 }
447 view
448 }
449
450 fn look_through(
451 &mut self,
452 tree: &SpaceTree<'a>,
453 (seen, came_from): (usize, Option<usize>),
454 opening: Rect,
455 ) {
456 let (cell, to_eye) = (self.seen[seen].cell, self.seen[seen].to_eye);
457 for (inner, space) in tree.cells.iter().enumerate() {
458 if space.parent != Some(cell) || Some(inner) == came_from {
459 continue;
460 }
461 let inner_to_eye = space.to_parent.then(&to_eye);
462 let quad = space.doorway.then(&to_eye);
463 self.through(
464 tree,
465 (seen, inner, inner_to_eye),
466 (quad, Through::Inward),
467 opening,
468 );
469 }
470 let space = &tree.cells[cell];
471 if let Some(outer) = space.parent.filter(|outer| Some(*outer) != came_from)
472 && let Some(from_parent) = space.to_parent.inverse()
473 {
474 let outer_to_eye = from_parent.then(&to_eye);
475 let quad = space.doorway.then(&outer_to_eye);
476 self.through(
477 tree,
478 (seen, outer, outer_to_eye),
479 (quad, Through::Outward),
480 opening,
481 );
482 }
483 }
484
485 fn through(
486 &mut self,
487 tree: &SpaceTree<'a>,
488 (seen, cell, to_eye): (usize, usize, Mat4),
489 (quad, through): (Mat4, Through),
490 opening: Rect,
491 ) {
492 let Some(depth) = self.seen[seen].depth.checked_add(1) else {
493 return;
494 };
495 let corner = quad.transform_point(Vec3::ZERO);
496 let Some(normal) = quad.transform_vector(Vec3::new(0.0, 0.0, 1.0)).normalized() else {
497 return;
498 };
499 let side = normal.dot(self.camera.eye() - corner);
500 let (facing, away, clip) = match through {
503 Through::Inward => (side < 0.0, 1.0, plane(normal, corner, 0.0)),
504 Through::Outward => {
505 let margin = BACK_THROUGH_DOORWAY * normal.dot(corner).abs().max(1.0);
506 (side > 0.0, -1.0, plane(-normal, corner, margin))
507 }
508 };
509 let shown = facing
510 .then(|| self.opening(&quad))
511 .flatten()
512 .and_then(|shown| shown.intersect(opening))
513 .filter(|shown| shown.width * shown.height >= SMALLEST_OPENING);
514 let Some(shown) = shown else {
515 return;
516 };
517 let light = tree.cells[cell].scene.light.map(|light| Light {
518 direction: to_eye.transform_vector(light.direction),
519 ..light
520 });
521 self.seen.push(SeenSpace {
522 cell,
523 through: Some(seen),
524 depth,
525 to_eye,
526 light,
527 door: Some(SeenDoor {
528 quad,
529 away,
530 clip,
531 opening: shown,
532 }),
533 });
534 let index = self.seen.len() - 1;
535 self.look_through(tree, (index, Some(self.seen[seen].cell)), shown);
536 }
537
538 fn opening(&self, quad: &Mat4) -> Option<Rect> {
539 let to_camera = quad.then(&self.camera.view);
540 let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
541 .map(|(u, v)| to_camera.transform_point(Vec3::new(u, v, 0.0)));
542 let near = self.camera.near() * DOORWAY_NEAR;
543 let (mut low, mut high) = (
544 (f32::INFINITY, f32::INFINITY),
545 (f32::NEG_INFINITY, f32::NEG_INFINITY),
546 );
547 let mut any = false;
548 let mut show = |point: Vec3| {
549 let scale = self.camera.focal_length / point.z;
550 let (x, y) = (
551 self.size.width * 0.5 + point.x * scale,
552 self.size.height * 0.5 + point.y * scale,
553 );
554 low = (low.0.min(x), low.1.min(y));
555 high = (high.0.max(x), high.1.max(y));
556 any = true;
557 };
558 for (index, &from) in corners.iter().enumerate() {
559 let to = corners[(index + 1) % corners.len()];
560 if from.z >= near {
561 show(from);
562 }
563 if (from.z >= near) != (to.z >= near) {
564 show(from + (to - from) * ((near - from.z) / (to.z - from.z)));
565 }
566 }
567 any.then_some(Rect {
568 x: low.0,
569 y: low.1,
570 width: high.0 - low.0,
571 height: high.1 - low.1,
572 })
573 }
574
575 pub fn build_world(&self, tree: &SpaceTree<'_>, world: &mut EyeWorld) {
579 if let Some(window_scene) = tree.cells[0].layer.node_id() {
580 world.set_window_scene(window_scene.0);
581 }
582 let walked = tree.walked_to(self.cell);
583 let base = world.add_space(Arc::clone(&walked), Mat4::IDENTITY);
584 let mut spaces = vec![(self.cell, base, Mat4::IDENTITY)];
585 let own = &tree.cells[self.cell];
586 if let Some(outer) = own.parent
587 && let Some(from_parent) = own.to_parent.inverse()
588 {
589 let path: Arc<[usize]> = Arc::from(&walked[..walked.len().saturating_sub(1)]);
590 let index = world.add_space(path, from_parent);
591 world.add_doorway((index, base), own.doorway.then(&from_parent));
592 spaces.push((outer, index, from_parent));
593 }
594 for (inner, space) in tree.cells.iter().enumerate() {
595 let (Some(cell), Some(node)) = (space.parent, space.layer.node_id()) else {
596 continue;
597 };
598 if cell != self.cell {
599 continue;
600 }
601 let path: Arc<[usize]> = walked.iter().copied().chain([node.0]).collect();
602 let index = world.add_space(path, space.to_parent);
603 world.add_doorway((base, index), space.doorway);
604 spaces.push((inner, index, space.to_parent));
605 }
606 for (surface_index, placed) in tree.surfaces.iter().enumerate() {
607 let Some(&(_, space, to_base)) =
608 spaces.iter().find(|(cell, _, _)| *cell == placed.cell)
609 else {
610 continue;
611 };
612 if !placed.surface.solid {
613 continue;
614 }
615 let holes = tree.cells.iter().filter_map(|cell| {
616 cell.hole
617 .filter(|(host, _)| *host == surface_index)
618 .map(|(_, rect)| rect)
619 });
620 world.add_solid(
621 (space, Arc::clone(&placed.surface.mesh)),
622 placed.surface.transform.then(&to_base),
623 (placed.content.size(), holes),
624 );
625 }
626 }
627}
628
629impl SpaceTree<'_> {
630 fn walked_to(&self, cell: usize) -> Arc<[usize]> {
631 let mut path = Vec::new();
632 let mut at = cell;
633 while let Some(parent) = self.cells[at].parent {
634 if let Some(node) = self.cells[at].layer.node_id() {
635 path.push(node.0);
636 }
637 at = parent;
638 }
639 path.reverse();
640 Arc::from(path)
641 }
642}
643
644fn plane(normal: Vec3, point: Vec3, margin: f32) -> [f32; 4] {
645 [normal.x, normal.y, normal.z, -normal.dot(point) - margin]
646}
647
648pub fn embed(transform: ProjectiveTransform) -> Mat4 {
651 let [[a, b, c], [d, e, f], [g, h, i]] = transform.matrix();
652 Mat4::from_rows([
653 [a, b, 0.0, c],
654 [d, e, 0.0, f],
655 [0.0, 0.0, 1.0, 0.0],
656 [g, h, 0.0, i],
657 ])
658}
659
660pub fn scene_of(layer: LayerRef<'_>) -> Option<&Scene3d> {
662 match layer.graphics_layer().space.as_deref()? {
663 LayerSpace::Scene(scene) => Some(scene),
664 LayerSpace::Surface(_) | LayerSpace::Transform(_) => None,
665 }
666}
667
668pub fn for_each_window_eye(
673 layer: LayerRef<'_>,
674 to_window: ProjectiveTransform,
675 visit: &mut dyn FnMut(&SpaceTree<'_>, &EyeView<'_>, ProjectiveTransform),
676) {
677 for_each_window_scene(layer, to_window, &mut |scene_layer, to_window| {
678 let Some(tree) = SpaceTree::of(scene_layer) else {
679 return;
680 };
681 let rect = scene_layer.local_bounds();
682 let view = EyeView::of(&tree, rect.size());
683 visit(
684 &tree,
685 &view,
686 ProjectiveTransform::translation(rect.x, rect.y).then(to_window),
687 );
688 });
689}
690
691impl EyeView<'_> {
692 pub fn content_to_window(
696 &self,
697 seen: &SeenSurface<'_>,
698 to_window: ProjectiveTransform,
699 ) -> Option<ProjectiveTransform> {
700 let content = seen.content;
701 seen.surface
702 .content_transform(&self.camera, self.size, content.size())
703 .map(|shown| {
704 ProjectiveTransform::translation(-content.x, -content.y)
705 .then(shown)
706 .then(to_window)
707 })
708 }
709}
710
711pub fn for_each_window_scene<'a>(
715 layer: LayerRef<'a>,
716 to_window: ProjectiveTransform,
717 visit: &mut dyn FnMut(LayerRef<'a>, ProjectiveTransform),
718) {
719 if scene_of(layer).is_some() {
720 visit(layer, to_window);
721 return;
722 }
723 for child in layer.children() {
724 if child.has_space() {
725 for_each_window_scene(child, child.transform_to_parent().then(to_window), visit);
726 }
727 }
728}