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