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 /// the shadows `casters` cast on the part of `receivers` that `camera`
152 /// shows in bounds of `size`. x and y run from -1 to 1 across the part
153 /// of the light where casters and that part overlap, with room for the
154 /// softest penumbra; depth runs from 0 at the caster nearest the light
155 /// to 1 at the farthest receiver the camera shows. A point farther along
156 /// the light than a caster's depth there lies in its shadow. `None` when
157 /// no caster overlaps a receiver the camera shows, or for a light with
158 /// no direction.
159 pub fn shadow_projection<'a>(
160 &self,
161 casters: impl IntoIterator<Item = &'a MeshSurface>,
162 receivers: impl IntoIterator<Item = &'a MeshSurface>,
163 (camera, size): (&Camera, Size),
164 ) -> Option<Mat4> {
165 const MARGIN: f32 = 0.02;
166 let forward = self.direction.normalized()?;
167 let hint = if forward.y.abs() < 0.9 {
168 Vec3::new(0.0, 1.0, 0.0)
169 } else {
170 Vec3::new(1.0, 0.0, 0.0)
171 };
172 let right = hint.cross(forward).normalized()?;
173 let up = forward.cross(right);
174 let view = Mat4::from_rows([
175 [right.x, right.y, right.z, 0.0],
176 [up.x, up.y, up.z, 0.0],
177 [forward.x, forward.y, forward.z, 0.0],
178 [0.0, 0.0, 0.0, 1.0],
179 ]);
180 let (caster_low, caster_high) = bounds_along(casters, &view);
181 let (seen_low, seen_high) = seen_receivers(receivers, &view, (camera, size))?;
182 // A caster darkens only what lies behind it along the light, and its
183 // penumbra reaches past it by the light's spread over the depth
184 // between them.
185 let reach = self.size.max(0.0).tan() * (seen_high.z - caster_low.z);
186 let low = Vec3::new(
187 caster_low.x.max(seen_low.x - reach),
188 caster_low.y.max(seen_low.y - reach),
189 caster_low.z,
190 );
191 let high = Vec3::new(
192 caster_high.x.min(seen_high.x + reach),
193 caster_high.y.min(seen_high.y + reach),
194 seen_high.z,
195 );
196 let extent = high - low;
197 let spans = |length: f32| length.is_finite() && length >= 0.0;
198 if !(spans(extent.x) && spans(extent.y) && spans(extent.z)) {
199 return None;
200 }
201 let pad = |extent: f32| (extent * MARGIN).max(1.0);
202 let (low, high) = (
203 low - Vec3::new(pad(extent.x), pad(extent.y), pad(extent.z)),
204 high + Vec3::new(pad(extent.x), pad(extent.y), pad(extent.z)),
205 );
206 let extent = high - low;
207 let fit = Mat4::from_rows([
208 [2.0 / extent.x, 0.0, 0.0, -1.0 - 2.0 * low.x / extent.x],
209 [0.0, 2.0 / extent.y, 0.0, -1.0 - 2.0 * low.y / extent.y],
210 [0.0, 0.0, 1.0 / extent.z, -low.z / extent.z],
211 [0.0, 0.0, 0.0, 1.0],
212 ]);
213 Some(view.then(&fit))
214 }
215}
216
217// The box, in the light's frame `light`, of what `camera` shows of
218// `receivers` in bounds of `size`: their own box, cut to the camera's view
219// between the nearest and the farthest of them. `None` when the camera
220// shows none of them.
221fn seen_receivers<'a>(
222 receivers: impl IntoIterator<Item = &'a MeshSurface>,
223 light: &Mat4,
224 (camera, size): (&Camera, Size),
225) -> Option<(Vec3, Vec3)> {
226 let empty = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
227 let (low, high, nearest, farthest) = receivers.into_iter().fold(
228 (empty, -empty, f32::INFINITY, f32::NEG_INFINITY),
229 |(low, high, nearest, farthest), surface| {
230 let (surface_low, surface_high) =
231 surface.mesh.bounds_in(&surface.transform.then(light));
232 let (seen_low, seen_high) = surface
233 .mesh
234 .bounds_in(&surface.transform.then(&camera.view));
235 (
236 low.min(surface_low),
237 high.max(surface_high),
238 nearest.min(seen_low.z),
239 farthest.max(seen_high.z),
240 )
241 },
242 );
243 let near = nearest.max(camera.near());
244 if !farthest.is_finite() || farthest < near {
245 return None;
246 }
247 let mut view = (empty, -empty);
248 for (x, y) in [
249 (0.0, 0.0),
250 (size.width, 0.0),
251 (0.0, size.height),
252 (size.width, size.height),
253 ] {
254 let ray = camera.ray(Point::new(x, y), size)?;
255 for depth in [near, farthest] {
256 let corner = light.transform_point(ray.origin + ray.direction * depth);
257 view = (view.0.min(corner), view.1.max(corner));
258 }
259 }
260 Some((low.max(view.0), high.min(view.1)))
261}
262
263// The box that holds `surfaces` in the coordinates of `view`.
264fn bounds_along<'a>(
265 surfaces: impl IntoIterator<Item = &'a MeshSurface>,
266 view: &Mat4,
267) -> (Vec3, Vec3) {
268 let empty = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
269 surfaces
270 .into_iter()
271 .fold((empty, -empty), |(low, high), surface| {
272 let (surface_low, surface_high) = surface.mesh.bounds_in(&surface.transform.then(view));
273 (low.min(surface_low), high.max(surface_high))
274 })
275}
276
277/// A scene's camera and light, which a `scene3d` modifier shows its
278/// children's mesh surfaces through.
279///
280/// A scene inside another scene's space is a doorway into a space of its
281/// own: the rect its layer covers in its frame opens onto that space, which
282/// lies behind it, placed so the doorway stands where the inner scene's
283/// camera stands (see [`Camera::doorway`]). The window's eye sees through
284/// doorways from the space it stands in, as deep as they show on screen,
285/// and walks through them (see [`EyePlace`]).
286#[derive(Clone, Debug, PartialEq)]
287pub struct Scene3d {
288 /// The camera the scene is seen through. For a scene behind a doorway,
289 /// the one that stands in the doorway; for the window's scene with an
290 /// [`eye`](Self::eye), the eye's, in the space the eye stands in.
291 pub camera: Camera,
292 /// The light on the scene's lit surfaces, or `None` for none.
293 pub light: Option<Light>,
294 /// For the window's scene, where its eye stands among the spaces behind
295 /// the scene's doorways and where the renderer leaves what the eye can
296 /// bump into; `None` for a camera in the scene's own space that walks
297 /// through nothing. A scene behind a doorway leaves it out.
298 pub eye: Option<EyePlace>,
299 /// How many samples the scene's pass takes in each pixel. A scene behind
300 /// a doorway draws in the pass of the window's scene, whose value counts
301 /// for both.
302 pub multisample: Multisample,
303}
304
305impl Scene3d {
306 /// A scene seen through `camera`, with no light, no eye and one sample
307 /// in each pixel.
308 pub fn new(camera: Camera) -> Self {
309 Self {
310 camera,
311 light: None,
312 eye: None,
313 multisample: Multisample::Off,
314 }
315 }
316}
317
318/// How many samples a scene's pass takes in each pixel.
319///
320/// With one sample, each pixel shows the surface its middle falls on, so the
321/// edge of a curved mesh, such as a sphere's or a tube's, steps from pixel to
322/// pixel. With four, the GPU tests coverage and depth at four points in each
323/// pixel and averages the colours they find, so the outline of a mesh and
324/// the line where two surfaces cut through each other show smooth. A
325/// surface's colour is still found once in each pixel: multisampling smooths
326/// the edges of meshes, not the edges of shapes a [`Volume`]'s shader finds
327/// or of transparent parts of a surface's content. A sheet, a mesh whose
328/// outline is its texture's edge, fades over that outline with either count.
329///
330/// A scene with four samples draws into targets of its own, four samples
331/// deep and as large as the scene, then averages them into the page: more
332/// GPU memory and time, which a scene left [`Off`](Self::Off) does not pay.
333/// The GPU renderer takes four samples on every backend, as every GPU format
334/// it draws scenes in supports them. The CPU renderer draws every scene with
335/// one sample.
336#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
337pub enum Multisample {
338 /// One sample in each pixel.
339 #[default]
340 Off,
341 /// Four samples in each pixel.
342 X4,
343}
344
345impl Multisample {
346 /// The samples taken in each pixel.
347 pub const fn samples(self) -> u32 {
348 match self {
349 Self::Off => 1,
350 Self::X4 => 4,
351 }
352 }
353}
354
355/// A composable's content drawn on a mesh placed in a scene.
356#[derive(Clone, Debug, PartialEq)]
357pub struct MeshSurface {
358 /// The mesh the content is drawn on.
359 pub mesh: Arc<Mesh>,
360 /// Places the mesh in the scene.
361 pub transform: Mat4,
362 /// How the content meets the scene's light and what lies behind it.
363 pub material: Material,
364 /// Whether the surface casts a shadow from the scene's light. Every lit
365 /// and unlit surface takes the shadows that fall on it.
366 pub casts_shadow: bool,
367 /// Whether an eye that walks into the surface (see
368 /// [`EyeWorld::walk`](super::EyeWorld::walk)) stops there. A doorway in
369 /// the surface's content lets it through.
370 pub solid: bool,
371}
372
373/// How a surface's content meets the scene's light and what lies behind
374/// it.
375#[derive(Clone, Debug, PartialEq)]
376pub enum Material {
377 /// Shaded by the angle the light falls at, and darkened where a shadow
378 /// falls on it.
379 Lit,
380 /// The content as it is, as a screen shows it, darkened only where a
381 /// shadow falls on it.
382 Unlit,
383 /// The content at its full colour, as fire or a lamp shows: neither the
384 /// light nor a shadow changes it.
385 Emissive,
386 /// Adds the content's colour to what lies behind it, as light does: a
387 /// halo, a flame or a spark. It hides nothing, and surfaces nearer the
388 /// eye hide it.
389 Glow,
390 /// The scene behind shows through, bent by the surface's curve, with the
391 /// light's highlight on it and the content drawn over it. Glass shows
392 /// the surfaces that are not glass behind it.
393 Glass(Glass),
394 /// A shape an app's shader finds inside the mesh, ray by ray, as the
395 /// camera sees it, with the depth of what each ray meets: the mesh only
396 /// bounds it. A volume casts no shadow.
397 Volume(Volume),
398 /// Coloured by an app's shader from the content, the light and the eye
399 /// at each point of the surface: a reflection, a sheen, a normal of its
400 /// own. Until the shader builds, and if it never does, the surface is
401 /// [`Lit`](Self::Lit).
402 Shaded(Shaded),
403}
404
405/// An app's shader that colours a surface: each pixel the mesh covers asks
406/// it for its colour from the content there, the light and the eye.
407///
408/// `shader` is WGSL that defines
409///
410/// ```text
411/// fn shade(surface: ShadedSurface) -> vec4<f32>
412/// ```
413///
414/// and returns the colour, premultiplied. `ShadedSurface` holds, in the
415/// mesh's own coordinates: `color`, the content's colour there,
416/// premultiplied; `uv`, where the point lies in the content, from `(0, 0)`
417/// at its top left corner to `(1, 1)` at its bottom right, at which
418/// `content_color(uv)` reads the content anywhere; `position`; `eye`;
419/// `normal`, of length one, on the side
420/// the eye sees; `to_eye` and `to_light`, of length one, toward the eye
421/// and toward the light, which is zero without a light; `lit`, how much of
422/// the light reaches the point, from 0 in full shadow to 1; and `ambient`,
423/// the light's ambient share, 1 without a light. `shaded_param(index)`
424/// reads `params[index]`. The renderer puts
425/// [`MESH_SHADED_PRELUDE_WGSL`](crate::framework_shaders::MESH_SHADED_PRELUDE_WGSL),
426/// which declares them, before it.
427#[derive(Clone, Debug)]
428pub struct Shaded {
429 /// The app's WGSL. Keep one `Arc` per shader: the renderer builds a
430 /// pipeline for each.
431 pub shader: Arc<str>,
432 /// The values the shader reads.
433 pub params: [f32; Self::PARAMS],
434}
435
436impl Shaded {
437 /// How many values a surface's shader reads.
438 pub const PARAMS: usize = 32;
439}
440
441impl PartialEq for Shaded {
442 fn eq(&self, other: &Self) -> bool {
443 Arc::ptr_eq(&self.shader, &other.shader) && self.params == other.params
444 }
445}
446
447/// An app's shader that draws inside a mesh: each pixel the mesh covers
448/// asks it what the camera's ray through the pixel meets.
449///
450/// `shader` is WGSL that defines
451///
452/// ```text
453/// fn volume(eye: vec3<f32>, direction: vec3<f32>, entry: f32, exit: f32, footprint: f32) -> VolumeHit
454/// ```
455///
456/// in the mesh's own coordinates: the eye; the ray's direction, of length
457/// one; how far along the ray it enters the mesh's bounds, zero for an eye
458/// inside them, and leaves the mesh; and how wide a pixel is, in radians.
459/// It returns a `VolumeHit`: the colour, premultiplied, nothing at an alpha
460/// of zero; and the point the ray met, which sets the pixel's depth.
461/// `volume_param(index)` reads `params[index]`, `volume_content(uv)` the
462/// surface's content and `volume_light()` the scene's light, in the mesh's
463/// coordinates. The renderer puts
464/// [`MESH_VOLUME_PRELUDE_WGSL`](crate::framework_shaders::MESH_VOLUME_PRELUDE_WGSL),
465/// which declares them, before it. The mesh's normals must point out of it.
466#[derive(Clone, Debug)]
467pub struct Volume {
468 /// The app's WGSL. Keep one `Arc` per shader: the renderer builds a
469 /// pipeline for each.
470 pub shader: Arc<str>,
471 /// The values the shader reads.
472 pub params: [f32; Self::PARAMS],
473}
474
475impl Volume {
476 /// How many values a volume's shader reads.
477 pub const PARAMS: usize = 32;
478}
479
480impl PartialEq for Volume {
481 fn eq(&self, other: &Self) -> bool {
482 Arc::ptr_eq(&self.shader, &other.shader) && self.params == other.params
483 }
484}
485
486/// How glass bends and tints the scene behind it.
487#[derive(Clone, Copy, Debug, PartialEq)]
488pub struct Glass {
489 /// The refractive index: 1 bends nothing, window glass is 1.5 and
490 /// diamond 2.4.
491 pub index: f32,
492 /// How far a ray travels inside the glass, in scene units: a ball's
493 /// diameter for a solid ball. A ray bends entering the glass and again
494 /// leaving it, as through a solid ball, so a thick ball shows the scene
495 /// behind it upside down.
496 pub thickness: f32,
497 /// The colour the glass tints what shows through it; white for clear
498 /// glass.
499 pub tint: Color,
500}
501
502impl Glass {
503 /// Clear window glass a ray crosses for `thickness` scene units.
504 pub const fn clear(thickness: f32) -> Self {
505 Self {
506 index: 1.5,
507 thickness,
508 tint: Color(1.0, 1.0, 1.0, 1.0),
509 }
510 }
511}
512
513impl MeshSurface {
514 /// The content of a composable of `size` on the mesh: the content point
515 /// where the ray meets the mesh, the triangle it meets, and how far along
516 /// the ray.
517 pub fn cast(&self, ray: Ray, size: Size) -> Option<SurfaceHit> {
518 let inverse = self.transform.inverse()?;
519 let hit = self.mesh.cast(
520 inverse.transform_point(ray.origin),
521 inverse.transform_vector(ray.direction),
522 )?;
523 Some(SurfaceHit::of(hit, size))
524 }
525
526 /// The content point of a composable of `size` where the ray meets the
527 /// plane of `triangle`: a drag that leaves the mesh's edge goes on along
528 /// it.
529 pub fn cast_plane(&self, ray: Ray, triangle: u32, size: Size) -> Option<Point> {
530 let inverse = self.transform.inverse()?;
531 let uv = self.mesh.cast_plane(
532 inverse.transform_point(ray.origin),
533 inverse.transform_vector(ray.direction),
534 triangle,
535 )?;
536 Some(content_point(uv, size))
537 }
538
539 /// The projective map that carries the content of a composable of
540 /// `size` from the mesh to the bounds of `viewport` that `camera` shows.
541 /// It is exact for a flat mesh; for a curved one it follows the plane
542 /// that touches the mesh at the content's middle. It sends the part
543 /// nearer than the camera's near plane to w below [`NEAR_PLANE`], which
544 /// [`ProjectiveTransform::front_polygon`] cuts away. `None` for content
545 /// of no size, or for a mesh with no texture plane.
546 pub fn content_transform(
547 &self,
548 camera: &Camera,
549 viewport: Size,
550 size: Size,
551 ) -> Option<ProjectiveTransform> {
552 if !(size.width > 0.0 && size.height > 0.0) {
553 return None;
554 }
555 let plane = self.mesh.texture_plane()?;
556 let to_camera = self.transform.then(&camera.view);
557 let origin = to_camera.transform_point(plane.origin);
558 let right = to_camera.transform_vector(plane.u_axis) * (1.0 / size.width);
559 let down = to_camera.transform_vector(plane.v_axis) * (1.0 / size.height);
560 let (center_x, center_y) = (viewport.width * 0.5, viewport.height * 0.5);
561 let focal_length = camera.focal_length;
562 let column = |v: Vec3| {
563 [
564 v.x + center_x * v.z / focal_length,
565 v.y + center_y * v.z / focal_length,
566 v.z / focal_length,
567 ]
568 };
569 let [a, b, c] = [column(right), column(down), column(origin)];
570 Some(ProjectiveTransform::from_rows([
571 [a[0], b[0], c[0]],
572 [a[1], b[1], c[1]],
573 [a[2], b[2], c[2]],
574 ]))
575 }
576
577 /// The map from the content space of a composable of `size` on the mesh
578 /// into the scene: x and y in the content's pixels from its top left, z
579 /// into the surface, away from the side it shows its content to, a unit
580 /// as long as a content pixel. A mesh surface inside this content is
581 /// placed in that space. It is exact for a flat mesh; for a curved one it
582 /// follows the plane that touches the mesh at the content's middle.
583 /// `None` for content of no size, or for a mesh with no texture plane.
584 pub fn content_to_scene(&self, size: Size) -> Option<Mat4> {
585 if !(size.width > 0.0 && size.height > 0.0) {
586 return None;
587 }
588 let plane = self.mesh.texture_plane()?;
589 let right = self.transform.transform_vector(plane.u_axis) * (1.0 / size.width);
590 let down = self.transform.transform_vector(plane.v_axis) * (1.0 / size.height);
591 let into = right.cross(down).normalized()? * (right.length() * down.length()).sqrt();
592 Some(Mat4::from_axes(
593 right,
594 down,
595 into,
596 self.transform.transform_point(plane.origin),
597 ))
598 }
599
600 /// This surface with its transform followed by `to_scene`: a surface
601 /// inside another's content, placed in the scene through the other's
602 /// [`content_to_scene`](Self::content_to_scene). Glass keeps its
603 /// thickness in the units of the space it is placed from.
604 pub fn placed_by(&self, to_scene: &Mat4) -> Self {
605 let material = match &self.material {
606 Material::Glass(glass) => Material::Glass(Glass {
607 thickness: glass.thickness * to_scene.length_scale(),
608 ..*glass
609 }),
610 material => material.clone(),
611 };
612 Self {
613 mesh: Arc::clone(&self.mesh),
614 transform: self.transform.then(to_scene),
615 material,
616 casts_shadow: self.casts_shadow,
617 solid: self.solid,
618 }
619 }
620
621 /// Where the content point `point` of a composable of `size` lies in the
622 /// scene.
623 pub fn point_at(&self, point: Point, size: Size) -> Option<Vec3> {
624 let uv = [
625 point.x / size.width.max(f32::MIN_POSITIVE),
626 point.y / size.height.max(f32::MIN_POSITIVE),
627 ];
628 self.mesh
629 .point_at(uv)
630 .map(|position| self.transform.transform_point(position))
631 }
632}
633
634/// The meshes one composable's content is drawn on: one or more, each
635/// placed in the scene on its own, all showing the same live content.
636///
637/// The content is rendered once and every mesh shows it. A pointer takes
638/// the nearest of the meshes where it points and reaches the content point
639/// that mesh shows there; a drag stays on the mesh it started on. The first
640/// mesh, the owner, places the layer for everything that needs one place:
641/// the 3D frames of the layer's children, the doorways in its content, and
642/// the bounds the window and accessibility services report for the content.
643#[derive(Clone, Debug, PartialEq)]
644pub struct MeshSurfaces {
645 owner: MeshSurface,
646 more: Vec<MeshSurface>,
647}
648
649impl MeshSurfaces {
650 /// The content on `owner`, which places the layer, and on each of
651 /// `more`.
652 pub fn new(owner: MeshSurface, more: Vec<MeshSurface>) -> Self {
653 Self { owner, more }
654 }
655
656 /// The mesh that places the layer: the first.
657 pub fn owner(&self) -> &MeshSurface {
658 &self.owner
659 }
660
661 /// The meshes, the owner first.
662 pub fn iter(&self) -> impl Iterator<Item = &MeshSurface> {
663 std::iter::once(&self.owner).chain(&self.more)
664 }
665
666 /// The meshes, the owner first, for a caller that moves them in a value it owns, such as one
667 /// that animates a model and keeps its surfaces from one frame to the next.
668 pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut MeshSurface> {
669 std::iter::once(&mut self.owner).chain(&mut self.more)
670 }
671}
672
673impl From<MeshSurface> for MeshSurfaces {
674 fn from(owner: MeshSurface) -> Self {
675 Self::new(owner, Vec::new())
676 }
677}
678
679/// Where a ray meets a [`MeshSurface`].
680#[derive(Clone, Copy, Debug, PartialEq)]
681pub struct SurfaceHit {
682 /// How far along the ray, in units of its direction.
683 pub distance: f32,
684 /// The mesh triangle the ray meets.
685 pub triangle: u32,
686 /// The content point at the hit.
687 pub point: Point,
688}
689
690impl SurfaceHit {
691 fn of(hit: MeshHit, size: Size) -> Self {
692 Self {
693 distance: hit.distance,
694 triangle: hit.triangle,
695 point: content_point(hit.uv, size),
696 }
697 }
698}
699
700fn content_point([u, v]: [f32; 2], size: Size) -> Point {
701 Point::new(u * size.width, v * size.height)
702}
703
704/// Where a layer sits in 3D, as its graphics layer carries it.
705///
706/// Inside a scene, every layer takes a frame from its parent's: its place
707/// in its parent's layout, turned into 3D on the parent's plane, with z
708/// away from the side the content shows to. A layer that carries a space
709/// changes the frame its descendants take.
710#[derive(Clone, Debug, PartialEq)]
711pub enum LayerSpace {
712 /// The layer shows a scene: its children's frames are the scene's
713 /// space. Inside another scene, the layer's rect is a doorway into it.
714 Scene(Scene3d),
715 /// The layer's content is drawn on each of its meshes, placed in the
716 /// layer's frame, and its children's frames lie in that content as the
717 /// first mesh shows it.
718 Surface(MeshSurfaces),
719 /// Moves the frames of the layer's descendants in its own frame, as a
720 /// group of 3D objects moves together. The layer's own draws stay where
721 /// they would be without it.
722 Transform(Mat4),
723}