1//! 3D scene graph traversal, material resolution, and 3D transform evaluation.
2
3use std::sync::Arc;
4
5use super::deform::{
6 apply_bender_to_meshes, extract_replicate_points, replicate_meshes, Bender3DParams, BenderMode,
7 Replicate3DParams, MAX_SCENE_MESHES,
8};
9use super::fbx::load_mesh_cached;
10use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, smooth_normals, triangle_soup};
11use super::math::{
12 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
13};
14use super::fx::layer_mode;
15use super::{alembic, custom_vertex, extrude, materials, projection, relief, scene_ops, textures};
16use super::{
17 CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights,
18 ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, Vertex3D, CUBE_FACES,
19};
20use model::{Comp, ExprEngine, Node, NodeId};
21
22#[derive(Clone, Default)]
23struct SceneOverrides {
24 material_override: Option<NodeId>,
25 affected_by_lights: Option<bool>,
26 casts_shadow: Option<bool>,
27 receives_shadows: Option<bool>,
28 wireframe: Option<bool>,
29 flip_normals: bool,
30 /// Smoothing angle of an enclosing `ReplaceNormals3D` that recomputes normals.
31 smooth_normals_deg: Option<f32>,
32 displace: Option<Displace3DSpec>,
33 cull_back: Option<bool>,
34 cull_front: Option<bool>,
35 unseen_by_cameras: Option<bool>,
36}
37
38fn splitmix64(mut x: u64) -> f32 {
39 x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
40 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
41 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
42 x ^= x >> 31;
43 // Uniform in [-0.5, +0.5]
44 ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5
45}
46
47/// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`,
48/// `ImagePlane3D`, `Shape3D`, `Text3D`, `LightAmbient`, `LightDirectional`, `LightPoint`,
49/// `LightSpot`, `ReplaceMaterial3D`, `Override3D`, `Duplicate3D`, `ReplaceNormals3D`, `Displace3D`).
50#[allow(clippy::too_many_arguments)]
51pub fn collect_scene(
52 comp: &Comp,
53 node_id: NodeId,
54 time: f64,
55 expr: &ExprEngine,
56 parent_xform: Mat4,
57 render_aspect: f32,
58 cameras: &mut Vec<CameraInstance>,
59 meshes: &mut Vec<MeshInstance>,
60 lights: &mut SceneLights,
61 depth: usize,
62) {
63 let mut visited = Vec::new();
64 collect_scene_with_nodes(
65 comp,
66 node_id,
67 time,
68 expr,
69 parent_xform,
70 render_aspect,
71 cameras,
72 meshes,
73 lights,
74 &mut visited,
75 depth,
76 );
77}
78
79/// Recursively traverses a Fusion 3D scene graph and records every visited 3D/material `NodeId`
80/// in `visited` so callers (`Renderer3D`) can include each visited node's `node_salt` in cache keys.
81#[allow(clippy::too_many_arguments)]
82pub fn collect_scene_with_nodes(
83 comp: &Comp,
84 node_id: NodeId,
85 time: f64,
86 expr: &ExprEngine,
87 parent_xform: Mat4,
88 render_aspect: f32,
89 cameras: &mut Vec<CameraInstance>,
90 meshes: &mut Vec<MeshInstance>,
91 lights: &mut SceneLights,
92 visited: &mut Vec<NodeId>,
93 depth: usize,
94) {
95 collect_scene_inner(
96 comp,
97 node_id,
98 time,
99 expr,
100 parent_xform,
101 render_aspect,
102 &SceneOverrides::default(),
103 cameras,
104 meshes,
105 lights,
106 visited,
107 depth,
108 );
109 // `Renderer3D` falls back to the first camera, so a spherical one there warps the scene.
110 if let Some((sph, cam_world)) = cameras.first().and_then(|c| Some((c.spherical?, c.world))) {
111 projection::warp_meshes(sph, cam_world, render_aspect, meshes, |m| infer_image_plane_aspect(comp, m.material_node, time, expr, render_aspect));
112 }
113}
114
115#[allow(clippy::too_many_arguments)]
116fn collect_scene_inner(
117 comp: &Comp,
118 node_id: NodeId,
119 time: f64,
120 expr: &ExprEngine,
121 parent_xform: Mat4,
122 render_aspect: f32,
123 ovr: &SceneOverrides,
124 cameras: &mut Vec<CameraInstance>,
125 meshes: &mut Vec<MeshInstance>,
126 lights: &mut SceneLights,
127 visited: &mut Vec<NodeId>,
128 depth: usize,
129) {
130 if depth > 32 || node_id.0 >= comp.nodes.len() || meshes.len() >= MAX_SCENE_MESHES {
131 return;
132 }
133 visited.push(node_id);
134 let node = comp.node(node_id);
135 if node.bypassed {
136 return;
137 }
138 let local = eval_transform3d(comp, node, time, expr);
139 let world = mat4_mul(parent_xform, local);
140
141 match node.kind.as_str() {
142 // Triangulate3D only matters to Fusion's own wireframe display; it passes the scene through,
143 // except that Fusion outputs nothing for a `Mode` beyond its single "Triangulate" entry.
144 "Merge3D" | "Transform3D" | "Triangulate3D" => {
145 if node.kind == "Triangulate3D" && comp.eval_number(node, "Mode", time, 0.0, expr).round() != 0.0 {
146 return;
147 }
148 let mut input_names: Vec<&String> = node
149 .inputs
150 .keys()
151 .filter(|k| k.starts_with("SceneInput"))
152 .collect();
153 // `SceneInput2` precedes `SceneInput10`.
154 input_names.sort_by_cached_key(|k| (k["SceneInput".len()..].parse::<u32>().unwrap_or(0), k.to_string()));
155 for in_name in input_names {
156 if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) {
157 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
158 }
159 }
160 }
161 "ReplaceMaterial3D" => {
162 let mut next_ovr = ovr.clone();
163 if comp.eval_number(node, "Enable", time, 1.0, expr) > 0.5 {
164 if let Some(mid) = node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)) {
165 next_ovr.material_override = Some(mid);
166 }
167 }
168 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
169 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
170 }
171 }
172 "Override3D" => {
173 let do_vis = comp.eval_number(node, "Visibility.DoVisible", time, 0.0, expr) > 0.5;
174 let is_vis = comp.eval_number(node, "Visibility.IsVisible", time, 1.0, expr) > 0.5;
175 if do_vis && !is_vis {
176 return;
177 }
178 let mut next_ovr = ovr.clone();
179 let flag_ovr = |do_k: &str, val_k: &str, def_val: f64| -> Option<bool> {
180 (comp.eval_number(node, do_k, time, 0.0, expr) > 0.5)
181 .then(|| comp.eval_number(node, val_k, time, def_val, expr) > 0.5)
182 };
183 if let Some(v) = flag_ovr("Visibility.DoIsUnseenByCameras", "Visibility.IsUnseenByCameras", 0.0) {
184 next_ovr.unseen_by_cameras = Some(v);
185 }
186 if let Some(v) = flag_ovr("Visibility.DoCullFrontFace", "Visibility.CullFrontFace", 0.0) {
187 next_ovr.cull_front = Some(v);
188 }
189 if let Some(v) = flag_ovr("Visibility.DoCullBackFace", "Visibility.CullBackFace", 0.0) {
190 next_ovr.cull_back = Some(v);
191 }
192 if let Some(v) = flag_ovr("Wireframe.DoWireframe", "Wireframe.Wireframe", 0.0) {
193 next_ovr.wireframe = Some(v);
194 }
195 if let Some(v) = flag_ovr("Lighting.DoAffectedByLights", "Lighting.IsAffectedByLights", 1.0) {
196 next_ovr.affected_by_lights = Some(v);
197 }
198 if let Some(v) = flag_ovr("Lighting.DoShadowCaster", "Lighting.IsShadowCaster", 1.0) {
199 next_ovr.casts_shadow = Some(v);
200 }
201 if let Some(v) = flag_ovr("Lighting.DoShadowReceiver", "Lighting.IsShadowReceiver", 1.0) {
202 next_ovr.receives_shadows = Some(v);
203 }
204 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
205 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
206 }
207 }
208 "ReplaceNormals3D" => {
209 let mut next_ovr = ovr.clone();
210 if comp.eval_number(node, "Normals.Flip", time, 0.0, expr) > 0.5 {
211 next_ovr.flip_normals = !next_ovr.flip_normals;
212 }
213 if comp.eval_number(node, "Normals.Recompute", time, 0.0, expr).round() as i32 == 0 {
214 next_ovr.smooth_normals_deg = Some(comp.eval_number(node, "Normals.SmoothingAngle", time, 45.0, expr) as f32);
215 }
216 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
217 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
218 }
219 }
220 "Weld3D" => {
221 let mut next_ovr = ovr.clone();
222 if comp.eval_number(node, "WeldNormals", time, 0.0, expr) > 0.5 {
223 next_ovr.smooth_normals_deg = Some(180.0);
224 }
225 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
226 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
227 }
228 }
229 "Fog3D" | "UVMap" | "CustomVertex3D" => {
230 let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {
231 return;
232 };
233 let mut child_meshes = Vec::new();
234 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, &mut child_meshes, lights, visited, depth + 1);
235 let aspect = |m: &MeshInstance| infer_image_plane_aspect(comp, m.material_node, time, expr, render_aspect);
236 if node.kind == "Fog3D" {
237 scene_ops::fog(comp, node, time, expr, &mut child_meshes);
238 } else if node.kind == "CustomVertex3D" {
239 custom_vertex::apply(comp, node, time, expr, &mut child_meshes, aspect);
240 } else if let Some(map) = scene_ops::UvMap::from_node(comp, node, time, expr) {
241 scene_ops::uv_map(&map, &mut child_meshes, aspect);
242 }
243 let remaining = MAX_SCENE_MESHES.saturating_sub(meshes.len());
244 meshes.extend(child_meshes.into_iter().take(remaining));
245 }
246 "PointCloud3D" => {
247 if let Some((shape, mat)) = scene_ops::point_cloud(comp, node, time, expr) {
248 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
249 }
250 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
251 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
252 }
253 }
254 "ExporterFBX" => {
255 if let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {
256 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
257 }
258 }
259 "Extrude3D" => {
260 let rings = node.connected_node("ShapeInput").and_then(|s| comp.find_node(s)).map(|id| extrude::shape_contours(comp, id, time, expr));
261 let (body, bevel) = extrude::extrude(&rings.unwrap_or_default(), &extrude::ExtrudeParams::from_node(comp, node, time, expr));
262 let mut material = |input: &str| {
263 let mat_node = ovr.material_override.or_else(|| node.connected_node(input).and_then(|s| comp.find_node(s)));
264 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
265 if !mat.has_material_shader {
266 apply_mtl_std(&mut mat, comp, node, "", time, expr);
267 // Without `OverrideColor` the diffuse colour is the shape's white.
268 if comp.eval_number(node, "OverrideColor", time, 0.0, expr) < 0.5 {
269 mat.diffuse_col[..3].fill(1.0);
270 }
271 }
272 mat
273 };
274 let bevel_mat = node.connected_node("BevelMaterialInput").is_some().then(|| material("BevelMaterialInput"));
275 let mut parts = vec![(body, material("MaterialInput"))];
276 match bevel_mat {
277 Some(mat) => parts.push((bevel, mat)),
278 None => parts[0].0.extend(bevel),
279 }
280 for (soup, mat) in parts.into_iter().filter(|(soup, _)| !soup.is_empty()) {
281 meshes.push(make_mesh_instance(world, ShapeKind::CustomMesh(Arc::new(soup)), mat, None, ovr));
282 }
283 }
284 "Locator3D" => {
285 if let Some((shape, mat)) = scene_ops::locator(comp, node, time, expr) {
286 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
287 }
288 // The locator's own transform does not reach its scene input.
289 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
290 collect_scene_inner(comp, src_id, time, expr, parent_xform, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
291 }
292 }
293 "Ribbon3D" => {
294 let mat_node = ovr.material_override.or_else(|| node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)));
295 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
296 if !mat.has_material_shader {
297 apply_mtl_std(&mut mat, comp, node, "", time, expr);
298 }
299 let (shape, mat) = scene_ops::ribbon(comp, node, time, expr, mat);
300 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
301 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
302 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
303 }
304 }
305 "Displace3D" => {
306 let mut next_ovr = ovr.clone();
307 if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {
308 let scale = comp.eval_number(node, "Scale", time, 0.1, expr) as f32;
309 let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32;
310 let channel = comp.eval_number(node, "Channel", time, 0.0, expr).round() as i32;
311 next_ovr.displace = Some(Displace3DSpec {
312 input_node: in_id,
313 scale,
314 bias,
315 channel,
316 });
317 }
318 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
319 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
320 }
321 }
322 "Bender3D" => {
323 let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {
324 return;
325 };
326 let mode = match node.static_str("Bender") {
327 Some("Taper") => BenderMode::Taper,
328 Some("Twist") => BenderMode::Twist,
329 Some("Shear") => BenderMode::Shear,
330 Some("Bend") => BenderMode::Bend,
331 _ => {
332 let idx = comp
333 .eval_number(
334 node,
335 "BenderType",
336 time,
337 comp.eval_number(node, "Bender", time, 0.0, expr),
338 expr,
339 )
340 .round() as i32;
341 match idx {
342 1 => BenderMode::Taper,
343 2 => BenderMode::Twist,
344 3 => BenderMode::Shear,
345 _ => BenderMode::Bend,
346 }
347 }
348 };
349 let params = Bender3DParams {
350 mode,
351 amount: comp.eval_number(node, "Amount", time, 0.0, expr) as f32,
352 axis: comp.eval_number(node, "Axis", time, 1.0, expr).round().clamp(0.0, 2.0) as u32,
353 angle_deg: comp.eval_number(node, "Angle", time, 0.0, expr) as f32,
354 center: comp.eval_number(node, "Center", time, 0.5, expr) as f32,
355 range_min: comp.eval_number(node, "RangeMin", time, 0.0, expr) as f32,
356 range_max: comp.eval_number(node, "RangeMax", time, 1.0, expr) as f32,
357 group: comp.eval_number(node, "Group", time, 0.0, expr) > 0.5,
358 };
359 let mut child_meshes = Vec::new();
360 collect_scene_inner(
361 comp,
362 src_id,
363 time,
364 expr,
365 world,
366 render_aspect,
367 ovr,
368 cameras,
369 &mut child_meshes,
370 lights,
371 visited,
372 depth + 1,
373 );
374 apply_bender_to_meshes(&mut child_meshes, world, &params, |m| {
375 infer_image_plane_aspect(comp, m.material_node, time, expr, render_aspect)
376 });
377 let remaining = MAX_SCENE_MESHES.saturating_sub(meshes.len());
378 meshes.extend(child_meshes.into_iter().take(remaining));
379 }
380 "Replicate3D" => {
381 let Some(dest_id) = node.connected_node("Destination").and_then(|s| comp.find_node(s)) else {
382 return;
383 };
384 let mut src_names: Vec<&String> = node
385 .inputs
386 .keys()
387 .filter(|k| k.starts_with("Input") && k["Input".len()..].chars().all(|c| c.is_ascii_digit()) && k.len() > "Input".len())
388 .collect();
389 src_names.sort_by_cached_key(|k| (k["Input".len()..].parse::<u32>().unwrap_or(0), k.to_string()));
390 let mut src_ids: Vec<NodeId> = src_names
391 .into_iter()
392 .filter_map(|k| node.connected_node(k).and_then(|s| comp.find_node(s)))
393 .collect();
394 if src_ids.is_empty() {
395 if let Some(sid) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
396 src_ids.push(sid);
397 }
398 }
399 if src_ids.is_empty() {
400 return;
401 }
402 let mut dest_meshes = Vec::new();
403 let mut dest_cams = Vec::new();
404 let mut dest_lights = SceneLights::default();
405 collect_scene_inner(
406 comp,
407 dest_id,
408 time,
409 expr,
410 mat4_identity(),
411 render_aspect,
412 ovr,
413 &mut dest_cams,
414 &mut dest_meshes,
415 &mut dest_lights,
416 visited,
417 depth + 1,
418 );
419 let mut source_templates = Vec::with_capacity(src_ids.len());
420 for sid in src_ids {
421 let mut tpl = Vec::new();
422 collect_scene_inner(
423 comp,
424 sid,
425 time,
426 expr,
427 mat4_identity(),
428 render_aspect,
429 ovr,
430 cameras,
431 &mut tpl,
432 lights,
433 visited,
434 depth + 1,
435 );
436 if !tpl.is_empty() {
437 source_templates.push(tpl);
438 }
439 }
440 if dest_meshes.is_empty() || source_templates.is_empty() {
441 return;
442 }
443 let step = comp.eval_number(node, "Step", time, 1.0, expr).round().max(1.0) as usize;
444 let remaining = MAX_SCENE_MESHES.saturating_sub(meshes.len());
445 let dest_points = extract_replicate_points(&dest_meshes, step, remaining);
446 let f = |k: &str, d: f64| comp.eval_number(node, k, time, d, expr) as f32;
447 let scale_lock = f("ScaleLock", 1.0) > 0.5;
448 let sx = f("Scale.X", 1.0);
449 let (sy, sz) = if scale_lock { (sx, sx) } else { (f("Scale.Y", 1.0), f("Scale.Z", 1.0)) };
450 let rot_order = node.static_str("RotationOrder").unwrap_or("XYZ");
451 let base_xform = trs_matrix(
452 [f("Translate.X", 0.0), f("Translate.Y", 0.0), f("Translate.Z", 0.0)],
453 [f("Rotate.X", 0.0), f("Rotate.Y", 0.0), f("Rotate.Z", 0.0)],
454 rot_order,
455 [sx, sy, sz],
456 [f("Pivot.X", 0.0), f("Pivot.Y", 0.0), f("Pivot.Z", 0.0)],
457 );
458 let j_scale_lock = f("JitterScaleLock", 1.0) > 0.5;
459 let jsx = f("JitterScale.X", 0.0);
460 let (jsy, jsz) = if j_scale_lock { (jsx, jsx) } else { (f("JitterScale.Y", 0.0), f("JitterScale.Z", 0.0)) };
461 let params = Replicate3DParams {
462 random_input: node.static_str("InputMode") == Some("Random"),
463 alignment: comp.eval_number(node, "Alignment", time, 0.0, expr).round() as i32,
464 base_xform,
465 random_seed: comp.eval_number(node, "RandomSeed", time, 0.0, expr).round().max(0.0) as u64,
466 jitter_prob: f("JitterProbability", 1.0).clamp(0.0, 1.0),
467 jitter_translate: [f("JitterTranslate.X", 0.0), f("JitterTranslate.Y", 0.0), f("JitterTranslate.Z", 0.0)],
468 jitter_rotate: [f("JitterRotate.X", 0.0), f("JitterRotate.Y", 0.0), f("JitterRotate.Z", 0.0)],
469 jitter_pivot: [f("JitterPivot.X", 0.0), f("JitterPivot.Y", 0.0), f("JitterPivot.Z", 0.0)],
470 jitter_scale: [jsx, jsy, jsz],
471 };
472 replicate_meshes(&dest_points, &source_templates, world, &params, meshes);
473 }
474 "Duplicate3D" => {
475 let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {
476 return;
477 };
478 let region_mode = node.static_str("RegionMode").unwrap_or("Ignore");
479 let region = node.static_str("Region").unwrap_or("AllRgn");
480 if region_mode == "NotInside" && region == "AllRgn" {
481 return;
482 }
483 let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32;
484 let last = comp.eval_number(node, "LastCopy", time, 2.0, expr).round() as i32;
485 let count = (i64::from(last) - i64::from(first)).clamp(0, 256) as i32;
486 if count == 0 {
487 return;
488 }
489 let dup_params = eval_duplicate3d_params(comp, node, time, expr);
490 let is_linear = node.static_str("TransformMethod") == Some("Linear");
491 let step = dup_params.matrix_for_step(1.0, false);
492
493 let copy_prob = comp.eval_number(node, "CopyProbability", time, 1.0, expr) as f32;
494 let seed = comp.eval_number(node, "RandomSeed", time, 0.0, expr).round() as u64;
495 let jtx = comp.eval_number(node, "JitterTranslate.X", time, 0.0, expr) as f32;
496 let jty = comp.eval_number(node, "JitterTranslate.Y", time, 0.0, expr) as f32;
497 let jtz = comp.eval_number(node, "JitterTranslate.Z", time, 0.0, expr) as f32;
498 let jrx = comp.eval_number(node, "JitterRotate.X", time, 0.0, expr) as f32;
499 let jry = comp.eval_number(node, "JitterRotate.Y", time, 0.0, expr) as f32;
500 let jrz = comp.eval_number(node, "JitterRotate.Z", time, 0.0, expr) as f32;
501 let j_scale_lock = comp.eval_number(node, "JitterScaleLock", time, 1.0, expr) > 0.5;
502 let jsx = comp.eval_number(node, "JitterScale.X", time, 0.0, expr) as f32;
503 let (jsy, jsz) = if j_scale_lock {
504 (jsx, jsx)
505 } else {
506 (
507 comp.eval_number(node, "JitterScale.Y", time, 0.0, expr) as f32,
508 comp.eval_number(node, "JitterScale.Z", time, 0.0, expr) as f32,
509 )
510 };
511 let has_jitter = (jtx.abs() + jty.abs() + jtz.abs()
512 + jrx.abs() + jry.abs() + jrz.abs()
513 + jsx.abs() + jsy.abs() + jsz.abs()) > 1e-5;
514
515 let mut acc = mat4_identity();
516 if !is_linear && first > 0 {
517 let mut exp = first as u32;
518 let mut base = step;
519 while exp > 0 {
520 if (exp & 1) != 0 {
521 acc = mat4_mul(acc, base);
522 }
523 exp >>= 1;
524 if exp > 0 {
525 base = mat4_mul(base, base);
526 }
527 }
528 }
529 for i in 0..count {
530 let copy_i64 = i64::from(first) + i64::from(i);
531 let copy_idx = copy_i64 as u64;
532 let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407));
533 if copy_prob < 0.9999 && (splitmix64(s ^ 13) + 0.5) > copy_prob {
534 if !is_linear {
535 acc = mat4_mul(acc, step);
536 }
537 continue;
538 }
539 let base_m = if is_linear {
540 dup_params.matrix_for_step(copy_i64 as f32, true)
541 } else {
542 acc
543 };
544 let mut m = mat4_mul(parent_xform, base_m);
545 // Fusion Duplicate3D leaves copy 0 unjittered.
546 if has_jitter && copy_idx > 0 {
547 let tx = splitmix64(s ^ 1) * jtx;
548 let ty = splitmix64(s ^ 2) * jty;
549 let tz = splitmix64(s ^ 3) * jtz;
550 let rx = (splitmix64(s ^ 4) * jrx).to_radians();
551 let ry = (splitmix64(s ^ 5) * jry).to_radians();
552 let rz = (splitmix64(s ^ 6) * jrz).to_radians();
553 let sx = (1.0 + splitmix64(s ^ 7) * jsx).max(1e-4);
554 let sy = (1.0 + splitmix64(s ^ 8) * jsy).max(1e-4);
555 let sz = (1.0 + splitmix64(s ^ 9) * jsz).max(1e-4);
556 let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx)));
557 let jm = mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz)));
558 m = mat4_mul(m, jm);
559 }
560 collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
561 if !is_linear {
562 acc = mat4_mul(acc, step);
563 }
564 }
565 }
566 "Camera3D" => {
567 let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32;
568 let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32;
569 // Fusion derives the vertical AoV from FLength (default 35mm) and the film-gate height;
570 // a serialized AoV is only an echo of that, so it is the fallback when neither FLength
571 // nor ApertureH is serialized (default Camera3D vertical AoV ~24.302°).
572 let fl_mm = if node.inputs.contains_key("FLength") {
573 Some(comp.eval_number(node, "FLength", time, 35.0, expr).max(0.5) as f32)
574 } else if node.inputs.contains_key("ApertureH") {
575 Some(35.0)
576 } else {
577 None
578 };
579 let aov_deg = match fl_mm {
580 Some(fl) => 2.0 * (ap_h * 25.4 * 0.5 / fl).atan().to_degrees(),
581 None => comp.eval_number(node, "AoV", time, 24.302, expr) as f32,
582 };
583 // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders)
584 let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height");
585 let gate_aspect = (ap_w / ap_h.max(1e-4)).max(1e-4);
586
587 let half_aov = (aov_deg.to_radians() * 0.5).tan();
588 let half_v = match gate_fit {
589 "Height" | "Stretch" => half_aov,
590 "Width" => half_aov * (gate_aspect / render_aspect.max(1e-4)),
591 "Outside" => half_aov * (gate_aspect / render_aspect.max(1e-4)).min(1.0),
592 _ => half_aov * (gate_aspect / render_aspect.max(1e-4)).max(1.0), // Inside (Fusion default!)
593 };
594 let vfov_rad = 2.0 * half_v.atan();
595 let orthographic = node.static_str("ProjectionType") == Some("Orthographic");
596 let (near, far) = if orthographic {
597 (
598 comp.eval_number(node, "OrthoNearClip", time, 0.0, expr) as f32,
599 comp.eval_number(node, "OrthoFarClip", time, 1000.0, expr) as f32,
600 )
601 } else {
602 (
603 comp.eval_number(node, "PerspNearClip", time, 0.1, expr).max(1e-4) as f32,
604 comp.eval_number(node, "PerspFarClip", time, 1000.0, expr) as f32,
605 )
606 };
607 cameras.push(CameraInstance {
608 name: node.name.clone(),
609 orthographic,
610 world,
611 vfov_rad,
612 near,
613 far,
614 spherical: None,
615 });
616 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
617 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
618 }
619 }
620 "SphericalCamera3D" => {
621 cameras.push(CameraInstance {
622 name: node.name.clone(),
623 orthographic: true,
624 world,
625 vfov_rad: std::f32::consts::FRAC_PI_2,
626 near: comp.eval_number(node, "PerspNearClip", time, 0.1, expr).max(1e-4) as f32,
627 far: comp.eval_number(node, "PerspFarClip", time, 1000.0, expr) as f32,
628 spherical: Some(projection::Spherical::from_node(node)),
629 });
630 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
631 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
632 }
633 }
634 "LightProjector" => {
635 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
636 if let Some(spot) = light_color(comp, node, time, expr).and_then(|c| projection::projector(comp, node, world, c, time, expr)) {
637 lights.spots.push(spot);
638 }
639 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
640 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
641 }
642 }
643 "LightAmbient" | "LightDome" => {
644 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
645 // An untextured dome lights nothing; a textured one's irradiance is approximated as a
646 // uniform ambient, exact for a constant white texture.
647 let lit = node.kind == "LightAmbient" || node.connected_node("DomeTexture").is_some();
648 if let Some(color) = light_color(comp, node, time, expr).filter(|_| lit) {
649 for (acc, c) in lights.ambient.iter_mut().zip(color) {
650 *acc += c;
651 }
652 }
653 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
654 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
655 }
656 }
657 "LightDirectional" => {
658 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
659 if let Some(color) = light_color(comp, node, time, expr) {
660 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!
661 let dx = world[8];
662 let dy = world[9];
663 let dz = world[10];
664 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
665 lights.dirs.push(DirLight { to_light: [dx / len, dy / len, dz / len], color });
666 }
667 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
668 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
669 }
670 }
671 "LightPoint" => {
672 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
673 if let Some(color) = light_color(comp, node, time, expr) {
674 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
675 lights.points.push(PointLight {
676 pos: [world[12], world[13], world[14]],
677 color,
678 decay_type,
679 decay_rate: 1.0,
680 shadow_density: (comp.eval_number(node, "ShadowLightInputs3D.ShadowsEnabled", time, 0.0, expr) > 0.5)
681 .then(|| comp.eval_number(node, "ShadowLightInputs3D.ShadowDensity", time, 0.5, expr).clamp(0.0, 1.0) as f32),
682 });
683 }
684 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
685 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
686 }
687 }
688 "LightSpot" => {
689 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
690 if let Some(color) = light_color(comp, node, time, expr) {
691 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;
692 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;
693 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
694 // SpotLight shines along -Z in local space
695 let dx = -world[8];
696 let dy = -world[9];
697 let dz = -world[10];
698 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
699 let half_cone = (cone_deg * 0.5).max(0.5);
700 let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5);
701 let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg);
702 lights.spots.push(SpotLight {
703 pos: [world[12], world[13], world[14]],
704 dir: [dx / len, dy / len, dz / len],
705 color,
706 cos_inner: inner_deg.to_radians().cos(),
707 cos_outer: outer_deg.to_radians().cos(),
708 decay_type,
709 });
710 }
711 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
712 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
713 }
714 }
715 "ImagePlane3D" => {
716 let Some(own) = surface_scope(comp, node, "SurfacePlaneInputs", ovr, time, expr) else { return };
717 let mat_node = ovr.material_override.or_else(|| {
718 node.connected_node("MaterialInput")
719 .or_else(|| node.connected_node("SceneInput"))
720 .and_then(|s| comp.find_node(s))
721 });
722 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
723 if !mat.has_material_shader {
724 mat.receives_shadows = comp.eval_number(node, "MtlStdInputs.ReceivesShadows", time, 1.0, expr) > 0.5;
725 }
726 meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own));
727 }
728 "Shape3D" => {
729 if let Some(own) = surface_scope(comp, node, node.static_str("Shape").unwrap_or("SurfacePlaneInputs"), ovr, time, expr) {
730 let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs");
731 let shape = match shape_name {
732 "SurfaceSphereInputs" => ShapeKind::Sphere {
733 // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00)
734 radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32,
735 sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,
736 sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 20.0, expr).round() as u32,
737 },
738 "SurfaceCylinderInputs" => {
739 let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32;
740 let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32;
741 ShapeKind::Cylinder {
742 radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 1.0, expr) as f32,
743 height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 2.0, expr) as f32,
744 start_sweep_deg: start_sw,
745 end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw },
746 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,
747 sub_height: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelHeight", time, 1.0, expr).round() as u32,
748 top_cap: comp.eval_number(node, "SurfaceCylinderInputs.TopCap", time, 0.0, expr) > 0.5,
749 bottom_cap: comp.eval_number(node, "SurfaceCylinderInputs.BottomCap", time, 0.0, expr) > 0.5,
750 }
751 }
752 "SurfaceConeInputs" => {
753 let f = |k: &str, d: f64| comp.eval_number(node, &format!("SurfaceConeInputs.{k}"), time, d, expr);
754 let sweep = [f("StartSweep", 0.0) as f32, f("EndSweep", 360.0) as f32];
755 custom_shape(build_cone(
756 f("Radius", 1.0) as f32,
757 f("Height", 2.0) as f32,
758 sweep,
759 f("SubdivisionLevelBase", 20.0).round() as u32,
760 f("SubdivisionLevelHeight", 1.0).round() as u32,
761 f("BottomCap", 0.0) > 0.5,
762 ))
763 }
764 "SurfaceTorusInputs" => {
765 let f = |k: &str, d: f64| comp.eval_number(node, &format!("SurfaceTorusInputs.{k}"), time, d, expr);
766 let sweep = [f("StartSweep", 0.0) as f32, f("EndSweep", 360.0) as f32];
767 custom_shape(build_torus(
768 f("Radius", 1.0) as f32,
769 f("Section", 0.5) as f32,
770 sweep,
771 f("SubdivisionLevelBase", 20.0).round() as u32,
772 f("SubdivisionLevelHeight", 20.0).round() as u32,
773 ))
774 }
775 "SurfaceIcoInputs" => {
776 let f = |k: &str, d: f64| comp.eval_number(node, &format!("SurfaceIcoInputs.{k}"), time, d, expr);
777 custom_shape(build_icosahedron(f("Size", 1.0) as f32, f("SubdivisionLevel", 0.0).round() as u32))
778 }
779 "SurfaceCubeInputs" => ShapeKind::Cube {
780 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32,
781 sub: cube_subdivisions(comp, node, time, expr),
782 faces: 0b11_1111,
783 },
784 _ => {
785 // Fusion's plane is square: Height and SubdivisionHeight follow Width.
786 let sub = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, 10.0, expr).round() as u32;
787 let width = comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32;
788 ShapeKind::Plane { width, height: width, sub_w: sub, sub_h: sub }
789 }
790 };
791 let mat_node = ovr.material_override.or_else(|| {
792 node.connected_node("MaterialInput")
793 .and_then(|s| comp.find_node(s))
794 });
795 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
796 if !mat.has_material_shader {
797 apply_mtl_std(&mut mat, comp, node, "", time, expr);
798 }
799 mat.fx.wireframe = comp.eval_number(node, &format!("{shape_name}.Wireframe"), time, 0.0, expr) > 0.5;
800 meshes.push(make_mesh_instance(world, shape, mat, None, &own));
801 }
802 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
803 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
804 }
805 }
806 "Cube3D" => {
807 if let Some(own) = surface_scope(comp, node, "SurfaceCubeInputs", ovr, time, expr) {
808 // Fusion's Cube3D only honors Width (all edges) and takes one material per face.
809 let width = comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32;
810 let wireframe = comp.eval_number(node, "SurfaceCubeInputs.Wireframe", time, 0.0, expr) > 0.5;
811 let sub = cube_subdivisions(comp, node, time, expr);
812 let mut groups: Vec<(Option<NodeId>, ResolvedMaterial, u8)> = Vec::new();
813 for (i, face) in CUBE_FACES.iter().enumerate() {
814 let mat_node = ovr.material_override.or_else(|| {
815 node.connected_node(&format!("{face}MaterialInput"))
816 .and_then(|s| comp.find_node(s))
817 });
818 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
819 if !mat.has_material_shader {
820 apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr);
821 }
822 mat.fx.wireframe = wireframe;
823 match groups.iter_mut().find(|(n, m, _)| *n == mat_node && *m == mat) {
824 Some((_, _, mask)) => *mask |= 1 << i,
825 None => groups.push((mat_node, mat, 1 << i)),
826 }
827 }
828 for (_, mat, faces) in groups {
829 meshes.push(make_mesh_instance(world, ShapeKind::Cube { width, sub, faces }, mat, None, &own));
830 }
831 }
832 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
833 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
834 }
835 }
836 "SurfaceAlembicMesh" => {
837 if let Some(own) = surface_scope(comp, node, "", ovr, time, expr) {
838 let fps = comp.eval_number(node, "SamplingRate", time, 24.0, expr).max(1e-3);
839 let path = node.static_str("Filename").unwrap_or("");
840 if let Some(verts) = alembic::load_alembic_cached(path, comp.path.as_deref(), node.static_str("ObjName").unwrap_or(""), time / fps) {
841 let mat_node = ovr.material_override.or_else(|| node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)));
842 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
843 if !mat.has_material_shader {
844 apply_mtl_std(&mut mat, comp, node, "", time, expr);
845 }
846 mat.fx.wireframe = comp.eval_number(node, "Wireframe", time, 0.0, expr) > 0.5;
847 meshes.push(make_mesh_instance(world, ShapeKind::CustomMesh(verts), mat, None, &own));
848 }
849 }
850 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
851 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
852 }
853 }
854 "SurfaceFBXMesh" => {
855 if let Some(own) = surface_scope(comp, node, "SurfaceFBXInputs", ovr, time, expr) {
856 let import_file = node.static_str("ImportFile").unwrap_or("");
857 let obj_name = node.static_str("ObjName");
858 let scale_units = comp.eval_number(node, "ScaleFileUnitsBy", time, 1.0, expr) as f32;
859 let verts = load_mesh_cached(import_file, comp.path.as_deref(), obj_name, scale_units);
860 let shape = ShapeKind::CustomMesh(verts);
861 let mat_node = ovr.material_override.or_else(|| {
862 node.connected_node("MaterialInput")
863 .or_else(|| {
864 let mut slots: Vec<&String> = node
865 .inputs
866 .keys()
867 .filter(|k| k.starts_with("Materials."))
868 .collect();
869 slots.sort();
870 slots.into_iter().find_map(|k| node.connected_node(k))
871 })
872 .and_then(|s| comp.find_node(s))
873 });
874 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
875 if !mat.has_material_shader {
876 apply_mtl_std(&mut mat, comp, node, "", time, expr);
877 }
878 meshes.push(make_mesh_instance(world, shape, mat, None, &own));
879 }
880 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
881 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
882 }
883 }
884 "Text3D" => {
885 let ext_depth = comp.eval_number(node, "Extrusion.ExtrusionDepth", time, 0.0, expr) as f32;
886 let mat_node = ovr.material_override.or_else(|| {
887 node.connected_node("MaterialInput")
888 .and_then(|s| comp.find_node(s))
889 });
890 let mut mat = resolve_material(comp, mat_node, time, expr, visited);
891 if mat_node.is_none() {
892 mat.diffuse_col = [1.0, 1.0, 1.0, 1.0];
893 }
894 let line_sx = comp.eval_number(node, "LineSizeX", time, 1.0, expr) as f32;
895 let line_sy = comp.eval_number(node, "LineSizeY", time, 1.0, expr) as f32;
896 let text_world = if (line_sx - 1.0).abs() > 1e-5 || (line_sy - 1.0).abs() > 1e-5 {
897 let lp = comp.eval_point(node, "LinePivot", time, [0.0, 0.0], expr);
898 let (px, py) = (lp[0] as f32, lp[1] as f32);
899 let lxf = mat4_mul(mat4_translate(px, py, 0.0), mat4_mul(mat4_scale(line_sx, line_sy, 1.0), mat4_translate(-px, -py, 0.0)));
900 mat4_mul(world, lxf)
901 } else {
902 world
903 };
904 // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate)
905 let shape = ShapeKind::TextPlate {
906 width: 4.0,
907 height: 2.0,
908 depth: ext_depth,
909 slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 },
910 };
911 meshes.push(make_mesh_instance(text_world, shape, mat, Some(Text3DSpec { node_id }), ovr));
912 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
913 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
914 }
915 }
916 "MacroOperator" | "GroupOperator" => {
917 if let Some(out_id) = node.macro_output {
918 collect_scene_inner(comp, out_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
919 }
920 }
921 _ => {}
922 }
923}
924
925#[derive(PartialEq)]
926pub(super) struct ResolvedMaterial {
927 pub(super) tex_node: Option<NodeId>,
928 pub(super) bump_node: Option<NodeId>,
929 pub(super) diffuse_col: [f32; 4],
930 pub(super) specular_col: [f32; 3],
931 pub(super) specular_intensity: f32,
932 pub(super) specular_exponent: f32,
933 pub(super) fx: MaterialFx,
934 /// A bare texture operator used as a surface's material renders flat, ignoring lights.
935 pub(super) unlit: bool,
936 pub(super) receives_shadows: bool,
937 /// True when resolved from a shader material node (`MtlBlinn` / `MtlPhong` / `MtlCookTorrance`),
938 /// which owns diffuse/specular rather than inheriting the geometry node's `MtlStdInputs`.
939 pub(super) has_material_shader: bool,
940}
941
942impl Default for ResolvedMaterial {
943 fn default() -> Self {
944 Self {
945 tex_node: None,
946 bump_node: None,
947 diffuse_col: [1.0, 1.0, 1.0, 1.0],
948 specular_col: [1.0, 1.0, 1.0],
949 specular_intensity: 1.0,
950 specular_exponent: 50.0,
951 fx: MaterialFx::default(),
952 unlit: false,
953 receives_shadows: true,
954 has_material_shader: false,
955 }
956 }
957}
958
959/// Infers the 2D texture aspect ratio for an `ImagePlane3D` material input when baking meshes
960/// during 3D scene collection (e.g. for `Bender3D`), walking upstream inputs for explicit
961/// `Width`/`Height` before falling back to `render_aspect` or `16/9`.
962fn infer_image_plane_aspect(
963 comp: &Comp,
964 mat_node: Option<NodeId>,
965 time: f64,
966 expr: &ExprEngine,
967 render_aspect: f32,
968) -> f32 {
969 let mut cur = mat_node;
970 for _ in 0..16 {
971 let Some(nid) = cur else { break };
972 let n = comp.node(nid);
973 if n.inputs.contains_key("Width") || n.inputs.contains_key("Height") {
974 let w = comp.eval_number(n, "Width", time, comp.width as f64, expr);
975 let h = comp.eval_number(n, "Height", time, comp.height as f64, expr);
976 if w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0 {
977 return (w / h) as f32;
978 }
979 }
980 cur = ["Input", "Background", "Image", "Source"]
981 .iter()
982 .find_map(|p| n.connected_node(p).and_then(|s| comp.find_node(s)));
983 }
984 if render_aspect.is_finite() && render_aspect > 1e-4 {
985 render_aspect
986 } else {
987 16.0 / 9.0
988 }
989}
990
991fn make_mesh_instance(
992 world: Mat4,
993 shape: ShapeKind,
994 mat: ResolvedMaterial,
995 text3d: Option<Text3DSpec>,
996 ovr: &SceneOverrides,
997) -> MeshInstance {
998 let shape = match (ovr.smooth_normals_deg, &shape) {
999 (Some(deg), s) if !matches!(s, ShapeKind::ImagePlane | ShapeKind::TextPlate { .. }) => ShapeKind::CustomMesh(Arc::new(smooth_normals(build_shape_mesh(s, 1.0), deg))),
1000 _ => shape,
1001 };
1002 let unseen = ovr.unseen_by_cameras.unwrap_or(false);
1003 let mut sfx = mat.fx.sfx;
1004 if ovr.affected_by_lights == Some(false) {
1005 sfx.layer[2] = 0.0;
1006 }
1007 MeshInstance {
1008 world,
1009 shape: ShapeKind::WithMaterialFx {
1010 inner: Box::new(shape),
1011 fx: MaterialFx {
1012 wireframe: ovr.wireframe.unwrap_or(mat.fx.wireframe),
1013 cull_back: ovr.cull_back.unwrap_or(false) || unseen,
1014 cull_front: ovr.cull_front.unwrap_or(false) || unseen,
1015 sfx,
1016 ..mat.fx
1017 },
1018 },
1019 material_node: mat.tex_node,
1020 bump_node: mat.bump_node,
1021 text3d,
1022 diffuse_col: mat.diffuse_col,
1023 specular_col: mat.specular_col,
1024 specular_intensity: mat.specular_intensity,
1025 specular_exponent: mat.specular_exponent,
1026 affected_by_lights: !mat.unlit && ovr.affected_by_lights.unwrap_or(true),
1027 casts_shadow: ovr.casts_shadow.unwrap_or(true),
1028 receives_shadows: ovr.receives_shadows.unwrap_or(mat.receives_shadows),
1029 flip_normals: ovr.flip_normals,
1030 displace: ovr.displace.clone(),
1031 }
1032}
1033
1034/// Applies a surface's own `<group>.Visibility.*` / `<group>.Lighting.IsAffectedByLights`
1035/// inputs on top of inherited overrides; `None` when the surface is hidden.
1036fn surface_scope(
1037 comp: &Comp,
1038 node: &Node,
1039 group: &str,
1040 ovr: &SceneOverrides,
1041 time: f64,
1042 expr: &ExprEngine,
1043) -> Option<SceneOverrides> {
1044 let key = |k: &str| if group.is_empty() { k.to_string() } else { format!("{group}.{k}") };
1045 let flag = |k: &str, d: f64| comp.eval_number(node, &key(k), time, d, expr) > 0.5;
1046 let unseen = ovr.unseen_by_cameras.unwrap_or_else(|| flag("Visibility.IsUnseenByCameras", 0.0));
1047 flag("Visibility.IsVisible", 1.0).then(|| SceneOverrides {
1048 affected_by_lights: ovr.affected_by_lights.or(Some(flag("Lighting.IsAffectedByLights", 1.0))),
1049 casts_shadow: ovr.casts_shadow.or(Some(flag("Lighting.IsShadowCaster", 1.0))),
1050 receives_shadows: ovr.receives_shadows,
1051 // Unseen-by-cameras surfaces skip the camera pass but still cast shadows.
1052 cull_back: Some(ovr.cull_back.unwrap_or_else(|| flag("Visibility.CullBackFace", 0.0)) || unseen),
1053 cull_front: Some(ovr.cull_front.unwrap_or_else(|| flag("Visibility.CullFrontFace", 0.0)) || unseen),
1054 unseen_by_cameras: Some(unseen),
1055 ..ovr.clone()
1056 })
1057}
1058
1059/// `Intensity * RGB` of a light, or `None` when it is disabled or contributes nothing.
1060fn light_color(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option<[f32; 3]> {
1061 if comp.eval_number(node, "Enabled", time, 1.0, expr) < 0.5 {
1062 return None;
1063 }
1064 let intensity = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
1065 let color = ["Red", "Green", "Blue"].map(|k| comp.eval_number(node, k, time, 1.0, expr) as f32 * intensity);
1066 (color != [0.0; 3]).then_some(color)
1067}
1068
1069fn custom_shape(mesh: (Vec<Vertex3D>, Vec<u32>)) -> ShapeKind {
1070 ShapeKind::CustomMesh(Arc::new(triangle_soup(mesh)))
1071}
1072
1073/// Cells per cube edge; Fusion's cube keeps all three subdivision counts equal.
1074fn cube_subdivisions(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> u32 {
1075 comp.eval_number(node, "SurfaceCubeInputs.SubdivisionWidth", time, 10.0, expr).round() as u32
1076}
1077
1078/// Reads the built-in `MtlStdInputs` material (diffuse and Blinn specular) under an optional
1079/// per-face `prefix` such as `"Front."` into `mat`.
1080fn apply_mtl_std(mat: &mut ResolvedMaterial, comp: &Comp, node: &Node, prefix: &str, time: f64, expr: &ExprEngine) {
1081 let f = |k: &str, d: f64| comp.eval_number(node, &format!("{prefix}MtlStdInputs.{k}"), time, d, expr) as f32;
1082 mat.diffuse_col = [f("Diffuse.Color.Red", 1.0), f("Diffuse.Color.Green", 1.0), f("Diffuse.Color.Blue", 1.0), f("Diffuse.Opacity", 1.0)];
1083 mat.fx.diffuse_color_alpha = f("Diffuse.Color.Alpha", 1.0).clamp(0.0, 1.0);
1084 mat.specular_col = [f("Specular.Color.Red", 1.0), f("Specular.Color.Green", 1.0), f("Specular.Color.Blue", 1.0)];
1085 mat.specular_intensity = f("Specular.Intensity", 1.0).clamp(0.0, 4.0);
1086 mat.specular_exponent = f("Specular.Exponent", 50.0).max(1.0);
1087 mat.receives_shadows = f("ReceivesShadows", 1.0) > 0.5;
1088 if f("ReceivesLighting", 1.0) < 0.5 {
1089 mat.unlit = true;
1090 mat.fx.per_light_unlit = true;
1091 }
1092 if f("EnablePBRMaterial", 0.0) > 0.5 {
1093 mat.fx.spec_model = SpecModel::Pbr;
1094 }
1095}
1096
1097fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option<u32> {
1098 if let Some(s) = node.static_str("WrapMode") {
1099 return Some(match s {
1100 "Wrap" | "Repeat" => 1,
1101 "Mirror" => 2,
1102 _ => 0,
1103 });
1104 }
1105 if node.inputs.contains_key("WrapMode") {
1106 let v = comp.eval_number(node, "WrapMode", time, 0.0, expr).round() as i32;
1107 return Some(match v {
1108 1 => 1,
1109 2 => 2,
1110 _ => 0,
1111 });
1112 }
1113 None
1114}
1115
1116/// Mesh-UV -> texture-UV map for a UVW content transform `m` (V up, W dropped when sampling).
1117/// `m` moves the content, so sampling applies its inverse; `invert` swaps the two.
1118pub(super) fn texture_transform_uv(m: Mat4, invert: bool) -> UvAffine {
1119 let sampling = if invert { m } else { mat4_inverse(m) };
1120 let sample = |uv: [f32; 2]| {
1121 let (x, y) = (uv[0], 1.0 - uv[1]);
1122 [
1123 sampling[0] * x + sampling[4] * y + sampling[12],
1124 1.0 - (sampling[1] * x + sampling[5] * y + sampling[13]),
1125 ]
1126 };
1127 let (o, eu, ev) = (sample([0.0, 0.0]), sample([1.0, 0.0]), sample([0.0, 1.0]));
1128 UvAffine { m: [eu[0] - o[0], eu[1] - o[1], ev[0] - o[0], ev[1] - o[1]], t: o }
1129}
1130
1131/// Resolves a 3D material input (`Texture2DOperator`, `TextureTransformOperator`, `BumpMap`,
1132/// `MtlBlinn`, `MtlCookTorrance`, `MtlPhong`, or a direct 2D image node).
1133fn resolve_material(
1134 comp: &Comp,
1135 mat_node: Option<NodeId>,
1136 time: f64,
1137 expr: &ExprEngine,
1138 visited: &mut Vec<NodeId>,
1139) -> ResolvedMaterial {
1140 resolve_material_inner(comp, mat_node, time, expr, visited, 0)
1141}
1142
1143fn resolve_material_inner(
1144 comp: &Comp,
1145 mat_node: Option<NodeId>,
1146 time: f64,
1147 expr: &ExprEngine,
1148 visited: &mut Vec<NodeId>,
1149 depth: usize,
1150) -> ResolvedMaterial {
1151 let default_mat = ResolvedMaterial::default();
1152 if depth > 16 {
1153 return default_mat;
1154 }
1155 let Some(mid) = mat_node else {
1156 return default_mat;
1157 };
1158 visited.push(mid);
1159 let n = comp.node(mid);
1160 match n.kind.as_str() {
1161 "Texture2DOperator" => {
1162 let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s));
1163 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
1164 ResolvedMaterial {
1165 tex_node: tex_src,
1166 fx: MaterialFx {
1167 uv: texture_transform_uv(
1168 trs_matrix([f("UOffset", 0.0), f("VOffset", 0.0), 0.0], [0.0; 3], "XYZ", [f("UScale", 1.0), f("VScale", 1.0), 1.0], [0.0; 3]),
1169 false,
1170 ),
1171 uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0),
1172 ..default_mat.fx
1173 },
1174 unlit: true,
1175 ..default_mat
1176 }
1177 }
1178 "TextureTransformOperator" => {
1179 let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s));
1180 let mut mat = resolve_material_inner(comp, inner_id, time, expr, visited, depth + 1);
1181 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
1182 let uvw = |prefix: &str, d: f64| ["U", "V", "W"].map(|a| f(&format!("{prefix}.{a}"), d));
1183 let order = n.static_str("Rotation.RotOrder").unwrap_or("UVW").replace('U', "X").replace('V', "Y").replace('W', "Z");
1184 let m = trs_matrix(uvw("Translation", 0.0), uvw("Rotation", 0.0), &order, uvw("Scale", 1.0), uvw("Pivot", 0.0));
1185 let xf = texture_transform_uv(m, f("InvertTransform", 0.0) > 0.5);
1186 mat.fx.uv = xf.then(&mat.fx.uv);
1187 if mat.bump_node.is_some() {
1188 mat.fx.bump_uv = xf.then(&mat.fx.bump_uv);
1189 }
1190 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {
1191 mat.fx.uv_wrap = w;
1192 if mat.bump_node.is_some() {
1193 mat.fx.bump_wrap = w;
1194 }
1195 }
1196 mat
1197 }
1198 "BumpMap" => {
1199 let src = n.connected_node("Input").and_then(|s| comp.find_node(s));
1200 let height_scale = comp.eval_number(n, "HeightScale", time, 1.0, expr) as f32;
1201 let clamp_z = comp.eval_number(n, "ClampNormalZ", time, 0.0, expr).clamp(0.0, 1.0) as f32;
1202 let bump_mode = if let Some(s) = n.static_str("SourceImageType") {
1203 if s.eq_ignore_ascii_case("NormalMap") || s.eq_ignore_ascii_case("Bumpmap") || s == "1" { 1 } else { 0 }
1204 } else {
1205 comp.eval_number(n, "SourceImageType", time, 0.0, expr)
1206 .round()
1207 .clamp(0.0, 1.0) as u32
1208 };
1209 let bump_channel = match n.static_str("SourceChannel").unwrap_or("Luminance") {
1210 "Average" => 1,
1211 "Max" => 2,
1212 "Min" => 3,
1213 "Red" => 4,
1214 "Green" => 5,
1215 "Blue" => 6,
1216 "Alpha" => 7,
1217 _ => 0,
1218 };
1219 let wrap = parse_wrap_mode(comp, n, time, expr).unwrap_or(0);
1220 ResolvedMaterial {
1221 tex_node: src,
1222 bump_node: src,
1223 fx: MaterialFx {
1224 uv_wrap: wrap,
1225 bump_scale: height_scale,
1226 bump_mode,
1227 bump_wrap: wrap,
1228 bump_clamp_z: clamp_z,
1229 bump_channel,
1230 ..default_mat.fx
1231 },
1232 ..default_mat
1233 }
1234 }
1235 "SphereMap" => textures::sphere_map(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)),
1236 "CubeMap" => textures::cube_map(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)),
1237 "TexGradient" => textures::tex_gradient(comp, n, time, expr),
1238 "FastNoiseTexture3D" => textures::fast_noise(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)),
1239 "MtlMerge3D" => materials::merge3d(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)),
1240 "MtlStereoMix3D" => materials::stereo_mix(comp, n, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)),
1241 "MtlPBRUber" => materials::pbr_uber(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)),
1242 "FalloffOperator" => materials::falloff(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)),
1243 "ReliefMap" => relief::relief_map(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)),
1244 "ReliefMapData" => relief::relief_data(comp, n, time, expr),
1245 "Texture3DTool" => relief::texture3d(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)),
1246 // Without projectors in the scene there is nothing to catch.
1247 "TexCatcher" => materials::flat([0.0; 4]),
1248 "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" | "MtlWard" => {
1249 let diff_in = n
1250 .connected_node("Diffuse.Color.Material")
1251 .or_else(|| n.connected_node("MaterialInput"))
1252 .and_then(|s| comp.find_node(s));
1253 let diff_mat = resolve_material_inner(comp, diff_in, time, expr, visited, depth + 1);
1254 let bump_in = n
1255 .connected_node("Bumpmap.Material")
1256 .and_then(|s| comp.find_node(s));
1257 let bump_mat = bump_in.map(|bid| resolve_material_inner(comp, Some(bid), time, expr, visited, depth + 1));
1258
1259 let col = [
1260 comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32,
1261 comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32,
1262 comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32,
1263 comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32,
1264 ];
1265 let col_alpha = comp.eval_number(n, "Diffuse.Color.Alpha", time, 1.0, expr).clamp(0.0, 1.0) as f32;
1266 let spec_col = [
1267 comp.eval_number(n, "Specular.Color.Red", time, 1.0, expr) as f32,
1268 comp.eval_number(n, "Specular.Color.Green", time, 1.0, expr) as f32,
1269 comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32,
1270 ];
1271 let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32;
1272 let (spec_exp, spec_model, refractive_index, do_fresnel, ward_spread_v) = match n.kind.as_str() {
1273 "MtlCookTorrance" => (
1274 comp.eval_number(n, "Specular.Roughness", time, 0.6, expr).clamp(0.05, 1.0) as f32,
1275 SpecModel::CookTorrance,
1276 comp.eval_number(n, "Specular.RefractiveIndex", time, 2.0, expr).max(1.0) as f32,
1277 comp.eval_number(n, "Specular.DoFresnel", time, 1.0, expr) > 0.5,
1278 0.16,
1279 ),
1280 "MtlWard" => (
1281 comp.eval_number(n, "Specular.SpreadU", time, 0.05, expr).clamp(0.0001, 2.0) as f32,
1282 SpecModel::Ward,
1283 2.0,
1284 true,
1285 comp.eval_number(n, "Specular.SpreadV", time, 0.16, expr).clamp(0.0001, 2.0) as f32,
1286 ),
1287 "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong, 2.0, true, 0.16),
1288 _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn, 2.0, true, 0.16),
1289 };
1290
1291 let spec_model = if comp.eval_number(n, "EnablePBRMaterial", time, 0.0, expr) > 0.5 { SpecModel::Pbr } else { spec_model };
1292 let lit = comp.eval_number(n, "ReceivesLighting", time, 1.0, expr) > 0.5;
1293 let mut tex_node = diff_mat.tex_node;
1294 let mut bump_node = diff_mat.bump_node;
1295 let mut fx = MaterialFx {
1296 spec_model,
1297 per_light_unlit: !lit,
1298 diffuse_color_alpha: col_alpha,
1299 refractive_index,
1300 do_fresnel,
1301 ward_spread_v,
1302 ..diff_mat.fx
1303 };
1304 if let Some(bm) = bump_mat {
1305 bump_node = bm.bump_node.or(bm.tex_node);
1306 if tex_node.is_none() {
1307 tex_node = bump_node;
1308 fx = MaterialFx {
1309 bump_only: true,
1310 spec_model,
1311 per_light_unlit: !lit,
1312 diffuse_color_alpha: col_alpha,
1313 refractive_index,
1314 do_fresnel,
1315 ward_spread_v,
1316 ..bm.fx
1317 };
1318 }
1319 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };
1320 fx.bump_mode = bm.fx.bump_mode;
1321 fx.bump_uv = bm.fx.uv;
1322 fx.bump_wrap = bm.fx.uv_wrap;
1323 fx.bump_clamp_z = bm.fx.bump_clamp_z;
1324 fx.bump_channel = bm.fx.bump_channel;
1325 }
1326
1327 ResolvedMaterial {
1328 tex_node,
1329 bump_node,
1330 diffuse_col: col,
1331 specular_col: spec_col,
1332 specular_intensity: spec_int.clamp(0.0, 4.0),
1333 specular_exponent: spec_exp,
1334 fx,
1335 unlit: !lit,
1336 receives_shadows: comp.eval_number(n, "ReceivesShadows", time, 1.0, expr) > 0.5,
1337 has_material_shader: true,
1338 }
1339 }
1340 "MtlReflect" => {
1341 let input = |k: &str| n.connected_node(k).and_then(|s| comp.find_node(s));
1342 let has_bg = input("BackgroundMaterial").is_some();
1343 let bg_mat = match input("BackgroundMaterial") {
1344 Some(id) => resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1),
1345 None => ResolvedMaterial { diffuse_col: [0.0; 4], unlit: true, ..default_mat },
1346 };
1347 let mut tex_node = bg_mat.tex_node.filter(|_| !bg_mat.fx.bump_only);
1348 let mut bump_node = bg_mat.bump_node;
1349 let mut fx = MaterialFx { bump_only: false, ..bg_mat.fx };
1350 if let Some(bm) = input("Bumpmap.Material").map(|id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)) {
1351 bump_node = bm.bump_node.or(bm.tex_node);
1352 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };
1353 fx.bump_mode = bm.fx.bump_mode;
1354 fx.bump_uv = bm.fx.uv;
1355 fx.bump_wrap = bm.fx.uv_wrap;
1356 fx.bump_clamp_z = bm.fx.bump_clamp_z;
1357 fx.bump_channel = bm.fx.bump_channel;
1358 }
1359 let mut mat = ResolvedMaterial { tex_node, bump_node, fx, has_material_shader: true, ..bg_mat };
1360 // Without a reflection material Fusion renders the background material alone.
1361 let Some(rm) = input("Reflection.Color.Material").map(|id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)) else {
1362 return mat;
1363 };
1364 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
1365 if let Some(env) = rm.tex_node {
1366 if tex_node.is_none() {
1367 tex_node = Some(env);
1368 mat.fx.env_tex_slot = 1;
1369 } else {
1370 bump_node = Some(env);
1371 mat.fx.env_tex_slot = 2;
1372 }
1373 }
1374 // A SphereMap/CubeMap reflects along directions; a plain image is laid on by mesh UV.
1375 if rm.fx.env_mode == 1 {
1376 mat.fx.env_rot = rm.fx.env_rot;
1377 mat.fx.env_map_mode = rm.fx.env_map_mode;
1378 mat.fx.sfx.env = rm.fx.sfx.env;
1379 } else {
1380 mat.fx.env_map_mode = 5;
1381 }
1382 mat.fx.env_mode = 2;
1383 mat.fx.refl_strength_var = f("Reflection.StrengthVariability", 1.0).round().clamp(0.0, 1.0) as u32;
1384 mat.fx.refl_constant_strength = f("Reflection.ConstantStrength", 1.0);
1385 mat.fx.refl_glancing_strength = f("Reflection.GlancingStrength", 0.8);
1386 mat.fx.refl_face_on_strength = f("Reflection.FaceOnStrength", 0.0);
1387 mat.fx.refl_falloff = f("Reflection.Falloff", 2.0);
1388 mat.fx.refl_tint = [rm.diffuse_col[0], rm.diffuse_col[1], rm.diffuse_col[2]];
1389 mat.fx.refl_has_bg = has_bg;
1390 mat.fx.refract_ior = f("Refraction.RefractiveIndex.RGB", 1.333).max(0.01);
1391 mat.fx.refract_tint = ["Red", "Green", "Blue"].map(|c| f(&format!("Refraction.Tint.{c}"), 1.0));
1392 ResolvedMaterial { tex_node, bump_node, ..mat }
1393 }
1394 "MtlChanBool" => {
1395 let mut resolve = |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1);
1396 let black = || materials::flat([0.0, 0.0, 0.0, 1.0]);
1397 let mut mat = materials::material_input(comp, n, "BackgroundMaterial", &mut resolve).unwrap_or_else(black);
1398 let fg = materials::material_input(comp, n, "ForegroundMaterial", &mut resolve).unwrap_or_else(black);
1399 let g = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr).round().clamp(0.0, 30.0) as u8;
1400 let op = |k: &str| comp.eval_number(n, k, time, 0.0, expr).round().clamp(0.0, 10.0) as u8;
1401 mat.fx.cb_enabled = true;
1402 mat.fx.cb_ops_a = [g("OperandAR", 4.0), g("OperandAG", 5.0), g("OperandAB", 6.0), g("OperandAA", 7.0)];
1403 mat.fx.cb_ops = [op("OperationR"), op("OperationG"), op("OperationB"), op("OperationA")];
1404 mat.fx.cb_ops_b = [g("OperandBR", 0.0), g("OperandBG", 1.0), g("OperandBB", 2.0), g("OperandBA", 3.0)];
1405 mat.fx.cb_coord_space = match n.static_str("CoordSpace") {
1406 Some("Model") => 0,
1407 Some("World") => 1,
1408 _ => 2,
1409 };
1410 materials::set_layer(&mut mat, &fg, layer_mode::CHAN_BOOL, 0.0);
1411 mat.has_material_shader = true;
1412 mat
1413 }
1414 _ => ResolvedMaterial {
1415 tex_node: Some(mid),
1416 ..default_mat
1417 },
1418 }
1419}
1420
1421struct Duplicate3DParams<'a> {
1422 translate: [f32; 3],
1423 rot_deg: [f32; 3],
1424 scale: [f32; 3],
1425 pivot: [f32; 3],
1426 rot_order: &'a str,
1427 xform_order: &'a str,
1428}
1429
1430impl Duplicate3DParams<'_> {
1431 fn matrix_for_step(&self, step: f32, linear: bool) -> Mat4 {
1432 let [tx, ty, tz] = self.translate.map(|v| v * step);
1433 let rot_deg = self.rot_deg.map(|v| v * step);
1434 let [sx, sy, sz] = if linear {
1435 self.scale.map(|s| 1.0 + (s - 1.0) * step)
1436 } else {
1437 self.scale
1438 };
1439 let rot = euler_matrix(rot_deg, self.rot_order);
1440 let t_mat = mat4_translate(tx, ty, tz);
1441 let s_mat = mat4_scale(sx, sy, sz);
1442 let core = self.xform_order.bytes().fold(mat4_identity(), |acc, op| match op {
1443 b'S' => mat4_mul(s_mat, acc),
1444 b'R' => mat4_mul(rot, acc),
1445 b'T' => mat4_mul(t_mat, acc),
1446 _ => acc,
1447 });
1448 mat4_mul(
1449 mat4_translate(self.pivot[0], self.pivot[1], self.pivot[2]),
1450 mat4_mul(core, mat4_translate(-self.pivot[0], -self.pivot[1], -self.pivot[2])),
1451 )
1452 }
1453}
1454
1455fn eval_duplicate3d_params<'a>(comp: &'a Comp, node: &'a Node, time: f64, expr: &ExprEngine) -> Duplicate3DParams<'a> {
1456 let f = |k: &str, fb: &str, d: f64| {
1457 comp.eval_number(node, k, time, comp.eval_number(node, fb, time, d, expr), expr) as f32
1458 };
1459 let translate = [
1460 f("Translate.X", "Transform3DOp.Translate.X", 0.0),
1461 f("Translate.Y", "Transform3DOp.Translate.Y", 0.0),
1462 f("Translate.Z", "Transform3DOp.Translate.Z", 0.0),
1463 ];
1464 let rot_deg = [
1465 f("Rotate.X", "Transform3DOp.Rotate.X", 0.0),
1466 f("Rotate.Y", "Transform3DOp.Rotate.Y", 0.0),
1467 f("Rotate.Z", "Transform3DOp.Rotate.Z", 0.0),
1468 ];
1469 let scale_lock = comp.eval_number(node, "ScaleLock", time, 1.0, expr) > 0.5;
1470 let sx = f("Scale.X", "Transform3DOp.Scale.X", 1.0);
1471 let (sy, sz) = if scale_lock {
1472 (sx, sx)
1473 } else {
1474 (
1475 f("Scale.Y", "Transform3DOp.Scale.Y", 1.0),
1476 f("Scale.Z", "Transform3DOp.Scale.Z", 1.0),
1477 )
1478 };
1479 let pivot = [
1480 f("Pivot.X", "Transform3DOp.Pivot.X", 0.0),
1481 f("Pivot.Y", "Transform3DOp.Pivot.Y", 0.0),
1482 f("Pivot.Z", "Transform3DOp.Pivot.Z", 0.0),
1483 ];
1484 let rot_order = node
1485 .static_str("RotationOrder")
1486 .or_else(|| node.static_str("Transform3DOp.Rotate.RotOrder"))
1487 .unwrap_or("XYZ");
1488 let xform_order = node.static_str("TransformOrder").unwrap_or("SRT");
1489 Duplicate3DParams {
1490 translate,
1491 rot_deg,
1492 scale: [sx, sy, sz],
1493 pivot,
1494 rot_order,
1495 xform_order,
1496 }
1497}
1498
1499/// General 4x4 inverse (Gauss-Jordan, partial pivoting); a singular `m` falls back to
1500/// `mat4_inverse_rigid` so a degenerate camera scale never yields NaNs.
1501pub fn mat4_inverse(m: Mat4) -> Mat4 {
1502 let mut a = [[0.0_f64; 8]; 4];
1503 for (r, row) in a.iter_mut().enumerate() {
1504 for c in 0..4 {
1505 row[c] = f64::from(m[c * 4 + r]);
1506 }
1507 row[4 + r] = 1.0;
1508 }
1509 for col in 0..4 {
1510 let pivot = (col..4).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs())).unwrap_or(col);
1511 let invertible = a[pivot][col].abs() > 1e-12;
1512 if !invertible {
1513 return mat4_inverse_rigid(m);
1514 }
1515 a.swap(col, pivot);
1516 let p = a[col][col];
1517 a[col].iter_mut().for_each(|x| *x /= p);
1518 let pivot_row = a[col];
1519 for (r, row) in a.iter_mut().enumerate() {
1520 if r != col {
1521 let f = row[col];
1522 row.iter_mut().zip(pivot_row).for_each(|(x, pv)| *x -= f * pv);
1523 }
1524 }
1525 }
1526 let mut out = [0.0_f32; 16];
1527 for (r, row) in a.iter().enumerate() {
1528 for c in 0..4 {
1529 out[c * 4 + r] = row[4 + c] as f32;
1530 }
1531 }
1532 out
1533}
1534
1535pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 {
1536 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32;
1537 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;
1538 let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32;
1539
1540 let r = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Rotate.{a}"), time, 0.0, expr) as f32);
1541 let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ");
1542
1543 let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5;
1544 let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32;
1545 let (sy, sz) = if scale_lock {
1546 (sx, sx)
1547 } else {
1548 (
1549 comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32,
1550 comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32,
1551 )
1552 };
1553
1554 let p = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Pivot.{a}"), time, 0.0, expr) as f32);
1555 let mut m = trs_matrix([tx, ty, tz], r, rot_order, [sx, sy, sz], p);
1556 if comp.eval_number(node, "Transform3DOp.UseTarget", time, 0.0, expr) > 0.5 {
1557 let tgt = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Target.{a}"), time, 0.0, expr) as f32);
1558 let neg_z = matches!(node.kind.as_str(), "Camera3D" | "LightDirectional" | "LightSpot" | "LightPoint");
1559 if let Some(aim) = target_aim_matrix([tx, ty, tz], tgt, neg_z) {
1560 let local_r = euler_matrix(r, rot_order);
1561 let local_s = mat4_scale(sx, sy, sz);
1562 let t = mat4_translate(tx + p[0], ty + p[1], tz + p[2]);
1563 m = mat4_mul(t, mat4_mul(aim, mat4_mul(local_r, mat4_mul(local_s, mat4_translate(-p[0], -p[1], -p[2])))));
1564 }
1565 }
1566 if comp.eval_number(node, "Transform3DOp.InvertTransform", time, 0.0, expr) > 0.5 { mat4_inverse(m) } else { m }
1567}
1568
1569/// Right-handed aim rotation pointing local `-Z` (cameras/lights) or `+Z` (meshes/merges) from `eye` toward `target`.
1570fn target_aim_matrix(eye: [f32; 3], target: [f32; 3], neg_z_forward: bool) -> Option<Mat4> {
1571 let f = [target[0] - eye[0], target[1] - eye[1], target[2] - eye[2]];
1572 let flen = (f[0] * f[0] + f[1] * f[1] + f[2] * f[2]).sqrt();
1573 if flen < 1e-6 {
1574 return None;
1575 }
1576 let dir = [f[0] / flen, f[1] / flen, f[2] / flen];
1577 // Local +Z axis in world space
1578 let z_axis = if neg_z_forward { [-dir[0], -dir[1], -dir[2]] } else { dir };
1579 let up_ref = if z_axis[1].abs() > 0.999 { [0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0] };
1580 // right = normalize(cross(up_ref, z_axis))
1581 let rx = up_ref[1] * z_axis[2] - up_ref[2] * z_axis[1];
1582 let ry = up_ref[2] * z_axis[0] - up_ref[0] * z_axis[2];
1583 let rz = up_ref[0] * z_axis[1] - up_ref[1] * z_axis[0];
1584 let rlen = (rx * rx + ry * ry + rz * rz).sqrt().max(1e-6);
1585 let right = [rx / rlen, ry / rlen, rz / rlen];
1586 let up = [
1587 z_axis[1] * right[2] - z_axis[2] * right[1],
1588 z_axis[2] * right[0] - z_axis[0] * right[2],
1589 z_axis[0] * right[1] - z_axis[1] * right[0],
1590 ];
1591 Some([
1592 right[0], right[1], right[2], 0.0,
1593 up[0], up[1], up[2], 0.0,
1594 z_axis[0], z_axis[1], z_axis[2], 0.0,
1595 0.0, 0.0, 0.0, 1.0,
1596 ])
1597}
1598
1599pub(super) fn euler_matrix(rot_deg: [f32; 3], order: &str) -> Mat4 {
1600 let [rx, ry, rz] = rot_deg.map(f32::to_radians);
1601 let axes = [mat4_rot_x(rx), mat4_rot_y(ry), mat4_rot_z(rz)];
1602 order
1603 .bytes()
1604 .filter_map(|b| "XYZ".find(b as char))
1605 .fold(mat4_identity(), |acc, a| mat4_mul(axes[a], acc))
1606}
1607
1608/// `T(translate + pivot) * R * S * T(-pivot)`; `rot_deg` is per-axis, composed in `order` (`"XYZ"` applies X first).
1609fn trs_matrix(translate: [f32; 3], rot_deg: [f32; 3], order: &str, scale: [f32; 3], pivot: [f32; 3]) -> Mat4 {
1610 let rot = euler_matrix(rot_deg, order);
1611 let t = mat4_translate(translate[0] + pivot[0], translate[1] + pivot[1], translate[2] + pivot[2]);
1612 let s = mat4_scale(scale[0], scale[1], scale[2]);
1613 mat4_mul(t, mat4_mul(rot, mat4_mul(s, mat4_translate(-pivot[0], -pivot[1], -pivot[2]))))
1614}
1615
1616#[cfg(test)]
1617pub(super) fn comp_src(tools: &str) -> String {
1618 format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}")
1619}
1620
1621#[cfg(test)]
1622pub(super) fn collect_test_scene(src: &str, root: &str) -> (Vec<CameraInstance>, Vec<MeshInstance>, SceneLights) {
1623 let comp = Comp::from_fusion_str(src).expect("parse comp");
1624 let expr = ExprEngine::new();
1625 let id = comp.find_node(root).expect("root node");
1626 let (mut cams, mut meshes, mut lights) = (Vec::new(), Vec::new(), SceneLights::default());
1627 collect_scene(&comp, id, 0.0, &expr, mat4_identity(), 1.0, &mut cams, &mut meshes, &mut lights, 0);
1628 (cams, meshes, lights)
1629}
1630
1631/// Resolves node `X` of a comp holding `tools`.
1632#[cfg(test)]
1633pub(super) fn resolve_test_material(tools: &str) -> ResolvedMaterial {
1634 let comp = Comp::from_fusion_str(&comp_src(tools)).expect("parse comp");
1635 let id = comp.find_node("X").expect("node X");
1636 resolve_material(&comp, Some(id), 0.0, &ExprEngine::new(), &mut Vec::new())
1637}
1638
1639#[cfg(test)]
1640mod tests {
1641 use super::*;
1642 use super::collect_test_scene as collect;
1643
1644 #[test]
1645 fn test_collect_scene_archive_3d_nodes() {
1646 let src = r#"Composition {
1647 CurrentTime = 0,
1648 RenderRange = { 0, 10 },
1649 GlobalRange = { 0, 10 },
1650 Tools = ordered() {
1651 BG1 = Background {
1652 Inputs = {
1653 Width = Input { Value = 64, },
1654 Height = Input { Value = 64, },
1655 },
1656 },
1657 Tex2D = Texture2DOperator {
1658 Inputs = {
1659 Input = Input { SourceOp = "BG1", Source = "Output", },
1660 },
1661 },
1662 Blinn1 = MtlBlinn {
1663 Inputs = {
1664 ["Diffuse.Color.Red"] = Input { Value = 0.8, },
1665 ["Diffuse.Color.Material"] = Input { SourceOp = "Tex2D", Source = "MaterialOutput", },
1666 ["Specular.Intensity"] = Input { Value = 0.75, },
1667 ["Specular.Exponent"] = Input { Value = 40.0, },
1668 },
1669 },
1670 Cook1 = MtlCookTorrance {
1671 Inputs = {
1672 ["Diffuse.Color.Green"] = Input { Value = 0.6, },
1673 ["Specular.Roughness"] = Input { Value = 0.25, },
1674 },
1675 },
1676 Shape1 = Shape3D {
1677 Inputs = {
1678 Shape = Input { Value = FuID { "SurfaceSphereInputs" }, },
1679 MaterialInput = Input { SourceOp = "Blinn1", Source = "MaterialOutput", },
1680 },
1681 },
1682 RepMat = ReplaceMaterial3D {
1683 Inputs = {
1684 SceneInput = Input { SourceOp = "Shape1", Source = "Output", },
1685 MaterialInput = Input { SourceOp = "Cook1", Source = "MaterialOutput", },
1686 },
1687 },
1688 RepNorm = ReplaceNormals3D {
1689 Inputs = {
1690 SceneInput = Input { SourceOp = "RepMat", Source = "Output", },
1691 ["Normals.Flip"] = Input { Value = 1, },
1692 },
1693 },
1694 Disp1 = Displace3D {
1695 Inputs = {
1696 SceneInput = Input { SourceOp = "RepNorm", Source = "Output", },
1697 Input = Input { SourceOp = "BG1", Source = "Output", },
1698 Scale = Input { Value = 0.2, },
1699 },
1700 },
1701 Dup1 = Duplicate3D {
1702 Inputs = {
1703 SceneInput = Input { SourceOp = "Disp1", Source = "Output", },
1704 FirstCopy = Input { Value = 0, },
1705 LastCopy = Input { Value = 2, },
1706 ["Translate.X"] = Input { Value = 1.5, },
1707 },
1708 },
1709 OvrHide = Override3D {
1710 Inputs = {
1711 SceneInput = Input { SourceOp = "Shape1", Source = "Output", },
1712 ["Visibility.DoVisible"] = Input { Value = 1, },
1713 ["Visibility.IsVisible"] = Input { Value = 0, },
1714 },
1715 },
1716 Txt1 = Text3D {
1717 Inputs = {
1718 StyledText = Input { Value = "HI", },
1719 ["Extrusion.ExtrusionDepth"] = Input { Value = 0.15, },
1720 },
1721 },
1722 Pt1 = LightPoint {
1723 Inputs = {
1724 Intensity = Input { Value = 2.0, },
1725 DecayType = Input { Value = 1, },
1726 ["Transform3DOp.Translate.X"] = Input { Value = 3.0, },
1727 },
1728 },
1729 Sp1 = LightSpot {
1730 Inputs = {
1731 Intensity = Input { Value = 1.5, },
1732 ConeAngle = Input { Value = 45.0, },
1733 PenumbraAngle = Input { Value = 10.0, },
1734 },
1735 },
1736 Cam1 = Camera3D {
1737 Inputs = {
1738 ["Transform3DOp.Translate.Z"] = Input { Value = 5.0, },
1739 },
1740 },
1741 Merge1 = Merge3D {
1742 Inputs = {
1743 SceneInput1 = Input { SourceOp = "Dup1", Source = "Output", },
1744 SceneInput2 = Input { SourceOp = "OvrHide", Source = "Output", },
1745 SceneInput3 = Input { SourceOp = "Txt1", Source = "Output", },
1746 SceneInput4 = Input { SourceOp = "Pt1", Source = "Output", },
1747 SceneInput5 = Input { SourceOp = "Sp1", Source = "Output", },
1748 SceneInput6 = Input { SourceOp = "Cam1", Source = "Output", },
1749 },
1750 },
1751 },
1752 }"#;
1753 let comp = Comp::from_fusion_str(src).expect("parse 3D test comp");
1754 let expr = ExprEngine::new();
1755 let merge_id = comp.find_node("Merge1").expect("Merge1");
1756 let mut cams = Vec::new();
1757 let mut meshes = Vec::new();
1758 let mut lights = SceneLights::default();
1759 collect_scene(
1760 &comp,
1761 merge_id,
1762 0.0,
1763 &expr,
1764 mat4_identity(),
1765 16.0 / 9.0,
1766 &mut cams,
1767 &mut meshes,
1768 &mut lights,
1769 0,
1770 );
1771 assert_eq!(cams.len(), 1);
1772 // 2 copies from Duplicate3D (0..2, exclusive LastCopy) + 1 Text3D (OvrHide suppresses its Shape1)
1773 assert_eq!(meshes.len(), 3);
1774 assert!(meshes[0].flip_normals);
1775 assert!(meshes[0].displace.is_some());
1776 assert!((meshes[0].diffuse_col[1] - 0.6).abs() < 1e-4, "ReplaceMaterial3D should apply Cook1");
1777 assert!((meshes[1].world[12] - 1.5).abs() < 1e-4, "Duplicate3D copy 1 translated X=1.5");
1778 assert!(meshes[2].text3d.is_some());
1779 assert_eq!(lights.points.len(), 1);
1780 assert!((lights.points[0].pos[0] - 3.0).abs() < 1e-4);
1781 assert_eq!(lights.spots.len(), 1);
1782 assert!(lights.spots[0].cos_inner > lights.spots[0].cos_outer);
1783 }
1784
1785 #[test]
1786 fn test_collect_fbx_cube_tex_transform_and_bump() {
1787 let faces: String = CUBE_FACES
1788 .iter()
1789 .map(|f| format!(r#"{f}MaterialInput = Input {{ SourceOp = "BlinnBump", Source = "MaterialOutput", }},"#))
1790 .collect();
1791 let src = format!(
1792 r#"Composition {{
1793 CurrentTime = 0,
1794 RenderRange = {{ 0, 10 }},
1795 GlobalRange = {{ 0, 10 }},
1796 Tools = ordered() {{
1797 BG1 = Background {{
1798 Inputs = {{
1799 Width = Input {{ Value = 64, }},
1800 Height = Input {{ Value = 64, }},
1801 }},
1802 }},
1803 Bump1 = BumpMap {{
1804 Inputs = {{
1805 Input = Input {{ SourceOp = "BG1", Source = "Output", }},
1806 HeightScale = Input {{ Value = 4.5, }},
1807 SourceImageType = Input {{ Value = 1, }},
1808 WrapMode = Input {{ Value = FuID {{ "Wrap" }}, }},
1809 }},
1810 }},
1811 TexXf = TextureTransformOperator {{
1812 Inputs = {{
1813 MaterialInput = Input {{ SourceOp = "Bump1", Source = "MaterialOutput", }},
1814 ["Translation.U"] = Input {{ Value = 0.25, }},
1815 ["Translation.V"] = Input {{ Value = -0.5, }},
1816 }},
1817 }},
1818 BlinnBump = MtlBlinn {{
1819 Inputs = {{
1820 ["Diffuse.Color.Red"] = Input {{ Value = 0.7, }},
1821 ["Bumpmap.Material"] = Input {{ SourceOp = "TexXf", Source = "MaterialOutput", }},
1822 }},
1823 }},
1824 CubeNode = Cube3D {{
1825 Inputs = {{
1826 ["SurfaceCubeInputs.Width"] = Input {{ Value = 2.0, }},
1827 ["SurfaceCubeInputs.Height"] = Input {{ Value = 4.0, }},
1828 ["Transform3DOp.Translate.Y"] = Input {{ Value = 1.5, }},
1829 {faces}
1830 }},
1831 }},
1832 FbxNode = SurfaceFBXMesh {{
1833 Inputs = {{
1834 ImportFile = Input {{ Value = "/does/not/exist/model.fbx", }},
1835 ObjName = Input {{ Value = "HeroMesh", }},
1836 ScaleFileUnitsBy = Input {{ Value = 0.01, }},
1837 ["Transform3DOp.Translate.X"] = Input {{ Value = -2.0, }},
1838 ["Materials.Mat0_mat0"] = Input {{ SourceOp = "TexXf", Source = "MaterialOutput", }},
1839 }},
1840 }},
1841 Merge1 = Merge3D {{
1842 Inputs = {{
1843 SceneInput1 = Input {{ SourceOp = "CubeNode", Source = "Output", }},
1844 SceneInput2 = Input {{ SourceOp = "FbxNode", Source = "Output", }},
1845 }},
1846 }},
1847 }},
1848 }}"#
1849 );
1850 let comp = Comp::from_fusion_str(&src).expect("parse comp");
1851 let expr = ExprEngine::new();
1852 let merge_id = comp.find_node("Merge1").expect("Merge1");
1853 let bg_id = comp.find_node("BG1").expect("BG1");
1854 let mut cams = Vec::new();
1855 let mut meshes = Vec::new();
1856 let mut lights = SceneLights::default();
1857 collect_scene(
1858 &comp,
1859 merge_id,
1860 0.0,
1861 &expr,
1862 mat4_identity(),
1863 16.0 / 9.0,
1864 &mut cams,
1865 &mut meshes,
1866 &mut lights,
1867 0,
1868 );
1869 // Six identical face materials collapse into one cube; Height is ignored.
1870 assert_eq!(meshes.len(), 2);
1871
1872 let cube = &meshes[0];
1873 assert!(matches!(
1874 cube.shape.base_shape(),
1875 ShapeKind::Cube { width, faces: 0b11_1111, .. } if (*width - 2.0).abs() < 1e-4
1876 ));
1877 assert!((cube.world[13] - 1.5).abs() < 1e-4);
1878 assert_eq!(cube.material_node, Some(bg_id));
1879 assert!((cube.diffuse_col[0] - 0.7).abs() < 1e-4);
1880 let fx = cube.shape.split_fx().1;
1881 assert!((fx.bump_scale - 4.5).abs() < 1e-4);
1882 assert_eq!(fx.bump_mode, 1);
1883 assert!(!fx.bump_only || cube.material_node.is_some());
1884 assert_eq!(fx.uv_wrap, 1);
1885 // Content moved +0.25 in U and -0.5 in V (V up) samples from u-0.25 and v-0.5.
1886 let sampled = fx.uv.apply([0.5, 0.5]);
1887 assert!((sampled[0] - 0.25).abs() < 1e-4 && sampled[1].abs() < 1e-4, "{sampled:?}");
1888
1889 let fbx = &meshes[1];
1890 assert!(matches!(fbx.shape.base_shape(), ShapeKind::CustomMesh(v) if v.len() == 36));
1891 assert!((fbx.world[12] + 2.0).abs() < 1e-4);
1892 assert_eq!(fbx.material_node, Some(bg_id));
1893 assert!((fbx.shape.split_fx().1.bump_scale - 4.5).abs() < 1e-4);
1894 }
1895
1896 #[test]
1897 fn cameras_carry_names_for_renderer_selection() {
1898 let src = comp_src(
1899 r#"A = Camera3D { }, B = Camera3D { Inputs = { ProjectionType = Input { Value = FuID { "Orthographic" }, }, }, },
1900 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output", }, SceneInput2 = Input { SourceOp = "B", Source = "Output", }, }, },"#,
1901 );
1902 let (cams, ..) = collect(&src, "M");
1903 let found: Vec<_> = cams.iter().map(|c| (c.name.as_str(), c.orthographic)).collect();
1904 assert_eq!(found, [("A", false), ("B", true)]);
1905 }
1906
1907 #[test]
1908 fn texture2d_offset_and_scale_move_content_like_a_texture_transform() {
1909 let src = comp_src(
1910 r#"Bg = Background { }, Tex = Texture2DOperator { Inputs = { UOffset = Input { Value = 0.25, }, UScale = Input { Value = 2, }, Input = Input { SourceOp = "Bg", Source = "Output", }, }, },
1911 S = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },"#,
1912 );
1913 let (_, meshes, _) = collect(&src, "S");
1914 let (_, fx) = meshes[0].shape.split_fx();
1915 // Content scales 2x about the origin then moves right by 0.25: mesh u=0.75 samples texture u=0.25.
1916 assert!((fx.uv.apply([0.75, 0.0])[0] - 0.25).abs() < 1e-5);
1917 }
1918
1919 #[test]
1920 fn receives_lighting_off_is_unlit_and_lights_are_counted() {
1921 let src = comp_src(
1922 r#"Mtl = MtlBlinn { Inputs = { ReceivesLighting = Input { Value = 0, }, EnablePBRMaterial = Input { Value = 1, }, }, },
1923 S = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Mtl", Source = "MaterialOutput", }, }, },
1924 A = LightAmbient { }, P = LightPoint { }, Off = LightPoint { Inputs = { Enabled = Input { Value = 0, }, }, },
1925 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, SceneInput2 = Input { SourceOp = "A", Source = "Output", }, SceneInput3 = Input { SourceOp = "P", Source = "Output", }, SceneInput4 = Input { SourceOp = "Off", Source = "Output", }, }, },"#,
1926 );
1927 let (_, meshes, lights) = collect(&src, "M");
1928 let (_, fx) = meshes[0].shape.split_fx();
1929 assert!(fx.per_light_unlit && !meshes[0].affected_by_lights);
1930 assert_eq!(fx.spec_model, SpecModel::Pbr);
1931 assert_eq!(lights.count, 2);
1932 }
1933
1934 #[test]
1935 fn invert_transform_inverts_the_node_matrix() {
1936 let src = comp_src(
1937 r#"Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = 3, }, ["Transform3DOp.InvertTransform"] = Input { Value = 1, }, }, },
1938 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#,
1939 );
1940 let (cams, ..) = collect(&src, "M");
1941 assert!((cams[0].world[12] + 3.0).abs() < 1e-5);
1942 }
1943
1944 #[test]
1945 fn replace_normals_recomputes_by_smoothing_angle() {
1946 let tris = |angle: f64| {
1947 let src = comp_src(&format!(
1948 r#"S = Shape3D {{ Inputs = {{ Shape = Input {{ Value = FuID {{ "SurfaceIcoInputs" }}, }}, }}, }},
1949 N = ReplaceNormals3D {{ Inputs = {{ ["Normals.SmoothingAngle"] = Input {{ Value = {angle}, }}, SceneInput = Input {{ SourceOp = "S", Source = "Output", }}, }}, }},"#
1950 ));
1951 let (_, meshes, _) = collect(&src, "N");
1952 let (ShapeKind::CustomMesh(v), _) = meshes[0].shape.split_fx() else { panic!("expected a mesh") };
1953 v.clone()
1954 };
1955 // Adjacent icosahedron faces differ by ~41.8 degrees: below that every face is flat.
1956 let flat = tris(30.0);
1957 let close = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4);
1958 assert!(flat.chunks_exact(3).all(|t| close(t[0].normal, t[1].normal) && close(t[1].normal, t[2].normal)));
1959 let smooth = tris(90.0);
1960 assert!(smooth.chunks_exact(3).any(|t| !close(t[0].normal, t[1].normal)));
1961 }
1962
1963 #[test]
1964 fn camera_vertical_aov_comes_from_default_35mm_focal_length() {
1965 // Serialized AoV is ignored: 35mm on a 1" gate gives 2*atan(12.7/35).
1966 let src = comp_src(
1967 r#"Cam = Camera3D { Inputs = { AoV = Input { Value = 35.0, }, ApertureW = Input { Value = 1.0, }, ApertureH = Input { Value = 1.0, }, }, },
1968 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#,
1969 );
1970 let (cams, ..) = collect(&src, "M");
1971 let expected = 2.0 * (12.7_f32 / 35.0).atan();
1972 assert!((cams[0].vfov_rad - expected).abs() < 1e-4, "{} vs {expected}", cams[0].vfov_rad);
1973
1974 let src = comp_src(
1975 r#"Cam = Camera3D { Inputs = { AoV = Input { Value = 35.0, }, ApertureH = Input { Value = 1.0, }, FLength = Input { Value = 50.0, }, }, },
1976 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#,
1977 );
1978 let (cams, ..) = collect(&src, "M");
1979 assert!((cams[0].vfov_rad - 2.0 * (12.7_f32 / 50.0).atan()).abs() < 1e-4);
1980 }
1981
1982 #[test]
1983 fn plane_is_square_and_defaults_to_ten_cells() {
1984 let src = comp_src(
1985 r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.Height"] = Input { Value = 1.0, }, ["SurfacePlaneInputs.SubdivisionHeight"] = Input { Value = 3, }, }, },
1986 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "P", Source = "Output", }, }, },"#,
1987 );
1988 let (_, meshes, _) = collect(&src, "M");
1989 assert!(matches!(
1990 meshes[0].shape.base_shape(),
1991 ShapeKind::Plane { width, height, sub_w: 10, sub_h: 10 } if *width == 2.0 && *height == 2.0
1992 ));
1993 }
1994
1995 #[test]
1996 fn cube3d_ignores_plain_material_input_and_splits_by_face_material() {
1997 let src = comp_src(
1998 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
1999 Tex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, }, },
2000 Plain = Cube3D { Inputs = { MaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },
2001 Front = Cube3D { Inputs = { FrontMaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },
2002 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Plain", Source = "Output", }, SceneInput2 = Input { SourceOp = "Front", Source = "Output", }, }, },"#,
2003 );
2004 let (_, meshes, _) = collect(&src, "M");
2005 let tex = Comp::from_fusion_str(&src).unwrap().find_node("Bg");
2006 assert_eq!(meshes.len(), 3);
2007 assert!(meshes[0].material_node.is_none(), "Cube3D has no plain MaterialInput");
2008 assert!(matches!(meshes[1].shape.base_shape(), ShapeKind::Cube { faces: 0b00_0001, .. }));
2009 assert_eq!(meshes[1].material_node, tex);
2010 assert!(matches!(meshes[2].shape.base_shape(), ShapeKind::Cube { faces: 0b11_1110, .. }));
2011 }
2012
2013 #[test]
2014 fn texture_transform_moves_content_about_a_bottom_left_pivot() {
2015 let uvw = |t, r, s, invert| texture_transform_uv(trs_matrix(t, r, "XYZ", s, [0.0; 3]), invert);
2016 // Scale 2 about the (0, 0) pivot zooms toward the bottom-left corner (V up).
2017 let zoom = uvw([0.0; 3], [0.0; 3], [2.0, 2.0, 1.0], false);
2018 let (bl, tr) = (zoom.apply([0.0, 1.0]), zoom.apply([1.0, 0.0]));
2019 assert!(bl[0].abs() < 1e-5 && (bl[1] - 1.0).abs() < 1e-5);
2020 assert!((tr[0] - 0.5).abs() < 1e-5 && (tr[1] - 0.5).abs() < 1e-5);
2021
2022 // Content moved right and up samples from smaller u and larger raw v (V down).
2023 let shift = uvw([0.25, 0.1, 0.0], [0.0; 3], [1.0; 3], false).apply([0.5, 0.5]);
2024 assert!((shift[0] - 0.25).abs() < 1e-5 && (shift[1] - 0.6).abs() < 1e-5);
2025
2026 // Counter-clockwise content rotation about the pivot.
2027 let quarter = uvw([0.0; 3], [0.0, 0.0, 90.0], [1.0; 3], false);
2028 let p = quarter.apply([0.0, 0.0]); // top-left corner samples from the content to its right
2029 assert!((p[0] - 1.0).abs() < 1e-5 && (p[1] - 1.0).abs() < 1e-5, "{p:?}");
2030
2031 // Tilting about U drops W, magnifying content in V by 1/cos; InvertTransform undoes a move.
2032 let tilt = uvw([0.0; 3], [60.0, 0.0, 0.0], [1.0; 3], false).apply([0.0, 0.5]);
2033 assert!((tilt[1] - 0.75).abs() < 1e-5, "{tilt:?}");
2034 let back = uvw([0.2, 0.0, 0.0], [0.0; 3], [1.0; 3], true).apply([0.5, 0.5]);
2035 assert!((back[0] - 0.7).abs() < 1e-5, "{back:?}");
2036 }
2037
2038 #[test]
2039 fn disabled_and_black_lights_do_not_take_slots() {
2040 let spot = |name: &str, extra: &str| format!("{name} = LightSpot {{ Inputs = {{ {extra} }}, }},");
2041 let src = comp_src(&format!(
2042 "{} {} {} Live = LightSpot {{ }}, M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = \"Off\", Source = \"Output\", }}, SceneInput2 = Input {{ SourceOp = \"Dark\", Source = \"Output\", }}, SceneInput3 = Input {{ SourceOp = \"Live\", Source = \"Output\", }}, }}, }},",
2043 spot("Off", "Enabled = Input { Value = 0, },"),
2044 spot("Dark", "Intensity = Input { Value = 0, },"),
2045 ""
2046 ));
2047 let (_, _, lights) = collect(&src, "M");
2048 assert_eq!(lights.spots.len(), 1);
2049 assert_eq!(lights.spots[0].color, [1.0, 1.0, 1.0]);
2050 }
2051
2052 #[test]
2053 fn surface_visibility_lighting_and_bare_texture_flags() {
2054 let src = comp_src(
2055 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
2056 Tex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, }, },
2057 Blinn = MtlBlinn { Inputs = { ["Diffuse.Color.Material"] = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },
2058 Hidden = Shape3D { Inputs = { ["SurfacePlaneInputs.Visibility.IsVisible"] = Input { Value = 0, }, }, },
2059 Unlit = Shape3D { Inputs = { ["SurfacePlaneInputs.Lighting.IsAffectedByLights"] = Input { Value = 0, }, }, },
2060 Flat = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },
2061 Shaded = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, },
2062 Forced = Override3D { Inputs = { SceneInput = Input { SourceOp = "Unlit", Source = "Output", }, ["Lighting.DoAffectedByLights"] = Input { Value = 1, }, ["Lighting.IsAffectedByLights"] = Input { Value = 1, }, }, },
2063 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Hidden", Source = "Output", }, SceneInput2 = Input { SourceOp = "Unlit", Source = "Output", }, SceneInput3 = Input { SourceOp = "Flat", Source = "Output", }, SceneInput4 = Input { SourceOp = "Shaded", Source = "Output", }, SceneInput5 = Input { SourceOp = "Forced", Source = "Output", }, }, },"#,
2064 );
2065 let (_, meshes, _) = collect(&src, "M");
2066 let lit: Vec<bool> = meshes.iter().map(|m| m.affected_by_lights).collect();
2067 assert_eq!(lit, [false, false, true, true], "hidden surface dropped; own flag, bare texture, Blinn, override");
2068 }
2069
2070 #[test]
2071 fn specular_models_and_defaults() {
2072 let src = comp_src(
2073 r#"Blinn = MtlBlinn { }, Phong = MtlPhong { }, Cook = MtlCookTorrance { },
2074 A = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, },
2075 B = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Phong", Source = "MaterialOutput", }, }, },
2076 C = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Cook", Source = "MaterialOutput", }, }, },
2077 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output", }, SceneInput2 = Input { SourceOp = "B", Source = "Output", }, SceneInput3 = Input { SourceOp = "C", Source = "Output", }, }, },"#,
2078 );
2079 let (_, meshes, _) = collect(&src, "M");
2080 let models: Vec<_> = meshes.iter().map(|m| (m.shape.split_fx().1.spec_model, m.specular_exponent)).collect();
2081 assert_eq!(models, [(SpecModel::Blinn, 50.0), (SpecModel::Phong, 50.0), (SpecModel::CookTorrance, 0.6)]);
2082 }
2083
2084 #[test]
2085 fn bump_only_material_does_not_color_the_surface_and_wireframe_follows_shape_input() {
2086 let src = comp_src(
2087 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
2088 Bump = BumpMap { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, HeightScale = Input { Value = 2.0, }, }, },
2089 Blinn = MtlBlinn { Inputs = { ["Bumpmap.Material"] = Input { SourceOp = "Bump", Source = "MaterialOutput", }, }, },
2090 S = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Wireframe"] = Input { Value = 1, }, MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, },
2091 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, }, },"#,
2092 );
2093 let (_, meshes, _) = collect(&src, "M");
2094 let fx = meshes[0].shape.split_fx().1;
2095 assert!(fx.bump_only && fx.wireframe);
2096 assert_eq!(fx.bump_scale, 2.0);
2097 }
2098
2099 #[test]
2100 fn hidden_cube_still_passes_its_scene_input_through() {
2101 let src = comp_src(
2102 r#"Inner = Shape3D { },
2103 C = Cube3D { Inputs = { ["SurfaceCubeInputs.Visibility.IsVisible"] = Input { Value = 0, }, SceneInput = Input { SourceOp = "Inner", Source = "Output", }, }, },
2104 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "C", Source = "Output", }, }, },"#,
2105 );
2106 let (_, meshes, _) = collect(&src, "M");
2107 assert_eq!(meshes.len(), 1);
2108 assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::Plane { .. }));
2109 }
2110
2111 #[test]
2112 fn scene_inputs_are_visited_in_numeric_order() {
2113 let plane = |name: &str, x: u32| format!(r#"{name} = Shape3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = {x}, }}, }}, }},"#);
2114 let src = comp_src(&format!(
2115 r#"{} {} {}
2116 M = Merge3D {{ Inputs = {{ SceneInput10 = Input {{ SourceOp = "C", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "B", Source = "Output", }}, SceneInput1 = Input {{ SourceOp = "A", Source = "Output", }}, }}, }},"#,
2117 plane("A", 1),
2118 plane("B", 2),
2119 plane("C", 10),
2120 ));
2121 let (_, meshes, _) = collect(&src, "M");
2122 let xs: Vec<f32> = meshes.iter().map(|m| m.world[12]).collect();
2123 assert_eq!(xs, [1.0, 2.0, 10.0]);
2124 }
2125
2126 #[test]
2127 fn every_directional_light_is_collected_with_its_own_direction_and_color() {
2128 let src = comp_src(
2129 r#"Front = LightDirectional { Inputs = { Intensity = Input { Value = 0.5, }, }, },
2130 Side = LightDirectional { Inputs = { ["Transform3DOp.Rotate.Y"] = Input { Value = 90, }, Red = Input { Value = 0, }, }, },
2131 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Front", Source = "Output", }, SceneInput2 = Input { SourceOp = "Side", Source = "Output", }, }, },"#,
2132 );
2133 let (_, _, lights) = collect(&src, "M");
2134 assert_eq!(lights.dirs.len(), 2);
2135 assert_eq!(lights.dirs[0].color, [0.5, 0.5, 0.5]);
2136 assert!((lights.dirs[0].to_light[2] - 1.0).abs() < 1e-5);
2137 assert_eq!(lights.dirs[1].color, [0.0, 1.0, 1.0]);
2138 assert!((lights.dirs[1].to_light[0] - 1.0).abs() < 1e-5, "{:?}", lights.dirs[1].to_light);
2139 }
2140
2141 #[test]
2142 fn mat4_inverse_handles_scaled_camera_parents() {
2143 let src = comp_src(
2144 r#"Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 30, }, }, },
2145 Rig = Transform3D { Inputs = { ["Transform3DOp.ScaleLock"] = Input { Value = 0, }, ["Transform3DOp.Scale.X"] = Input { Value = 2, }, ["Transform3DOp.Scale.Y"] = Input { Value = 0.5, }, ["Transform3DOp.Translate.X"] = Input { Value = 3, }, SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#,
2146 );
2147 let (cams, ..) = collect(&src, "Rig");
2148 let world = cams[0].world;
2149 let near_identity = |m: Mat4| m.iter().zip(mat4_identity()).all(|(a, b)| (a - b).abs() < 1e-5);
2150 assert!(near_identity(mat4_mul(mat4_inverse(world), world)));
2151 assert!(!near_identity(mat4_mul(mat4_inverse_rigid(world), world)), "rigid inverse is wrong under scale");
2152 }
2153
2154 #[test]
2155 fn mat4_inverse_of_singular_matrix_is_finite() {
2156 let inv = mat4_inverse(mat4_scale(0.0, 1.0, 1.0));
2157 assert!(inv.iter().all(|v| v.is_finite()));
2158 assert_eq!(mat4_inverse(mat4_translate(1.0, 2.0, 3.0)), mat4_translate(-1.0, -2.0, -3.0));
2159 }
2160
2161 #[test]
2162 fn camera3d_passes_scene_input_and_cube3d_tints_textured_faces() {
2163 let src = comp_src(
2164 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
2165 Cube = Cube3D { Inputs = {
2166 FrontMaterialInput = Input { SourceOp = "Bg", Source = "Output", },
2167 ["Front.MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.5, },
2168 ["Front.MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.0, },
2169 }, },
2170 Cam = Camera3D { Inputs = { SceneInput = Input { SourceOp = "Cube", Source = "Output", }, }, },"#,
2171 );
2172 let (cams, meshes, _) = collect(&src, "Cam");
2173 assert_eq!(cams.len(), 1);
2174 assert!(meshes.len() >= 2, "Camera3D must pass SceneInput Cube3D through");
2175 let front = meshes.iter().find(|m| matches!(m.shape.base_shape(), ShapeKind::Cube { faces: 1, .. })).unwrap();
2176 assert_eq!(front.diffuse_col, [1.0, 0.5, 0.0, 1.0]);
2177 }
2178
2179 #[test]
2180 fn duplicate3d_honors_exclusive_last_copy_region_scale_lock_linear_and_copy0_unjittered() {
2181 let src = comp_src(
2182 r#"S = Shape3D { },
2183 Hidden = Duplicate3D { Inputs = { SceneInput = Input { SourceOp = "S", Source = "Output", }, RegionMode = Input { Value = FuID { "NotInside" }, }, }, },
2184 Locked = Duplicate3D { Inputs = { SceneInput = Input { SourceOp = "S", Source = "Output", }, LastCopy = Input { Value = 2, }, ["Scale.Y"] = Input { Value = 3.0, }, ["JitterTranslate.X"] = Input { Value = 2.0, }, }, },
2185 Linear = Duplicate3D { Inputs = { SceneInput = Input { SourceOp = "S", Source = "Output", }, LastCopy = Input { Value = 3, }, TransformMethod = Input { Value = FuID { "Linear" }, }, ["Translate.X"] = Input { Value = 1.0, }, ["Rotate.Z"] = Input { Value = 90.0, }, ["Scale.X"] = Input { Value = 0.5, }, }, },"#,
2186 );
2187 assert_eq!(collect(&src, "Hidden").1.len(), 0, "RegionMode=NotInside with AllRgn emits zero copies");
2188
2189 let (_, locked, _) = collect(&src, "Locked");
2190 assert_eq!(locked.len(), 2, "LastCopy=2 emits copies 0..2");
2191 assert!((locked[0].world[5] - 1.0).abs() < 1e-5, "ScaleLock=1 ignores Scale.Y");
2192 assert!(locked[0].world[12].abs() < 1e-5, "copy 0 is never jittered");
2193 assert!(locked[1].world[12].abs() > 1e-4, "copy 1 receives jitter");
2194
2195 let (_, linear, _) = collect(&src, "Linear");
2196 assert_eq!(linear.len(), 3);
2197 // Linear SRT: copy 2 has T = 2*(1,0,0), S = 1 + 2*(0.5-1) = 0, so copy 2 stays at X=2 without orbiting.
2198 assert!((linear[2].world[12] - 2.0).abs() < 1e-4 && linear[2].world[13].abs() < 1e-4);
2199 }
2200
2201 #[test]
2202 fn replace_material_enable_zero_displace_default_scale_and_override_wireframe() {
2203 let src = comp_src(
2204 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
2205 Mtl = MtlBlinn { Inputs = { ["Diffuse.Color.Red"] = Input { Value = 0.2, }, }, },
2206 S = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.9, }, }, },
2207 RepOff = ReplaceMaterial3D { Inputs = { SceneInput = Input { SourceOp = "S", Source = "Output", }, MaterialInput = Input { SourceOp = "Mtl", Source = "MaterialOutput", }, Enable = Input { Value = 0, }, }, },
2208 Disp = Displace3D { Inputs = { SceneInput = Input { SourceOp = "RepOff", Source = "Output", }, Input = Input { SourceOp = "Bg", Source = "Output", }, }, },
2209 Ovr = Override3D { Inputs = { SceneInput = Input { SourceOp = "Disp", Source = "Output", }, ["Wireframe.DoWireframe"] = Input { Value = 1, }, ["Wireframe.Wireframe"] = Input { Value = 1, }, ["Lighting.DoShadowCaster"] = Input { Value = 1, }, ["Lighting.IsShadowCaster"] = Input { Value = 0, }, }, },"#,
2210 );
2211 let (_, meshes, _) = collect(&src, "Ovr");
2212 assert_eq!(meshes.len(), 1);
2213 assert!((meshes[0].diffuse_col[0] - 0.9).abs() < 1e-4, "Enable=0 keeps Shape3D material");
2214 assert!((meshes[0].displace.as_ref().unwrap().scale - 0.1).abs() < 1e-5, "Displace3D default Scale=0.1");
2215 let (_, fx) = meshes[0].shape.split_fx();
2216 assert!(fx.wireframe);
2217 assert!(!meshes[0].casts_shadow);
2218 }
2219
2220 #[test]
2221 fn merge3d_use_target_aims_plus_z_and_bumpmap_preserves_diffuse_and_bump_nodes() {
2222 let src = comp_src(
2223 r#"DiffBg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
2224 BumpBg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
2225 Bump = BumpMap { Inputs = { Input = Input { SourceOp = "BumpBg", Source = "Output", }, SourceImageType = Input { Value = 1, }, }, },
2226 Mtl = MtlBlinn { Inputs = { ["Diffuse.Color.Material"] = Input { SourceOp = "DiffBg", Source = "Output", }, ["Bumpmap.Material"] = Input { SourceOp = "Bump", Source = "MaterialOutput", }, }, },
2227 S = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Mtl", Source = "MaterialOutput", }, }, },
2228 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, ["Transform3DOp.UseTarget"] = Input { Value = 1, }, ["Transform3DOp.Target.Z"] = Input { Value = -3.0, }, }, },"#,
2229 );
2230 let comp = Comp::from_fusion_str(&src).unwrap();
2231 let diff_id = comp.find_node("DiffBg").unwrap();
2232 let bump_id = comp.find_node("BumpBg").unwrap();
2233 let (_, meshes, _) = collect(&src, "M");
2234 assert_eq!(meshes[0].material_node, Some(diff_id));
2235 assert_eq!(meshes[0].bump_node, Some(bump_id));
2236 // Target at -Z rotates Merge3D +Z toward -Z (world[10] == -1).
2237 assert!((meshes[0].world[10] + 1.0).abs() < 1e-4, "world[10]={}", meshes[0].world[10]);
2238 }
2239
2240 #[test]
2241 fn diffuse_color_alpha_and_cook_torrance_fresnel_inputs_are_collected() {
2242 let src = comp_src(
2243 r#"Blinn = MtlBlinn { Inputs = { ["Diffuse.Color.Alpha"] = Input { Value = 0.35, }, ["Diffuse.Opacity"] = Input { Value = 0.8, }, }, },
2244 Cook = MtlCookTorrance { Inputs = { ["Diffuse.Color.Alpha"] = Input { Value = 0.5, }, ["Specular.RefractiveIndex"] = Input { Value = 2.75, }, ["Specular.DoFresnel"] = Input { Value = 0, }, }, },
2245 Std = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Alpha"] = Input { Value = 0.25, }, ["MtlStdInputs.Diffuse.Opacity"] = Input { Value = 0.6, }, }, },
2246 Sb = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, },
2247 Sc = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Cook", Source = "MaterialOutput", }, }, },
2248 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Sb", Source = "Output", }, SceneInput2 = Input { SourceOp = "Sc", Source = "Output", }, SceneInput3 = Input { SourceOp = "Std", Source = "Output", }, }, },"#,
2249 );
2250 let (_, meshes, _) = collect(&src, "M");
2251 assert_eq!(meshes.len(), 3);
2252 let b_fx = meshes[0].shape.split_fx().1;
2253 assert!((b_fx.diffuse_color_alpha - 0.35).abs() < 1e-5);
2254 assert!((meshes[0].diffuse_col[3] - 0.8).abs() < 1e-5);
2255
2256 let c_fx = meshes[1].shape.split_fx().1;
2257 assert!((c_fx.diffuse_color_alpha - 0.5).abs() < 1e-5);
2258 assert!((c_fx.refractive_index - 2.75).abs() < 1e-5);
2259 assert!(!c_fx.do_fresnel);
2260
2261 let s_fx = meshes[2].shape.split_fx().1;
2262 assert!((s_fx.diffuse_color_alpha - 0.25).abs() < 1e-5);
2263 assert!((meshes[2].diffuse_col[3] - 0.6).abs() < 1e-5);
2264 }
2265
2266 #[test]
2267 fn bender3d_and_replicate3d_scene_collection() {
2268 let src = comp_src(
2269 r#"Plane = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.SubdivisionWidth"] = Input { Value = 4, }, }, },
2270 Bent = Bender3D { Inputs = {
2271 SceneInput = Input { SourceOp = "Plane", Source = "Output", },
2272 Bender = Input { Value = FuID { "Taper" }, },
2273 Amount = Input { Value = 0.5, },
2274 Axis = Input { Value = 1, },
2275 Center = Input { Value = 0.5, },
2276 }, },
2277 DestCube = Shape3D { Inputs = {
2278 Shape = Input { Value = FuID { "SurfaceCubeInputs" }, },
2279 ["SurfaceCubeInputs.Width"] = Input { Value = 2.0, },
2280 ["SurfaceCubeInputs.SubdivisionWidth"] = Input { Value = 1, },
2281 }, },
2282 SrcA = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 1.0, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.0, }, }, },
2283 SrcB = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.0, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 1.0, }, }, },
2284 Rep = Replicate3D { Inputs = {
2285 Destination = Input { SourceOp = "DestCube", Source = "Output", },
2286 Input1 = Input { SourceOp = "SrcA", Source = "Output", },
2287 Input2 = Input { SourceOp = "SrcB", Source = "Output", },
2288 Step = Input { Value = 2, },
2289 Alignment = Input { Value = 1, },
2290 ["Scale.X"] = Input { Value = 0.25, },
2291 }, },
2292 M = Merge3D { Inputs = {
2293 SceneInput1 = Input { SourceOp = "Bent", Source = "Output", },
2294 SceneInput2 = Input { SourceOp = "Rep", Source = "Output", },
2295 }, },"#,
2296 );
2297 let (_, meshes, _) = collect(&src, "M");
2298 // 1 deformed plane + 4 replicated instances (8 unique cube corners / Step 2).
2299 assert_eq!(meshes.len(), 5);
2300 assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::CustomMesh(v) if !v.is_empty()));
2301 // Loop mode alternates Input1 (red) and Input2 (green).
2302 assert!((meshes[1].diffuse_col[0] - 1.0).abs() < 1e-4 && meshes[1].diffuse_col[1].abs() < 1e-4);
2303 assert!(meshes[2].diffuse_col[0].abs() < 1e-4 && (meshes[2].diffuse_col[1] - 1.0).abs() < 1e-4);
2304 }
2305
2306 #[test]
2307 fn spheremap_ward_reflect_and_chanbool_material_resolution() {
2308 let src = comp_src(
2309 r#"EnvBg = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 8, }, }, },
2310 DiffBg = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, }, },
2311 SMap = SphereMap { Inputs = {
2312 Image = Input { SourceOp = "EnvBg", Source = "Output", },
2313 ["Rotate.Y"] = Input { Value = 90.0, },
2314 StartAngle = Input { Value = 30.0, },
2315 EndAngle = Input { Value = 330.0, },
2316 }, },
2317 Ward = MtlWard { Inputs = {
2318 ["Diffuse.Color.Material"] = Input { SourceOp = "DiffBg", Source = "Output", },
2319 ["Specular.SpreadU"] = Input { Value = 0.04, },
2320 ["Specular.SpreadV"] = Input { Value = 0.28, },
2321 }, },
2322 Refl = MtlReflect { Inputs = {
2323 BackgroundMaterial = Input { SourceOp = "Ward", Source = "MaterialOutput", },
2324 ["Reflection.Color.Material"] = Input { SourceOp = "SMap", Source = "MaterialOutput", },
2325 ["Reflection.GlancingStrength"] = Input { Value = 0.9, },
2326 ["Reflection.FaceOnStrength"] = Input { Value = 0.15, },
2327 ["Reflection.Falloff"] = Input { Value = 3.0, },
2328 ["Refraction.RefractiveIndex.RGB"] = Input { Value = 1.5, },
2329 }, },
2330 FgBlinn = MtlBlinn { Inputs = {
2331 ["Diffuse.Color.Red"] = Input { Value = 0.2, },
2332 ["Diffuse.Color.Green"] = Input { Value = 0.4, },
2333 ["Diffuse.Color.Blue"] = Input { Value = 0.6, },
2334 }, },
2335 CB = MtlChanBool { Inputs = {
2336 BackgroundMaterial = Input { SourceOp = "Ward", Source = "MaterialOutput", },
2337 ForegroundMaterial = Input { SourceOp = "FgBlinn", Source = "MaterialOutput", },
2338 OperandAR = Input { Value = 4, },
2339 OperationR = Input { Value = 4, },
2340 OperandBR = Input { Value = 0, },
2341 CoordSpace = Input { Value = FuID { "World" }, },
2342 }, },
2343 S0 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "SMap", Source = "MaterialOutput", }, }, },
2344 S1 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Ward", Source = "MaterialOutput", }, }, },
2345 S2 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Refl", Source = "MaterialOutput", }, }, },
2346 S3 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "CB", Source = "MaterialOutput", }, }, },
2347 M = Merge3D { Inputs = {
2348 SceneInput1 = Input { SourceOp = "S0", Source = "Output", },
2349 SceneInput2 = Input { SourceOp = "S1", Source = "Output", },
2350 SceneInput3 = Input { SourceOp = "S2", Source = "Output", },
2351 SceneInput4 = Input { SourceOp = "S3", Source = "Output", },
2352 }, },"#,
2353 );
2354 let comp = Comp::from_fusion_str(&src).unwrap();
2355 let env_id = comp.find_node("EnvBg").unwrap();
2356 let diff_id = comp.find_node("DiffBg").unwrap();
2357 let (_, meshes, _) = collect(&src, "M");
2358 assert_eq!(meshes.len(), 4);
2359
2360 // SphereMap standalone
2361 let fx0 = meshes[0].shape.split_fx().1;
2362 assert_eq!(meshes[0].material_node, Some(env_id));
2363 assert_eq!(fx0.env_mode, 1);
2364 assert_eq!(fx0.env_tex_slot, 1);
2365
2366 // MtlWard
2367 let fx1 = meshes[1].shape.split_fx().1;
2368 assert_eq!(fx1.spec_model, SpecModel::Ward);
2369 assert!((meshes[1].specular_exponent - 0.04).abs() < 1e-5);
2370 assert!((fx1.ward_spread_v - 0.28).abs() < 1e-5);
2371
2372 // MtlReflect with both diffuse texture (in mat_tex) and SphereMap (in bump_tex slot 2)
2373 let fx2 = meshes[2].shape.split_fx().1;
2374 assert_eq!(meshes[2].material_node, Some(diff_id));
2375 assert_eq!(meshes[2].bump_node, Some(env_id));
2376 assert_eq!(fx2.env_mode, 2);
2377 assert_eq!(fx2.env_tex_slot, 2);
2378 assert!((fx2.refl_glancing_strength - 0.9).abs() < 1e-5);
2379 assert!((fx2.refl_face_on_strength - 0.15).abs() < 1e-5);
2380 assert!((fx2.refl_falloff - 3.0).abs() < 1e-5);
2381 assert!((fx2.refract_ior - 1.5).abs() < 1e-5);
2382
2383 // MtlChanBool
2384 let fx3 = meshes[3].shape.split_fx().1;
2385 assert!(fx3.cb_enabled);
2386 assert_eq!(fx3.cb_ops_a[0], 4);
2387 assert_eq!(fx3.cb_ops[0], 4);
2388 assert_eq!(fx3.cb_ops_b[0], 0);
2389 assert_eq!(fx3.cb_coord_space, 1);
2390 assert_eq!(fx3.sfx.layer, [layer_mode::CHAN_BOOL, 0.0, 1.0, 0.0], "a wired shader foreground is lit");
2391 assert!((fx3.sfx.layer_col[0] - 0.2).abs() < 1e-5 && (fx3.sfx.layer_col[2] - 0.6).abs() < 1e-5);
2392 }
2393}