1//! Scene operators that edit or add geometry: `Fog3D`, `Locator3D`, `PointCloud3D`, `Ribbon3D` and `UVMap`.
2
3use std::f32::consts::{PI, TAU};
4use std::sync::Arc;
5
6use super::collect::{euler_matrix, ResolvedMaterial};
7use super::materials::flat;
8use super::mesh::{build_shape_mesh, triangle_soup};
9use super::{MeshInstance, ShapeKind, Vertex3D};
10use model::{Comp, ExprEngine, Node};
11
12pub(super) fn fog(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, meshes: &mut [MeshInstance]) {
13 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
14 if f("Enable", 1.0) < 0.5 {
15 return;
16 }
17 let kind = match n.static_str("FogType") {
18 Some("Exp") => 2.0,
19 Some("Exp2") => 3.0,
20 _ => 1.0,
21 };
22 let fog = [kind, f("NearFogDist", 1.0), f("FarFogDistance", 100.0), f("FogDensity", 0.05)];
23 let fog_col = [f("FogRed", 0.7), f("FogGreen", 0.7), f("FogBlue", 0.8), f("Radial", 0.0)];
24 for m in meshes {
25 if let ShapeKind::WithMaterialFx { fx, .. } = &mut m.shape {
26 fx.sfx.fog = fog;
27 fx.sfx.fog_col = fog_col;
28 }
29 }
30}
31
32/// Segments as degenerate `(a, b, b)` triangles, which the wireframe pass draws as the line `a-b`.
33fn lines(segments: impl IntoIterator<Item = [[f32; 3]; 2]>, normal: [f32; 3], mut mat: ResolvedMaterial) -> (ShapeKind, ResolvedMaterial) {
34 let v = |pos| Vertex3D { pos, normal, uv: [0.0; 2] };
35 mat.fx.wireframe = true;
36 (ShapeKind::CustomMesh(Arc::new(segments.into_iter().flat_map(|[a, b]| [v(a), v(b), v(b)]).collect())), mat)
37}
38
39/// `Locator3D` with `MakeRenderable`: an unlit axis cross `Size` across.
40pub(super) fn locator(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> Option<(ShapeKind, ResolvedMaterial)> {
41 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
42 if f("MakeRenderable", 0.0) < 0.5 || f("UnseenByCamera", 0.0) > 0.5 {
43 return None;
44 }
45 let half = f("Size", 0.25) * 0.5;
46 let axes = [0, 1, 2].map(|a| {
47 let mut p = [0.0; 3];
48 p[a] = half;
49 [p.map(|c| -c), p]
50 });
51 Some(lines(axes, [0.0, 0.0, 1.0], flat([f("ColorRed", 1.0), f("ColorGreen", 1.0), f("ColorBlue", 1.0), 1.0])))
52}
53
54/// `Ribbon3D`: `NumberOfLines` parallel lines from `Start` to `End`, spread `RibbonWidth` across
55/// the axis's up side and turned about it by `RibbonRotation`.
56pub(super) fn ribbon(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, mat: ResolvedMaterial) -> (ShapeKind, ResolvedMaterial) {
57 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
58 let point = |k: &str, d: [f64; 3]| [0, 1, 2].map(|i| f(&format!("{k}.{}", ["X", "Y", "Z"][i]), d[i]));
59 let (start, end) = (point("Start", [-1.0, 0.0, 0.0]), point("End", [1.0, 0.0, 0.0]));
60 let dot = |a: [f32; 3], b: [f32; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
61 let unit = |a: [f32; 3]| {
62 let l = dot(a, a).sqrt();
63 if l > 1e-9 { a.map(|c| c / l) } else { [1.0, 0.0, 0.0] }
64 };
65 let axis = unit([0, 1, 2].map(|i| end[i] - start[i]));
66 let up = if axis[1].abs() > 0.99 { [0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0] };
67 let side0 = unit([0, 1, 2].map(|i| up[i] - axis[i] * dot(up, axis)));
68 let normal0 = [axis[1] * side0[2] - axis[2] * side0[1], axis[2] * side0[0] - axis[0] * side0[2], axis[0] * side0[1] - axis[1] * side0[0]];
69 let (s, c) = f("RibbonRotation", 0.0).to_radians().sin_cos();
70 let side = [0, 1, 2].map(|i| side0[i] * c + normal0[i] * s);
71 let normal = [0, 1, 2].map(|i| normal0[i] * c - side0[i] * s);
72 let count = f("NumberOfLines", 10.0).round().max(1.0) as usize;
73 let width = f("RibbonWidth", 0.2);
74 let segments = (0..count).map(|i| {
75 let t = if count == 1 { 0.0 } else { (i as f32 / (count - 1) as f32 - 0.5) * width };
76 [start, end].map(|p| [0, 1, 2].map(|k| p[k] + side[k] * t))
77 });
78 lines(segments, normal, mat)
79}
80
81/// `PointCloud3D` with `MakeRenderable`: an unlit cross per point of its `Positions` table
82/// (`{ x, y, z, "name" }` rows), thinned to `Density`. `Point` style draws a cross `Point.Size`
83/// pixels across at a 256-pixel-wide unit.
84pub(super) fn point_cloud(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> Option<(ShapeKind, ResolvedMaterial)> {
85 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
86 if f("MakeRenderable", 0.0) < 0.5 || f("UnseenByCamera", 0.0) > 0.5 {
87 return None;
88 }
89 let half = if n.static_str("LocatorStyle") == Some("Point") {
90 [f("Point.Size", 8.0) / 512.0; 3]
91 } else {
92 let x = f("Cross.Size.X", 0.25);
93 if f("Cross.Size.Lock", 1.0) > 0.5 { [x; 3] } else { [x, f("Cross.Size.Y", 0.25), f("Cross.Size.Z", 0.25)] }.map(|s| s * 0.5)
94 };
95 let density = f("Density", 1.0).clamp(0.0, 1.0);
96 let rows = n.raw.get_table("Positions").into_iter().flat_map(|t| t.positional_values());
97 let points: Vec<[f32; 3]> = rows
98 .filter_map(|row| {
99 let t = row.as_table()?;
100 let c = |i: i64, k: &str| t.get_index(i).or_else(|| t.get(k)).and_then(|v| v.as_f64()).map(|v| v as f32);
101 Some([c(1, "X")?, c(2, "Y")?, c(3, "Z")?])
102 })
103 .enumerate()
104 .filter(|&(i, _)| ((i + 1) as f32 * density).floor() > (i as f32 * density).floor())
105 .map(|(_, p)| p)
106 .collect();
107 let segments = points.iter().flat_map(|p| {
108 [0, 1, 2].map(|a| {
109 let (mut lo, mut hi) = (*p, *p);
110 lo[a] -= half[a];
111 hi[a] += half[a];
112 [lo, hi]
113 })
114 });
115 Some(lines(segments, [0.0, 0.0, 1.0], flat([f("ColorRed", 1.0), f("ColorGreen", 1.0), f("ColorBlue", 1.0), 1.0])))
116}
117
118#[derive(Clone, Copy, PartialEq)]
119enum UvMode {
120 Planar,
121 Cylindrical,
122 Spherical,
123 Cube,
124 Xyz,
125}
126
127/// `UVMap` projection: world points enter the map's frame (`R^T (p - Center)`), whose
128/// `Orientation` axis is "up" and whose other two axes span the image.
129pub(super) struct UvMap {
130 mode: UvMode,
131 rot: [f32; 16],
132 center: [f32; 3],
133 size: [f32; 3],
134 orientation: usize,
135 tile: [f32; 2],
136 flip: [bool; 2],
137}
138
139/// `(s, t, up)` world-axis indices and signs per `Orientation` (`X`, `Y`, `Z`).
140const FRAMES: [[(usize, f32); 3]; 3] = [[(2, -1.0), (1, 1.0), (0, 1.0)], [(0, 1.0), (2, -1.0), (1, 1.0)], [(0, 1.0), (1, 1.0), (2, 1.0)]];
141
142impl UvMap {
143 /// `None` for `Camera` projection, which leaves UVs untouched.
144 pub(super) fn from_node(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> Option<Self> {
145 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
146 let xyz = |k: &str, d: f64| ["X", "Y", "Z"].map(|a| f(&format!("{k}.{a}"), d));
147 let mode = match n.static_str("MapMode") {
148 Some("Cylindrical") => UvMode::Cylindrical,
149 Some("Spherical") => UvMode::Spherical,
150 Some("CubeMap") => UvMode::Cube,
151 Some("XYZtoUVW") => UvMode::Xyz,
152 Some("Camera") => return None,
153 _ => UvMode::Planar,
154 };
155 Some(Self {
156 mode,
157 rot: euler_matrix(xyz("Rotate", 0.0), n.static_str("Rotate.RotOrder").unwrap_or("XYZ")),
158 center: xyz("Center", 0.0),
159 size: xyz("Size", 2.0).map(|s| if s.abs() < 1e-6 { 1e-6 } else { s }),
160 orientation: f("Orientation", 1.0).round().clamp(0.0, 2.0) as usize,
161 tile: [f("Tile.U", 1.0), f("Tile.V", 1.0)],
162 flip: [f("Flip.U", 0.0) > 0.5, f("Flip.V", 0.0) > 0.5],
163 })
164 }
165
166 fn to_local(&self, p: [f32; 3]) -> [f32; 3] {
167 let (r, c) = (&self.rot, self.center);
168 [0, 1, 2].map(|i| r[i * 4] * (p[0] - c[0]) + r[i * 4 + 1] * (p[1] - c[1]) + r[i * 4 + 2] * (p[2] - c[2]))
169 }
170
171 /// Mesh UV (V down) of world point `p`; in cube mode the face is the dominant axis of the
172 /// world point `face_at`.
173 fn uv(&self, p: [f32; 3], face_at: [f32; 3]) -> [f32; 2] {
174 let local = self.to_local(p);
175 let (orientation, face_sign) = if self.mode == UvMode::Cube {
176 let f = self.to_local(face_at);
177 let a = (0..3).max_by(|&a, &b| f[a].abs().total_cmp(&f[b].abs())).unwrap_or(2);
178 (a, if f[a] < 0.0 { -1.0 } else { 1.0 })
179 } else {
180 (self.orientation, 1.0)
181 };
182 let [s, t, up] = FRAMES[orientation].map(|(i, sign)| (local[i] * sign, self.size[i]));
183 let (u, v) = match self.mode {
184 UvMode::Xyz => return [s.0, 1.0 - t.0],
185 UvMode::Planar | UvMode::Cube => (face_sign * s.0 / s.1, t.0 / t.1),
186 UvMode::Cylindrical | UvMode::Spherical => {
187 let u = s.0.atan2(-t.0) / TAU;
188 let len = (s.0 * s.0 + t.0 * t.0 + up.0 * up.0).sqrt();
189 let v = if self.mode == UvMode::Cylindrical { up.0 / up.1 } else { (up.0 / len.max(1e-9)).clamp(-1.0, 1.0).asin() / PI };
190 (u, v)
191 }
192 };
193 let [u, v] = [(u, 0), (v, 1)].map(|(c, k)| {
194 let c = c * self.tile[k] + 0.5;
195 if self.flip[k] { 1.0 - c } else { c }
196 });
197 [u, 1.0 - v]
198 }
199}
200
201/// Re-projects UVs; in cube mode each triangle takes the face of its centroid.
202pub(super) fn uv_map(map: &UvMap, meshes: &mut [MeshInstance], aspect: impl Fn(&MeshInstance) -> f32) {
203 for m in meshes.iter_mut().filter(|m| m.text3d.is_none()) {
204 let mut soup = triangle_soup(build_shape_mesh(m.shape.base_shape(), aspect(m)));
205 let w = m.world;
206 let to_world = |v: [f32; 3]| [0, 1, 2].map(|i| w[i] * v[0] + w[4 + i] * v[1] + w[8 + i] * v[2] + w[12 + i]);
207 for tri in soup.chunks_exact_mut(3) {
208 let p = [0, 1, 2].map(|k| to_world(tri[k].pos));
209 let centroid = [0, 1, 2].map(|i| (p[0][i] + p[1][i] + p[2][i]) / 3.0);
210 for (v, q) in tri.iter_mut().zip(p) {
211 v.uv = map.uv(q, centroid);
212 }
213 }
214 let (_, fx) = m.shape.split_fx();
215 m.shape = ShapeKind::WithMaterialFx { inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))), fx };
216 }
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use crate::scene3d::collect::{collect_test_scene, comp_src};
223
224 fn scene(tools: &str) -> (Vec<MeshInstance>, crate::scene3d::SceneLights) {
225 let (_, meshes, lights) = collect_test_scene(&comp_src(tools), "R");
226 (meshes, lights)
227 }
228
229 #[test]
230 fn fog_tags_every_child_mesh() {
231 let (meshes, _) = scene(
232 "S = Shape3D { }, C = Shape3D { },
233 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = \"S\", Source = \"Output\", }, SceneInput2 = Input { SourceOp = \"C\", Source = \"Output\", }, }, },
234 R = Fog3D { Inputs = { SceneInput = Input { SourceOp = \"M\", Source = \"Output\", }, FogType = Input { Value = FuID { \"Exp2\" }, },
235 FogDensity = Input { Value = 0.3, }, Radial = Input { Value = 1, }, }, },",
236 );
237 assert_eq!(meshes.len(), 2);
238 for m in &meshes {
239 let fx = m.shape.split_fx().1;
240 assert_eq!(fx.sfx.fog, [3.0, 1.0, 100.0, 0.3]);
241 assert_eq!(fx.sfx.fog_col, [0.7, 0.7, 0.8, 1.0]);
242 }
243 }
244
245 #[test]
246 fn locator_draws_a_cross_and_leaves_its_input_untransformed() {
247 let (meshes, _) = scene(
248 "S = Shape3D { },
249 R = Locator3D { Inputs = { SceneInput = Input { SourceOp = \"S\", Source = \"Output\", }, MakeRenderable = Input { Value = 1, },
250 [\"Transform3DOp.Translate.X\"] = Input { Value = 3, }, ColorGreen = Input { Value = 0, }, }, },",
251 );
252 assert_eq!(meshes.len(), 2);
253 assert_eq!(meshes[0].world[12], 3.0);
254 assert_eq!(meshes[0].diffuse_col, [1.0, 0.0, 1.0, 1.0]);
255 assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::CustomMesh(v) if v.len() == 9));
256 assert!(meshes[0].shape.split_fx().1.wireframe);
257 assert_eq!(meshes[1].world[12], 0.0);
258 let (hidden, _) = scene("R = Locator3D { },");
259 assert!(hidden.is_empty());
260 }
261
262 #[test]
263 fn point_cloud_draws_thinned_crosses_from_its_positions_table() {
264 let positions = "Positions = { Version = 2, [0] = { 1, 2, 3, \"A\", \"\" }, [1] = { -1, 0, 0, \"B\", \"\" }, [2] = { 0, 0, 5, \"C\", \"\" }, [3] = { 2, 2, 2, \"D\", \"\" }, },";
265 let (meshes, _) = scene(&format!(
266 "R = PointCloud3D {{ Inputs = {{ MakeRenderable = Input {{ Value = 1, }}, Density = Input {{ Value = 0.5, }}, ColorBlue = Input {{ Value = 0, }}, }}, {positions} }},"
267 ));
268 let ShapeKind::CustomMesh(v) = meshes[0].shape.base_shape() else { panic!("point cloud mesh") };
269 assert_eq!(v.len(), 2 * 3 * 3, "every other point, three segments each");
270 assert_eq!(v[0].pos, [-1.125, 0.0, 0.0], "B's X arm");
271 assert_eq!(meshes[0].diffuse_col, [1.0, 1.0, 0.0, 1.0]);
272 let (hidden, _) = scene(&format!("R = PointCloud3D {{ {positions} }},"));
273 assert!(hidden.is_empty());
274 }
275
276 #[test]
277 fn ribbon_spreads_lines_across_its_width() {
278 let (meshes, _) = scene("R = Ribbon3D { Inputs = { NumberOfLines = Input { Value = 3, }, RibbonWidth = Input { Value = 1, }, }, },");
279 let ShapeKind::CustomMesh(v) = meshes[0].shape.base_shape() else { panic!("ribbon mesh") };
280 let ys: Vec<f32> = v.chunks(3).map(|t| t[0].pos[1]).collect();
281 assert_eq!(ys, [-0.5, 0.0, 0.5]);
282 assert_eq!((v[0].pos[0], v[1].pos[0]), (-1.0, 1.0));
283 assert!(meshes[0].shape.split_fx().1.wireframe);
284 }
285
286 #[test]
287 fn triangulate_passes_through_and_weld_smooths_normals() {
288 let cube = "S = Shape3D { Inputs = { Shape = Input { Value = FuID { \"SurfaceCubeInputs\" }, }, }, },";
289 let (tri, _) = scene(&format!("{cube} R = Triangulate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = \"S\", Source = \"Output\", }}, }}, }},"));
290 assert!(matches!(tri[0].shape.base_shape(), ShapeKind::Cube { .. }));
291 let (dropped, _) = scene(&format!("{cube} R = Triangulate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = \"S\", Source = \"Output\", }}, Mode = Input {{ Value = 1, }}, }}, }},"));
292 assert!(dropped.is_empty());
293 let (welded, _) = scene(&format!(
294 "{cube} R = Weld3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = \"S\", Source = \"Output\", }}, WeldNormals = Input {{ Value = 1, }}, }}, }},"
295 ));
296 let ShapeKind::CustomMesh(v) = welded[0].shape.base_shape() else { panic!("welded mesh") };
297 let corner = v.iter().find(|p| p.pos.iter().all(|c| c.abs() > 0.49)).expect("corner vertex");
298 assert!(corner.normal.iter().all(|c| c.abs() > 0.5), "corner normals average the three faces: {:?}", corner.normal);
299 }
300
301 #[test]
302 fn light_dome_is_ambient_only_when_textured() {
303 let (_, bare) = scene("R = LightDome { Inputs = { Intensity = Input { Value = 0.5, }, }, },");
304 assert_eq!((bare.count, bare.ambient), (1, [0.0; 3]));
305 let (_, lit) = scene(
306 "Img = Background { },
307 R = LightDome { Inputs = { Intensity = Input { Value = 0.5, }, DomeTexture = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },",
308 );
309 assert_eq!(lit.ambient, [0.5; 3]);
310 }
311
312 #[test]
313 fn uv_map_rebuilds_child_meshes() {
314 let (meshes, _) = scene(
315 "S = Shape3D { },
316 R = UVMap { Inputs = { SceneInput = Input { SourceOp = \"S\", Source = \"Output\", }, }, },",
317 );
318 let ShapeKind::CustomMesh(v) = meshes[0].shape.base_shape() else { panic!("uv mapped mesh") };
319 assert!(v.iter().all(|p| (0.0..=1.0).contains(&p.uv[0]) && (0.0..=1.0).contains(&p.uv[1])));
320 }
321
322 fn map(mode: UvMode, orientation: usize) -> UvMap {
323 UvMap { mode, rot: crate::scene3d::mat4_identity(), center: [0.0; 3], size: [2.0; 3], orientation, tile: [1.0; 2], flip: [false; 2] }
324 }
325
326 #[test]
327 fn planar_orientations_follow_fusion_frames() {
328 let p = [0.5, 0.25, -0.5];
329 assert_eq!(map(UvMode::Planar, 2).uv(p, [0.0; 3]), [0.75, 1.0 - 0.625]);
330 assert_eq!(map(UvMode::Planar, 1).uv(p, [0.0; 3]), [0.75, 1.0 - 0.75]);
331 assert_eq!(map(UvMode::Planar, 0).uv(p, [0.0; 3]), [0.75, 1.0 - 0.625]);
332 let mut tiled = map(UvMode::Planar, 2);
333 tiled.tile = [2.0, 1.0];
334 tiled.flip = [false, true];
335 assert_eq!(tiled.uv(p, [0.0; 3]), [1.0, 0.625]);
336 }
337
338 #[test]
339 fn cylindrical_spherical_and_xyz() {
340 let front = [0.0, 0.0, 1.0];
341 let cyl = map(UvMode::Cylindrical, 1).uv(front, front);
342 assert!((cyl[0] - 0.5).abs() < 1e-6 && (cyl[1] - 0.5).abs() < 1e-6, "{cyl:?}");
343 let top = map(UvMode::Spherical, 1).uv([0.0, 1.0, 0.0], [0.0, 1.0, 0.0]);
344 assert!((top[1] - 0.0).abs() < 1e-6, "pole maps to v = 1 (V down 0): {top:?}");
345 assert_eq!(map(UvMode::Xyz, 2).uv([0.3, 0.4, 0.5], [0.0; 3]), [0.3, 0.6]);
346 }
347
348 #[test]
349 fn cube_mode_projects_each_face_along_its_dominant_axis() {
350 let m = map(UvMode::Cube, 1);
351 let side = m.uv([1.0, 0.5, 0.0], [1.0, 0.4, 0.0]);
352 let back = m.uv([-1.0, 0.5, 0.0], [-1.0, 0.4, 0.0]);
353 assert_eq!(side[1], back[1]);
354 assert_eq!(side[1], 1.0 - 0.75);
355 }
356}