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
151impl<'a> SpaceTree<'a> {
152 pub fn of(scene_layer: LayerRef<'a>) -> Option<Self> {
155 let scene = scene_of(scene_layer)?;
156 let mut tree = Self {
157 cells: Vec::new(),
158 surfaces: Vec::new(),
159 };
160 tree.open(scene_layer, scene, None);
161 Some(tree)
162 }
163
164 pub fn holds_scene(&self, layer: LayerRef<'_>) -> bool {
166 layer.node_id().is_some()
167 && self
168 .cells
169 .iter()
170 .any(|cell| cell.layer.node_id() == layer.node_id())
171 }
172
173 pub fn cell_along(&self, path: &[usize]) -> usize {
176 let mut cell = 0;
177 for &node in path {
178 let next = self.cells.iter().position(|inner| {
179 inner.parent == Some(cell) && inner.layer.node_id() == Some(NodeId(node))
180 });
181 match next {
182 Some(next) => cell = next,
183 None => break,
184 }
185 }
186 cell
187 }
188
189 pub fn to_root(&self, cell: usize) -> Mat4 {
191 let mut transform = Mat4::IDENTITY;
192 let mut at = Some(cell);
193 while let Some(index) = at {
194 let cell = &self.cells[index];
195 transform = transform.then(&cell.to_parent);
196 at = cell.parent;
197 }
198 transform
199 }
200
201 fn open(
202 &mut self,
203 layer: LayerRef<'a>,
204 scene: &'a Scene3d,
205 place: Option<(usize, Mat4, Option<Host>)>,
206 ) {
207 let index = self.cells.len();
208 let cell = match place {
209 None => Cell {
210 layer,
211 scene,
212 parent: None,
213 hole: None,
214 doorway: Mat4::IDENTITY,
215 to_parent: Mat4::IDENTITY,
216 },
217 Some((parent, frame, host)) => {
218 let rect = layer.local_bounds();
219 Cell {
220 layer,
221 scene,
222 parent: Some(parent),
223 hole: host
224 .map(|(surface, to_content)| (surface, to_content.bounds_for_rect(rect))),
225 doorway: Mat4::scaling(Vec3::new(rect.width, rect.height, 1.0))
226 .then(&Mat4::translation(Vec3::new(rect.x, rect.y, 0.0)))
227 .then(&frame),
228 to_parent: scene.camera.doorway(rect).then(&frame),
229 }
230 }
231 };
232 self.cells.push(cell);
233 self.children(layer, &Mat4::IDENTITY, (index, None));
234 }
235
236 fn children(&mut self, layer: LayerRef<'a>, frame: &Mat4, (cell, host): (usize, Option<Host>)) {
237 for child in layer.children() {
238 if !child.has_space() {
239 continue;
240 }
241 let to_parent = child.transform_to_parent();
242 let child_frame = embed(to_parent).then(frame);
243 let child_host =
244 host.map(|(surface, to_content)| (surface, to_parent.then(to_content)));
245 match child.graphics_layer().space.as_deref() {
246 Some(LayerSpace::Scene(scene)) => {
247 self.open(child, scene, Some((cell, child_frame, child_host)));
248 }
249 Some(LayerSpace::Surface(surfaces)) => {
250 self.surface(child, surfaces, &child_frame, cell);
251 }
252 Some(LayerSpace::Transform(transform)) => {
253 self.children(child, &transform.then(&child_frame), (cell, None));
254 }
255 None => self.children(child, &child_frame, (cell, child_host)),
256 }
257 }
258 }
259
260 fn surface(&mut self, layer: LayerRef<'a>, surfaces: &MeshSurfaces, frame: &Mat4, cell: usize) {
261 let content = layer.local_bounds();
262 let index = self.surfaces.len();
263 for (mesh, surface) in surfaces.iter().enumerate() {
264 self.surfaces.push(Placed {
265 layer,
266 surface: surface.placed_by(frame),
267 mesh,
268 cell,
269 content,
270 });
271 }
272 if let Some(to_scene) = self.surfaces[index]
273 .surface
274 .content_to_scene(content.size())
275 {
276 let to_content = ProjectiveTransform::translation(-content.x, -content.y);
279 self.children(
280 layer,
281 &embed(to_content).then(&to_scene),
282 (cell, Some((index, to_content))),
283 );
284 }
285 }
286}
287
288#[derive(Clone, Copy, PartialEq, Eq)]
289enum Through {
290 Inward,
291 Outward,
292}
293
294impl<'a> EyeView<'a> {
295 pub fn of(tree: &SpaceTree<'a>, size: Size) -> Self {
299 let root = tree.cells[0].scene;
300 let cell = root
301 .eye
302 .as_ref()
303 .map_or(0, |eye| tree.cell_along(&eye.doorways));
304 let mut view = Self {
305 camera: root.camera,
306 size,
307 cell,
308 seen: vec![SeenSpace {
309 cell,
310 through: None,
311 depth: 0,
312 to_eye: Mat4::IDENTITY,
313 light: tree.cells[cell].scene.light,
314 door: None,
315 }],
316 surfaces: Vec::new(),
317 };
318 view.look_through(tree, (0, None), Rect::from_size(size));
319 let mut seen_of = vec![None; tree.cells.len()];
320 for (index, seen) in view.seen.iter().enumerate() {
321 seen_of[seen.cell] = Some(index);
322 }
323 for placed in &tree.surfaces {
324 let Some(seen) = seen_of[placed.cell] else {
325 continue;
326 };
327 view.surfaces.push(SeenSurface {
328 layer: placed.layer,
329 surface: placed.surface.placed_by(&view.seen[seen].to_eye),
330 mesh: placed.mesh,
331 content: placed.content,
332 seen,
333 });
334 }
335 view
336 }
337
338 fn look_through(
339 &mut self,
340 tree: &SpaceTree<'a>,
341 (seen, came_from): (usize, Option<usize>),
342 opening: Rect,
343 ) {
344 let (cell, to_eye) = (self.seen[seen].cell, self.seen[seen].to_eye);
345 for (inner, space) in tree.cells.iter().enumerate() {
346 if space.parent != Some(cell) || Some(inner) == came_from {
347 continue;
348 }
349 let inner_to_eye = space.to_parent.then(&to_eye);
350 let quad = space.doorway.then(&to_eye);
351 self.through(
352 tree,
353 (seen, inner, inner_to_eye),
354 (quad, Through::Inward),
355 opening,
356 );
357 }
358 let space = &tree.cells[cell];
359 if let Some(outer) = space.parent.filter(|outer| Some(*outer) != came_from)
360 && let Some(from_parent) = space.to_parent.inverse()
361 {
362 let outer_to_eye = from_parent.then(&to_eye);
363 let quad = space.doorway.then(&outer_to_eye);
364 self.through(
365 tree,
366 (seen, outer, outer_to_eye),
367 (quad, Through::Outward),
368 opening,
369 );
370 }
371 }
372
373 fn through(
374 &mut self,
375 tree: &SpaceTree<'a>,
376 (seen, cell, to_eye): (usize, usize, Mat4),
377 (quad, through): (Mat4, Through),
378 opening: Rect,
379 ) {
380 let Some(depth) = self.seen[seen].depth.checked_add(1) else {
381 return;
382 };
383 let corner = quad.transform_point(Vec3::ZERO);
384 let Some(normal) = quad.transform_vector(Vec3::new(0.0, 0.0, 1.0)).normalized() else {
385 return;
386 };
387 let side = normal.dot(self.camera.eye() - corner);
388 let (facing, away, clip) = match through {
391 Through::Inward => (side < 0.0, 1.0, plane(normal, corner, 0.0)),
392 Through::Outward => {
393 let margin = BACK_THROUGH_DOORWAY * normal.dot(corner).abs().max(1.0);
394 (side > 0.0, -1.0, plane(-normal, corner, margin))
395 }
396 };
397 let shown = facing
398 .then(|| self.opening(&quad))
399 .flatten()
400 .and_then(|shown| shown.intersect(opening))
401 .filter(|shown| shown.width * shown.height >= SMALLEST_OPENING);
402 let Some(shown) = shown else {
403 return;
404 };
405 let light = tree.cells[cell].scene.light.map(|light| Light {
406 direction: to_eye.transform_vector(light.direction),
407 ..light
408 });
409 self.seen.push(SeenSpace {
410 cell,
411 through: Some(seen),
412 depth,
413 to_eye,
414 light,
415 door: Some(SeenDoor {
416 quad,
417 away,
418 clip,
419 opening: shown,
420 }),
421 });
422 let index = self.seen.len() - 1;
423 self.look_through(tree, (index, Some(self.seen[seen].cell)), shown);
424 }
425
426 fn opening(&self, quad: &Mat4) -> Option<Rect> {
427 let to_camera = quad.then(&self.camera.view);
428 let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
429 .map(|(u, v)| to_camera.transform_point(Vec3::new(u, v, 0.0)));
430 let near = self.camera.near() * DOORWAY_NEAR;
431 let (mut low, mut high) = (
432 (f32::INFINITY, f32::INFINITY),
433 (f32::NEG_INFINITY, f32::NEG_INFINITY),
434 );
435 let mut any = false;
436 let mut show = |point: Vec3| {
437 let scale = self.camera.focal_length / point.z;
438 let (x, y) = (
439 self.size.width * 0.5 + point.x * scale,
440 self.size.height * 0.5 + point.y * scale,
441 );
442 low = (low.0.min(x), low.1.min(y));
443 high = (high.0.max(x), high.1.max(y));
444 any = true;
445 };
446 for (index, &from) in corners.iter().enumerate() {
447 let to = corners[(index + 1) % corners.len()];
448 if from.z >= near {
449 show(from);
450 }
451 if (from.z >= near) != (to.z >= near) {
452 show(from + (to - from) * ((near - from.z) / (to.z - from.z)));
453 }
454 }
455 any.then_some(Rect {
456 x: low.0,
457 y: low.1,
458 width: high.0 - low.0,
459 height: high.1 - low.1,
460 })
461 }
462
463 pub fn build_world(&self, tree: &SpaceTree<'_>, world: &mut EyeWorld) {
467 if let Some(window_scene) = tree.cells[0].layer.node_id() {
468 world.set_window_scene(window_scene.0);
469 }
470 let walked = tree.walked_to(self.cell);
471 let base = world.add_space(Arc::clone(&walked), Mat4::IDENTITY);
472 let mut spaces = vec![(self.cell, base, Mat4::IDENTITY)];
473 let own = &tree.cells[self.cell];
474 if let Some(outer) = own.parent
475 && let Some(from_parent) = own.to_parent.inverse()
476 {
477 let path: Arc<[usize]> = Arc::from(&walked[..walked.len().saturating_sub(1)]);
478 let index = world.add_space(path, from_parent);
479 world.add_doorway((index, base), own.doorway.then(&from_parent));
480 spaces.push((outer, index, from_parent));
481 }
482 for (inner, space) in tree.cells.iter().enumerate() {
483 let (Some(cell), Some(node)) = (space.parent, space.layer.node_id()) else {
484 continue;
485 };
486 if cell != self.cell {
487 continue;
488 }
489 let path: Arc<[usize]> = walked.iter().copied().chain([node.0]).collect();
490 let index = world.add_space(path, space.to_parent);
491 world.add_doorway((base, index), space.doorway);
492 spaces.push((inner, index, space.to_parent));
493 }
494 for (surface_index, placed) in tree.surfaces.iter().enumerate() {
495 let Some(&(_, space, to_base)) =
496 spaces.iter().find(|(cell, _, _)| *cell == placed.cell)
497 else {
498 continue;
499 };
500 if !placed.surface.solid {
501 continue;
502 }
503 let holes = tree.cells.iter().filter_map(|cell| {
504 cell.hole
505 .filter(|(host, _)| *host == surface_index)
506 .map(|(_, rect)| rect)
507 });
508 world.add_solid(
509 (space, Arc::clone(&placed.surface.mesh)),
510 placed.surface.transform.then(&to_base),
511 (placed.content.size(), holes),
512 );
513 }
514 }
515}
516
517impl SpaceTree<'_> {
518 fn walked_to(&self, cell: usize) -> Arc<[usize]> {
519 let mut path = Vec::new();
520 let mut at = cell;
521 while let Some(parent) = self.cells[at].parent {
522 if let Some(node) = self.cells[at].layer.node_id() {
523 path.push(node.0);
524 }
525 at = parent;
526 }
527 path.reverse();
528 Arc::from(path)
529 }
530}
531
532fn plane(normal: Vec3, point: Vec3, margin: f32) -> [f32; 4] {
533 [normal.x, normal.y, normal.z, -normal.dot(point) - margin]
534}
535
536pub fn embed(transform: ProjectiveTransform) -> Mat4 {
539 let [[a, b, c], [d, e, f], [g, h, i]] = transform.matrix();
540 Mat4::from_rows([
541 [a, b, 0.0, c],
542 [d, e, 0.0, f],
543 [0.0, 0.0, 1.0, 0.0],
544 [g, h, 0.0, i],
545 ])
546}
547
548pub fn scene_of(layer: LayerRef<'_>) -> Option<&Scene3d> {
550 match layer.graphics_layer().space.as_deref()? {
551 LayerSpace::Scene(scene) => Some(scene),
552 LayerSpace::Surface(_) | LayerSpace::Transform(_) => None,
553 }
554}
555
556pub fn for_each_window_eye(
561 layer: LayerRef<'_>,
562 to_window: ProjectiveTransform,
563 visit: &mut dyn FnMut(&SpaceTree<'_>, &EyeView<'_>, ProjectiveTransform),
564) {
565 for_each_window_scene(layer, to_window, &mut |scene_layer, to_window| {
566 let Some(tree) = SpaceTree::of(scene_layer) else {
567 return;
568 };
569 let rect = scene_layer.local_bounds();
570 let view = EyeView::of(&tree, rect.size());
571 visit(
572 &tree,
573 &view,
574 ProjectiveTransform::translation(rect.x, rect.y).then(to_window),
575 );
576 });
577}
578
579impl EyeView<'_> {
580 pub fn content_to_window(
584 &self,
585 seen: &SeenSurface<'_>,
586 to_window: ProjectiveTransform,
587 ) -> Option<ProjectiveTransform> {
588 let content = seen.content;
589 seen.surface
590 .content_transform(&self.camera, self.size, content.size())
591 .map(|shown| {
592 ProjectiveTransform::translation(-content.x, -content.y)
593 .then(shown)
594 .then(to_window)
595 })
596 }
597}
598
599pub fn for_each_window_scene<'a>(
603 layer: LayerRef<'a>,
604 to_window: ProjectiveTransform,
605 visit: &mut dyn FnMut(LayerRef<'a>, ProjectiveTransform),
606) {
607 if scene_of(layer).is_some() {
608 visit(layer, to_window);
609 return;
610 }
611 for child in layer.children() {
612 if child.has_space() {
613 for_each_window_scene(child, child.transform_to_parent().then(to_window), visit);
614 }
615 }
616}