Skip to main content

cranpose_ui_graphics/space/
scene.rs

1use std::sync::Arc;
2
3use super::{
4    eye::EyePlace,
5    math::{Mat4, Vec3},
6    mesh::{Mesh, MeshHit},
7};
8use crate::{Color, Point, Rect, Size, transform::ProjectiveTransform};
9
10/// How much nearer than its focal length a camera sees: points closer to the
11/// eye than `focal_length * NEAR_PLANE` are cut away. It is the w at which
12/// [`ProjectiveTransform::front_polygon`] cuts a perspective map.
13pub const NEAR_PLANE: f32 = crate::transform::NEAR_W;
14
15/// A pinhole camera that shows a 3D scene in a composable's bounds.
16///
17/// The camera looks along its own z axis with its x to the right and y down.
18/// A point at `(x, y, z)` in the camera's frame shows at
19/// `center + (x, y) * focal_length / z`, where `center` is the middle of the
20/// bounds.
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub struct Camera {
23    /// Maps scene space into the camera's frame.
24    pub view: Mat4,
25    /// The distance from the eye to the image, in logical pixels: the
26    /// distance at which one scene unit shows as one pixel.
27    pub focal_length: f32,
28}
29
30impl Camera {
31    /// A camera at `eye` that looks at `target`. `down` is the scene
32    /// direction that shows as down; it need not be square to the view.
33    pub fn look_at(eye: Vec3, target: Vec3, down: Vec3, focal_length: f32) -> Self {
34        let forward = (target - eye)
35            .normalized()
36            .unwrap_or(Vec3::new(0.0, 0.0, 1.0));
37        let right = down
38            .cross(forward)
39            .normalized()
40            .unwrap_or(Vec3::new(1.0, 0.0, 0.0));
41        let down = forward.cross(right);
42        let row = |axis: Vec3| [axis.x, axis.y, axis.z, -axis.dot(eye)];
43        Self {
44            view: Mat4::from_rows([row(right), row(down), row(forward), [0.0, 0.0, 0.0, 1.0]]),
45            focal_length,
46        }
47    }
48
49    /// The focal length that shows `vertical_fov` radians across `height`
50    /// pixels.
51    pub fn focal_length_for(height: f32, vertical_fov: f32) -> f32 {
52        height * 0.5 / (vertical_fov * 0.5).tan()
53    }
54
55    /// The eye's position in scene space.
56    pub fn eye(&self) -> Vec3 {
57        self.view
58            .inverse()
59            .map_or(Vec3::ZERO, |inverse| inverse.transform_point(Vec3::ZERO))
60    }
61
62    /// The camera-frame depth below which the camera sees nothing.
63    pub fn near(&self) -> f32 {
64        self.focal_length * NEAR_PLANE
65    }
66
67    /// Where `point` shows in bounds of `size`; `None` when it lies nearer
68    /// than [`Self::near`] or behind the eye.
69    pub fn project(&self, point: Vec3, size: Size) -> Option<Point> {
70        let seen = self.view.transform_point(point);
71        (seen.z >= self.near()).then(|| {
72            let scale = self.focal_length / seen.z;
73            Point::new(
74                size.width * 0.5 + seen.x * scale,
75                size.height * 0.5 + seen.y * scale,
76            )
77        })
78    }
79
80    /// The map from the scene this camera sees into the frame in which
81    /// `window`, a rect on the frame's plane, is a doorway into the scene:
82    /// the camera stands in the doorway's middle, looking along the frame's
83    /// z, with its x and y along the frame's, a scene unit to a frame unit.
84    /// What the camera sees lies behind the doorway.
85    pub fn doorway(&self, window: Rect) -> Mat4 {
86        self.view.then(&Mat4::translation(Vec3::new(
87            window.x + window.width * 0.5,
88            window.y + window.height * 0.5,
89            0.0,
90        )))
91    }
92
93    /// The ray from the eye through `point` of bounds of `size`, in scene
94    /// space, with a direction that reaches depth one in the camera's frame
95    /// at distance one.
96    pub fn ray(&self, point: Point, size: Size) -> Option<Ray> {
97        let inverse = self.view.inverse()?;
98        let through = Vec3::new(
99            (point.x - size.width * 0.5) / self.focal_length,
100            (point.y - size.height * 0.5) / self.focal_length,
101            1.0,
102        );
103        Some(Ray {
104            origin: inverse.transform_point(Vec3::ZERO),
105            direction: inverse.transform_vector(through),
106        })
107    }
108}
109
110/// A half line in scene space.
111#[derive(Clone, Copy, Debug, PartialEq)]
112pub struct Ray {
113    /// Where the ray starts.
114    pub origin: Vec3,
115    /// Which way the ray goes; distances along the ray count in its length.
116    pub direction: Vec3,
117}
118
119/// A light from one direction, with an even part that reaches every side.
120#[derive(Clone, Copy, Debug, PartialEq)]
121pub struct Light {
122    /// The direction the light travels, in scene space.
123    pub direction: Vec3,
124    /// How bright a surface the light does not reach is, from 0 to 1: the
125    /// side of a lit surface turned away from the light, and any surface in
126    /// shadow.
127    pub ambient: f32,
128    /// Whether the surfaces that cast shadows cast them on the scene's
129    /// surfaces.
130    pub shadows: bool,
131    /// The angle the light spans as the scene sees it, in radians: 0 for a
132    /// point far away, whose shadows have hard edges. A light of some size
133    /// casts shadows that are sharp where a caster meets a surface and soft
134    /// farther from it, as the sun's 0.0093 does and a wide lamp's more.
135    pub size: f32,
136}
137
138impl Light {
139    /// How bright a surface is, from `ambient` to 1, where its side that
140    /// faces the viewer has `normal`: the light reaches only a side that
141    /// faces it.
142    pub fn brightness(&self, normal: Vec3) -> f32 {
143        let facing = match (self.direction.normalized(), normal.normalized()) {
144            (Some(direction), Some(normal)) => (-normal.dot(direction)).max(0.0),
145            _ => 0.0,
146        };
147        self.ambient + (1.0 - self.ambient) * facing
148    }
149
150    /// The map from scene space to a shadow map of this light that holds
151    /// `casters`: x and y from -1 to 1 across the map, and depth from 0 at
152    /// the caster nearest the light to 1 at the farthest. A point farther
153    /// along the light than a caster's depth there lies in its shadow.
154    /// `None` without casters, or for a light with no direction.
155    pub fn shadow_projection<'a>(
156        &self,
157        casters: impl IntoIterator<Item = &'a MeshSurface>,
158    ) -> Option<Mat4> {
159        const MARGIN: f32 = 0.02;
160        let forward = self.direction.normalized()?;
161        let hint = if forward.y.abs() < 0.9 {
162            Vec3::new(0.0, 1.0, 0.0)
163        } else {
164            Vec3::new(1.0, 0.0, 0.0)
165        };
166        let right = hint.cross(forward).normalized()?;
167        let up = forward.cross(right);
168        let view = Mat4::from_rows([
169            [right.x, right.y, right.z, 0.0],
170            [up.x, up.y, up.z, 0.0],
171            [forward.x, forward.y, forward.z, 0.0],
172            [0.0, 0.0, 0.0, 1.0],
173        ]);
174        let mut low = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
175        let mut high = -low;
176        for caster in casters {
177            let (caster_low, caster_high) = caster.mesh.bounds_in(&caster.transform.then(&view));
178            (low, high) = (low.min(caster_low), high.max(caster_high));
179        }
180        let extent = high - low;
181        if !(extent.x.is_finite() && extent.y.is_finite() && extent.z.is_finite()) {
182            return None;
183        }
184        let pad = |extent: f32| (extent * MARGIN).max(1.0);
185        let (low, high) = (
186            low - Vec3::new(pad(extent.x), pad(extent.y), pad(extent.z)),
187            high + Vec3::new(pad(extent.x), pad(extent.y), pad(extent.z)),
188        );
189        let extent = high - low;
190        let fit = Mat4::from_rows([
191            [2.0 / extent.x, 0.0, 0.0, -1.0 - 2.0 * low.x / extent.x],
192            [0.0, 2.0 / extent.y, 0.0, -1.0 - 2.0 * low.y / extent.y],
193            [0.0, 0.0, 1.0 / extent.z, -low.z / extent.z],
194            [0.0, 0.0, 0.0, 1.0],
195        ]);
196        Some(view.then(&fit))
197    }
198}
199
200/// A scene's camera and light, which a `scene3d` modifier shows its
201/// children's mesh surfaces through.
202///
203/// A scene inside another scene's space is a doorway into a space of its
204/// own: the rect its layer covers in its frame opens onto that space, which
205/// lies behind it, placed so the doorway stands where the inner scene's
206/// camera stands (see [`Camera::doorway`]). The window's eye sees through
207/// doorways from the space it stands in, as deep as they show on screen,
208/// and walks through them (see [`EyePlace`]).
209#[derive(Clone, Debug, PartialEq)]
210pub struct Scene3d {
211    /// The camera the scene is seen through. For a scene behind a doorway,
212    /// the one that stands in the doorway; for the window's scene with an
213    /// [`eye`](Self::eye), the eye's, in the space the eye stands in.
214    pub camera: Camera,
215    /// The light on the scene's lit surfaces, or `None` for none.
216    pub light: Option<Light>,
217    /// For the window's scene, where its eye stands among the spaces behind
218    /// the scene's doorways and where the renderer leaves what the eye can
219    /// bump into; `None` for a camera in the scene's own space that walks
220    /// through nothing. A scene behind a doorway leaves it out.
221    pub eye: Option<EyePlace>,
222    /// How many samples the scene's pass takes in each pixel. A scene behind
223    /// a doorway draws in the pass of the window's scene, whose value counts
224    /// for both.
225    pub multisample: Multisample,
226}
227
228impl Scene3d {
229    /// A scene seen through `camera`, with no light, no eye and one sample
230    /// in each pixel.
231    pub fn new(camera: Camera) -> Self {
232        Self {
233            camera,
234            light: None,
235            eye: None,
236            multisample: Multisample::Off,
237        }
238    }
239}
240
241/// How many samples a scene's pass takes in each pixel.
242///
243/// With one sample, each pixel shows the surface its middle falls on, so the
244/// edge of a curved mesh, such as a sphere's or a tube's, steps from pixel to
245/// pixel. With four, the GPU tests coverage and depth at four points in each
246/// pixel and averages the colours they find, so the outline of a mesh and
247/// the line where two surfaces cut through each other show smooth. A
248/// surface's colour is still found once in each pixel: multisampling smooths
249/// the edges of meshes, not the edges of shapes a [`Volume`]'s shader finds
250/// or of transparent parts of a surface's content. A sheet, a mesh whose
251/// outline is its texture's edge, fades over that outline with either count.
252///
253/// A scene with four samples draws into targets of its own, four samples
254/// deep and as large as the scene, then averages them into the page: more
255/// GPU memory and time, which a scene left [`Off`](Self::Off) does not pay.
256/// The GPU renderer takes four samples on every backend, as every GPU format
257/// it draws scenes in supports them. The CPU renderer draws every scene with
258/// one sample.
259#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
260pub enum Multisample {
261    /// One sample in each pixel.
262    #[default]
263    Off,
264    /// Four samples in each pixel.
265    X4,
266}
267
268impl Multisample {
269    /// The samples taken in each pixel.
270    pub const fn samples(self) -> u32 {
271        match self {
272            Self::Off => 1,
273            Self::X4 => 4,
274        }
275    }
276}
277
278/// A composable's content drawn on a mesh placed in a scene.
279#[derive(Clone, Debug, PartialEq)]
280pub struct MeshSurface {
281    /// The mesh the content is drawn on.
282    pub mesh: Arc<Mesh>,
283    /// Places the mesh in the scene.
284    pub transform: Mat4,
285    /// How the content meets the scene's light and what lies behind it.
286    pub material: Material,
287    /// Whether the surface casts a shadow from the scene's light. Every lit
288    /// and unlit surface takes the shadows that fall on it.
289    pub casts_shadow: bool,
290    /// Whether an eye that walks into the surface (see
291    /// [`EyeWorld::walk`](super::EyeWorld::walk)) stops there. A doorway in
292    /// the surface's content lets it through.
293    pub solid: bool,
294}
295
296/// How a surface's content meets the scene's light and what lies behind
297/// it.
298#[derive(Clone, Debug, PartialEq)]
299pub enum Material {
300    /// Shaded by the angle the light falls at, and darkened where a shadow
301    /// falls on it.
302    Lit,
303    /// The content as it is, as a screen shows it, darkened only where a
304    /// shadow falls on it.
305    Unlit,
306    /// The content at its full colour, as fire or a lamp shows: neither the
307    /// light nor a shadow changes it.
308    Emissive,
309    /// Adds the content's colour to what lies behind it, as light does: a
310    /// halo, a flame or a spark. It hides nothing, and surfaces nearer the
311    /// eye hide it.
312    Glow,
313    /// The scene behind shows through, bent by the surface's curve, with the
314    /// light's highlight on it and the content drawn over it. Glass shows
315    /// the surfaces that are not glass behind it.
316    Glass(Glass),
317    /// A shape an app's shader finds inside the mesh, ray by ray, as the
318    /// camera sees it, with the depth of what each ray meets: the mesh only
319    /// bounds it. A volume casts no shadow.
320    Volume(Volume),
321    /// Coloured by an app's shader from the content, the light and the eye
322    /// at each point of the surface: a reflection, a sheen, a normal of its
323    /// own. Until the shader builds, and if it never does, the surface is
324    /// [`Lit`](Self::Lit).
325    Shaded(Shaded),
326}
327
328/// An app's shader that colours a surface: each pixel the mesh covers asks
329/// it for its colour from the content there, the light and the eye.
330///
331/// `shader` is WGSL that defines
332///
333/// ```text
334/// fn shade(surface: ShadedSurface) -> vec4<f32>
335/// ```
336///
337/// and returns the colour, premultiplied. `ShadedSurface` holds, in the
338/// mesh's own coordinates: `color`, the content's colour there,
339/// premultiplied; `uv`, where the point lies in the content, from `(0, 0)`
340/// at its top left corner to `(1, 1)` at its bottom right, at which
341/// `content_color(uv)` reads the content anywhere; `position`; `eye`;
342/// `normal`, of length one, on the side
343/// the eye sees; `to_eye` and `to_light`, of length one, toward the eye
344/// and toward the light, which is zero without a light; `lit`, how much of
345/// the light reaches the point, from 0 in full shadow to 1; and `ambient`,
346/// the light's ambient share, 1 without a light. `shaded_param(index)`
347/// reads `params[index]`. The renderer puts
348/// [`MESH_SHADED_PRELUDE_WGSL`](crate::framework_shaders::MESH_SHADED_PRELUDE_WGSL),
349/// which declares them, before it.
350#[derive(Clone, Debug)]
351pub struct Shaded {
352    /// The app's WGSL. Keep one `Arc` per shader: the renderer builds a
353    /// pipeline for each.
354    pub shader: Arc<str>,
355    /// The values the shader reads.
356    pub params: [f32; Self::PARAMS],
357}
358
359impl Shaded {
360    /// How many values a surface's shader reads.
361    pub const PARAMS: usize = 32;
362}
363
364impl PartialEq for Shaded {
365    fn eq(&self, other: &Self) -> bool {
366        Arc::ptr_eq(&self.shader, &other.shader) && self.params == other.params
367    }
368}
369
370/// An app's shader that draws inside a mesh: each pixel the mesh covers
371/// asks it what the camera's ray through the pixel meets.
372///
373/// `shader` is WGSL that defines
374///
375/// ```text
376/// fn volume(eye: vec3<f32>, direction: vec3<f32>, entry: f32, exit: f32, footprint: f32) -> VolumeHit
377/// ```
378///
379/// in the mesh's own coordinates: the eye; the ray's direction, of length
380/// one; how far along the ray it enters the mesh's bounds, zero for an eye
381/// inside them, and leaves the mesh; and how wide a pixel is, in radians.
382/// It returns a `VolumeHit`: the colour, premultiplied, nothing at an alpha
383/// of zero; and the point the ray met, which sets the pixel's depth.
384/// `volume_param(index)` reads `params[index]`, `volume_content(uv)` the
385/// surface's content and `volume_light()` the scene's light, in the mesh's
386/// coordinates. The renderer puts
387/// [`MESH_VOLUME_PRELUDE_WGSL`](crate::framework_shaders::MESH_VOLUME_PRELUDE_WGSL),
388/// which declares them, before it. The mesh's normals must point out of it.
389#[derive(Clone, Debug)]
390pub struct Volume {
391    /// The app's WGSL. Keep one `Arc` per shader: the renderer builds a
392    /// pipeline for each.
393    pub shader: Arc<str>,
394    /// The values the shader reads.
395    pub params: [f32; Self::PARAMS],
396}
397
398impl Volume {
399    /// How many values a volume's shader reads.
400    pub const PARAMS: usize = 32;
401}
402
403impl PartialEq for Volume {
404    fn eq(&self, other: &Self) -> bool {
405        Arc::ptr_eq(&self.shader, &other.shader) && self.params == other.params
406    }
407}
408
409/// How glass bends and tints the scene behind it.
410#[derive(Clone, Copy, Debug, PartialEq)]
411pub struct Glass {
412    /// The refractive index: 1 bends nothing, window glass is 1.5 and
413    /// diamond 2.4.
414    pub index: f32,
415    /// How far a ray travels inside the glass, in scene units: a ball's
416    /// diameter for a solid ball. A ray bends entering the glass and again
417    /// leaving it, as through a solid ball, so a thick ball shows the scene
418    /// behind it upside down.
419    pub thickness: f32,
420    /// The colour the glass tints what shows through it; white for clear
421    /// glass.
422    pub tint: Color,
423}
424
425impl Glass {
426    /// Clear window glass a ray crosses for `thickness` scene units.
427    pub const fn clear(thickness: f32) -> Self {
428        Self {
429            index: 1.5,
430            thickness,
431            tint: Color(1.0, 1.0, 1.0, 1.0),
432        }
433    }
434}
435
436impl MeshSurface {
437    /// The content of a composable of `size` on the mesh: the content point
438    /// where the ray meets the mesh, the triangle it meets, and how far along
439    /// the ray.
440    pub fn cast(&self, ray: Ray, size: Size) -> Option<SurfaceHit> {
441        let inverse = self.transform.inverse()?;
442        let hit = self.mesh.cast(
443            inverse.transform_point(ray.origin),
444            inverse.transform_vector(ray.direction),
445        )?;
446        Some(SurfaceHit::of(hit, size))
447    }
448
449    /// The content point of a composable of `size` where the ray meets the
450    /// plane of `triangle`: a drag that leaves the mesh's edge goes on along
451    /// it.
452    pub fn cast_plane(&self, ray: Ray, triangle: u32, size: Size) -> Option<Point> {
453        let inverse = self.transform.inverse()?;
454        let uv = self.mesh.cast_plane(
455            inverse.transform_point(ray.origin),
456            inverse.transform_vector(ray.direction),
457            triangle,
458        )?;
459        Some(content_point(uv, size))
460    }
461
462    /// The projective map that carries the content of a composable of
463    /// `size` from the mesh to the bounds of `viewport` that `camera` shows.
464    /// It is exact for a flat mesh; for a curved one it follows the plane
465    /// that touches the mesh at the content's middle. It sends the part
466    /// nearer than the camera's near plane to w below [`NEAR_PLANE`], which
467    /// [`ProjectiveTransform::front_polygon`] cuts away. `None` for content
468    /// of no size, or for a mesh with no texture plane.
469    pub fn content_transform(
470        &self,
471        camera: &Camera,
472        viewport: Size,
473        size: Size,
474    ) -> Option<ProjectiveTransform> {
475        if !(size.width > 0.0 && size.height > 0.0) {
476            return None;
477        }
478        let plane = self.mesh.texture_plane()?;
479        let to_camera = self.transform.then(&camera.view);
480        let origin = to_camera.transform_point(plane.origin);
481        let right = to_camera.transform_vector(plane.u_axis) * (1.0 / size.width);
482        let down = to_camera.transform_vector(plane.v_axis) * (1.0 / size.height);
483        let (center_x, center_y) = (viewport.width * 0.5, viewport.height * 0.5);
484        let focal_length = camera.focal_length;
485        let column = |v: Vec3| {
486            [
487                v.x + center_x * v.z / focal_length,
488                v.y + center_y * v.z / focal_length,
489                v.z / focal_length,
490            ]
491        };
492        let [a, b, c] = [column(right), column(down), column(origin)];
493        Some(ProjectiveTransform::from_rows([
494            [a[0], b[0], c[0]],
495            [a[1], b[1], c[1]],
496            [a[2], b[2], c[2]],
497        ]))
498    }
499
500    /// The map from the content space of a composable of `size` on the mesh
501    /// into the scene: x and y in the content's pixels from its top left, z
502    /// into the surface, away from the side it shows its content to, a unit
503    /// as long as a content pixel. A mesh surface inside this content is
504    /// placed in that space. It is exact for a flat mesh; for a curved one it
505    /// follows the plane that touches the mesh at the content's middle.
506    /// `None` for content of no size, or for a mesh with no texture plane.
507    pub fn content_to_scene(&self, size: Size) -> Option<Mat4> {
508        if !(size.width > 0.0 && size.height > 0.0) {
509            return None;
510        }
511        let plane = self.mesh.texture_plane()?;
512        let right = self.transform.transform_vector(plane.u_axis) * (1.0 / size.width);
513        let down = self.transform.transform_vector(plane.v_axis) * (1.0 / size.height);
514        let into = right.cross(down).normalized()? * (right.length() * down.length()).sqrt();
515        Some(Mat4::from_axes(
516            right,
517            down,
518            into,
519            self.transform.transform_point(plane.origin),
520        ))
521    }
522
523    /// This surface with its transform followed by `to_scene`: a surface
524    /// inside another's content, placed in the scene through the other's
525    /// [`content_to_scene`](Self::content_to_scene). Glass keeps its
526    /// thickness in the units of the space it is placed from.
527    pub fn placed_by(&self, to_scene: &Mat4) -> Self {
528        let material = match &self.material {
529            Material::Glass(glass) => Material::Glass(Glass {
530                thickness: glass.thickness * to_scene.length_scale(),
531                ..*glass
532            }),
533            material => material.clone(),
534        };
535        Self {
536            mesh: Arc::clone(&self.mesh),
537            transform: self.transform.then(to_scene),
538            material,
539            casts_shadow: self.casts_shadow,
540            solid: self.solid,
541        }
542    }
543
544    /// Where the content point `point` of a composable of `size` lies in the
545    /// scene.
546    pub fn point_at(&self, point: Point, size: Size) -> Option<Vec3> {
547        let uv = [
548            point.x / size.width.max(f32::MIN_POSITIVE),
549            point.y / size.height.max(f32::MIN_POSITIVE),
550        ];
551        self.mesh
552            .point_at(uv)
553            .map(|position| self.transform.transform_point(position))
554    }
555}
556
557/// The meshes one composable's content is drawn on: one or more, each
558/// placed in the scene on its own, all showing the same live content.
559///
560/// The content is rendered once and every mesh shows it. A pointer takes
561/// the nearest of the meshes where it points and reaches the content point
562/// that mesh shows there; a drag stays on the mesh it started on. The first
563/// mesh, the owner, places the layer for everything that needs one place:
564/// the 3D frames of the layer's children, the doorways in its content, and
565/// the bounds the window and accessibility services report for the content.
566#[derive(Clone, Debug, PartialEq)]
567pub struct MeshSurfaces {
568    owner: MeshSurface,
569    more: Vec<MeshSurface>,
570}
571
572impl MeshSurfaces {
573    /// The content on `owner`, which places the layer, and on each of
574    /// `more`.
575    pub fn new(owner: MeshSurface, more: Vec<MeshSurface>) -> Self {
576        Self { owner, more }
577    }
578
579    /// The mesh that places the layer: the first.
580    pub fn owner(&self) -> &MeshSurface {
581        &self.owner
582    }
583
584    /// The meshes, the owner first.
585    pub fn iter(&self) -> impl Iterator<Item = &MeshSurface> {
586        std::iter::once(&self.owner).chain(&self.more)
587    }
588}
589
590impl From<MeshSurface> for MeshSurfaces {
591    fn from(owner: MeshSurface) -> Self {
592        Self::new(owner, Vec::new())
593    }
594}
595
596/// Where a ray meets a [`MeshSurface`].
597#[derive(Clone, Copy, Debug, PartialEq)]
598pub struct SurfaceHit {
599    /// How far along the ray, in units of its direction.
600    pub distance: f32,
601    /// The mesh triangle the ray meets.
602    pub triangle: u32,
603    /// The content point at the hit.
604    pub point: Point,
605}
606
607impl SurfaceHit {
608    fn of(hit: MeshHit, size: Size) -> Self {
609        Self {
610            distance: hit.distance,
611            triangle: hit.triangle,
612            point: content_point(hit.uv, size),
613        }
614    }
615}
616
617fn content_point([u, v]: [f32; 2], size: Size) -> Point {
618    Point::new(u * size.width, v * size.height)
619}
620
621/// Where a layer sits in 3D, as its graphics layer carries it.
622///
623/// Inside a scene, every layer takes a frame from its parent's: its place
624/// in its parent's layout, turned into 3D on the parent's plane, with z
625/// away from the side the content shows to. A layer that carries a space
626/// changes the frame its descendants take.
627#[derive(Clone, Debug, PartialEq)]
628pub enum LayerSpace {
629    /// The layer shows a scene: its children's frames are the scene's
630    /// space. Inside another scene, the layer's rect is a doorway into it.
631    Scene(Scene3d),
632    /// The layer's content is drawn on each of its meshes, placed in the
633    /// layer's frame, and its children's frames lie in that content as the
634    /// first mesh shows it.
635    Surface(MeshSurfaces),
636    /// Moves the frames of the layer's descendants in its own frame, as a
637    /// group of 3D objects moves together. The layer's own draws stay where
638    /// they would be without it.
639    Transform(Mat4),
640}