authoravatarclover caruso<git@paperclover.net>2026-11-30 17:19:01-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 18:09:38-08:00
loged61cc49ec6096291f4e15915bd6cc130c9a65af
tree2890f0df2a947e115a8a00e3af7f5a26ee7b526b
parenta952b35a7e933e8fb662f6357a4d35328c0f561d
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Fix 3D pipeline parity across matrix_3d and archive 3D comps (#32)

matrix_3d goes from 0/11 to 10/11 under 1.5% MAE (case 7, Duplicate3D, is not drawn by the render node's software renderer; Fission keeps drawing it). - Camera3D: vertical AoV derives from FLength (default 35mm) and ApertureH, not the serialized AoV - Cube3D: only Width counts; one material per face via {Face}MaterialInput; cubes are subdivided (default 10) - Shape3D plane is square (Height follows Width), default 10 cells; sphere 20x20, cylinder r=1 h=2 20 segments - TextureTransformOperator: real Translation/Rotation.W/Scale/Pivot inputs, content-space semantics, pivot at 0 - Light decay is 1/d and 1/d^2; disabled and black lights no longer consume slots (8 slots) - Specular: Blinn/Phong default exponent 50 and intensity 1, true Phong, Beckmann Cook-Torrance (default roughness 0.6) - MtlStdInputs specular on surfaces; bump-only materials no longer tint the diffuse - Bare Texture2D materials render unlit; Displace3D adds (value+bias)*scale with Luma=0,R,G,B,A channels on existing vertices - Wireframe surfaces, per-surface visibility, lighting and cull inputs - Back faces draw before front faces so translucent surfaces show their inside Assisted-by: claude-sonnet-5.5

4 files changed, 825 insertions(+), 454 deletions(-)

crates/engine/src/scene3d/collect.rs+427-300
...@@ -5,8 +5,8 @@ use super::math::{...@@ -5,8 +5,8 @@ use super::math::{
5 mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,5 mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
6};6};
7use super::{7use super::{
8 CameraInstance, Displace3DSpec, Mat4, MeshInstance, PointLight, SceneLights, ShapeKind,8 CameraInstance, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights,
9 SpotLight, Text3DSpec,9 ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, CUBE_FACES,
10};10};
11use model::{Comp, ExprEngine, Node, NodeId};11use model::{Comp, ExprEngine, Node, NodeId};
1212
...@@ -16,6 +16,8 @@ struct SceneOverrides {...@@ -16,6 +16,8 @@ struct SceneOverrides {
16 affected_by_lights: Option<bool>,16 affected_by_lights: Option<bool>,
17 flip_normals: bool,17 flip_normals: bool,
18 displace: Option<Displace3DSpec>,18 displace: Option<Displace3DSpec>,
19 cull_back: bool,
20 cull_front: bool,
19}21}
2022
21fn splitmix64(mut x: u64) -> f32 {23fn splitmix64(mut x: u64) -> f32 {
...@@ -135,7 +137,7 @@ fn collect_scene_inner(...@@ -135,7 +137,7 @@ fn collect_scene_inner(
135 if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {137 if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {
136 let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32;138 let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32;
137 let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32;139 let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32;
138 let channel = comp.eval_number(node, "Channel", time, 4.0, expr).round() as i32;140 let channel = comp.eval_number(node, "Channel", time, 0.0, expr).round() as i32;
139 next_ovr.displace = Some(Displace3DSpec {141 next_ovr.displace = Some(Displace3DSpec {
140 input_node: in_id,142 input_node: in_id,
141 scale,143 scale,
...@@ -190,18 +192,19 @@ fn collect_scene_inner(...@@ -190,18 +192,19 @@ fn collect_scene_inner(
190 "Camera3D" => {192 "Camera3D" => {
191 let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32;193 let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32;
192 let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32;194 let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32;
193 // In Fusion .comp files, serialized AoV is always vertical degrees (AoVType only changes UI display).195 // Fusion derives the vertical AoV from FLength (default 35mm) and the film-gate height;
194 // When AoV is omitted, compute from FLength if present, else Fusion 21's default Camera3D vertical AoV (~24.302°).196 // a serialized AoV is only an echo of that, so it is the fallback when neither FLength
195 let has_aov = node.inputs.contains_key("AoV");197 // nor ApertureH is serialized (default Camera3D vertical AoV ~24.302°).
196 let has_fl = node.inputs.contains_key("FLength");198 let fl_mm = if node.inputs.contains_key("FLength") {
197 let aov_deg = if has_aov {199 Some(comp.eval_number(node, "FLength", time, 35.0, expr).max(0.5) as f32)
198 comp.eval_number(node, "AoV", time, 24.302, expr) as f32200 } else if node.inputs.contains_key("ApertureH") {
199 } else if has_fl {201 Some(35.0)
200 let fl_mm = comp.eval_number(node, "FLength", time, 24.0, expr).max(0.5) as f32;
201 let sensor_h_mm = ap_h * 25.4;
202 2.0 * (sensor_h_mm * 0.5 / fl_mm).atan().to_degrees()
203 } else {202 } else {
204 24.302203 None
204 };
205 let aov_deg = match fl_mm {
206 Some(fl) => 2.0 * (ap_h * 25.4 * 0.5 / fl).atan().to_degrees(),
207 None => comp.eval_number(node, "AoV", time, 24.302, expr) as f32,
205 };208 };
206 // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders)209 // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders)
207 let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height");210 let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height");
...@@ -220,47 +223,34 @@ fn collect_scene_inner(...@@ -220,47 +223,34 @@ fn collect_scene_inner(
220 cameras.push(CameraInstance { world, vfov_rad, near, far });223 cameras.push(CameraInstance { world, vfov_rad, near, far });
221 }224 }
222 "LightAmbient" => {225 "LightAmbient" => {
223 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;226 let Some(color) = light_color(comp, node, time, expr) else { return };
224 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;227 for (acc, c) in lights.ambient.iter_mut().zip(color) {
225 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;228 *acc += c;
226 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;229 }
227 lights.ambient[0] += r * inten;
228 lights.ambient[1] += g * inten;
229 lights.ambient[2] += b * inten;
230 }230 }
231 "LightDirectional" => {231 "LightDirectional" => {
232 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;232 let Some(color) = light_color(comp, node, time, expr) else { return };
233 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
234 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
235 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
236 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!233 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!
237 let dx = world[8];234 let dx = world[8];
238 let dy = world[9];235 let dy = world[9];
239 let dz = world[10];236 let dz = world[10];
240 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);237 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
241 lights.dir_to_light = [dx / len, dy / len, dz / len];238 lights.dir_to_light = [dx / len, dy / len, dz / len];
242 lights.dir_color = [r * inten, g * inten, b * inten];239 lights.dir_color = color;
243 lights.has_dir = true;240 lights.has_dir = true;
244 }241 }
245 "LightPoint" => {242 "LightPoint" => {
246 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;243 let Some(color) = light_color(comp, node, time, expr) else { return };
247 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
248 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
249 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
250 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;244 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
251 let decay_rate = comp.eval_number(node, "DecayRate", time, 1.0, expr) as f32;
252 lights.points.push(PointLight {245 lights.points.push(PointLight {
253 pos: [world[12], world[13], world[14]],246 pos: [world[12], world[13], world[14]],
254 color: [r * inten, g * inten, b * inten],247 color,
255 decay_type,248 decay_type,
256 decay_rate,249 decay_rate: 1.0,
257 });250 });
258 }251 }
259 "LightSpot" => {252 "LightSpot" => {
260 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;253 let Some(color) = light_color(comp, node, time, expr) else { return };
261 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
262 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
263 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
264 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;254 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;
265 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;255 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;
266 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;256 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
...@@ -275,59 +265,53 @@ fn collect_scene_inner(...@@ -275,59 +265,53 @@ fn collect_scene_inner(
275 lights.spots.push(SpotLight {265 lights.spots.push(SpotLight {
276 pos: [world[12], world[13], world[14]],266 pos: [world[12], world[13], world[14]],
277 dir: [dx / len, dy / len, dz / len],267 dir: [dx / len, dy / len, dz / len],
278 color: [r * inten, g * inten, b * inten],268 color,
279 cos_inner: inner_deg.to_radians().cos(),269 cos_inner: inner_deg.to_radians().cos(),
280 cos_outer: outer_deg.to_radians().cos(),270 cos_outer: outer_deg.to_radians().cos(),
281 decay_type,271 decay_type,
282 });272 });
283 }273 }
284 "ImagePlane3D" => {274 "ImagePlane3D" => {
275 let Some(own) = surface_scope(comp, node, "SurfacePlaneInputs", ovr, time, expr) else { return };
285 let mat_node = ovr.material_override.or_else(|| {276 let mat_node = ovr.material_override.or_else(|| {
286 node.connected_node("MaterialInput")277 node.connected_node("MaterialInput")
287 .or_else(|| node.connected_node("SceneInput"))278 .or_else(|| node.connected_node("SceneInput"))
288 .and_then(|s| comp.find_node(s))279 .and_then(|s| comp.find_node(s))
289 });280 });
290 let mat = resolve_material(comp, mat_node, time, expr);281 let mat = resolve_material(comp, mat_node, time, expr);
291 meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, ovr));282 meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own));
292 }283 }
293 "Shape3D" => {284 "Shape3D" => {
294 let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs");285 let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs");
295 let disp_sub = if ovr.displace.is_some() { 32 } else { 1 };286 let Some(own) = surface_scope(comp, node, shape_name, ovr, time, expr) else { return };
296 let shape = match shape_name {287 let shape = match shape_name {
297 "SurfaceSphereInputs" => ShapeKind::Sphere {288 "SurfaceSphereInputs" => ShapeKind::Sphere {
298 // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00)289 // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00)
299 radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32,290 radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32,
300 sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 32.0, expr).round() as u32,291 sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,
301 sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32,292 sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 20.0, expr).round() as u32,
302 },293 },
303 "SurfaceCylinderInputs" => {294 "SurfaceCylinderInputs" => {
304 let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32;295 let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32;
305 let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32;296 let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32;
306 ShapeKind::Cylinder {297 ShapeKind::Cylinder {
307 radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 0.5, expr) as f32,298 radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 1.0, expr) as f32,
308 height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 1.0, expr) as f32,299 height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 2.0, expr) as f32,
309 start_sweep_deg: start_sw,300 start_sweep_deg: start_sw,
310 end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw },301 end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw },
311 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32,302 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,
312 }
313 }
314 "SurfaceCubeInputs" => {
315 let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr);
316 ShapeKind::Cube {
317 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32,
318 height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32,
319 depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32,
320 }303 }
321 }304 }
305 "SurfaceCubeInputs" => ShapeKind::Cube {
306 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32,
307 sub: cube_subdivisions(comp, node, time, expr),
308 faces: 0b11_1111,
309 },
322 _ => {310 _ => {
323 let sw = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32;311 // Fusion's plane is square: Height and SubdivisionHeight follow Width.
324 let sh = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionHeight", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32;312 let sub = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, 10.0, expr).round() as u32;
325 ShapeKind::Plane {313 let width = comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32;
326 width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32,314 ShapeKind::Plane { width, height: width, sub_w: sub, sub_h: sub }
327 height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32,
328 sub_w: sw,
329 sub_h: sh,
330 }
331 }315 }
332 };316 };
333 let mat_node = ovr.material_override.or_else(|| {317 let mat_node = ovr.material_override.or_else(|| {
...@@ -336,83 +320,67 @@ fn collect_scene_inner(...@@ -336,83 +320,67 @@ fn collect_scene_inner(
336 });320 });
337 let mut mat = resolve_material(comp, mat_node, time, expr);321 let mut mat = resolve_material(comp, mat_node, time, expr);
338 if mat_node.is_none() {322 if mat_node.is_none() {
339 mat.diffuse_col = [323 apply_mtl_std(&mut mat, comp, node, "", time, expr);
340 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32,
341 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32,
342 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32,
343 comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32,
344 ];
345 }324 }
346 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));325 mat.fx.wireframe = comp.eval_number(node, &format!("{shape_name}.Wireframe"), time, 0.0, expr) > 0.5;
326 meshes.push(make_mesh_instance(world, shape, mat, None, &own));
347 }327 }
348 "Cube3D" => {328 "Cube3D" => {
349 let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr);329 if let Some(own) = surface_scope(comp, node, "SurfaceCubeInputs", ovr, time, expr) {
350 let shape = ShapeKind::Cube {330 // Fusion's Cube3D only honors Width (all edges) and takes one material per face.
351 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32,331 let width = comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32;
352 height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32,332 let wireframe = comp.eval_number(node, "SurfaceCubeInputs.Wireframe", time, 0.0, expr) > 0.5;
353 depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32,333 let sub = cube_subdivisions(comp, node, time, expr);
354 };334 let mut groups: Vec<(Option<NodeId>, ResolvedMaterial, u8)> = Vec::new();
355 let mat_node = ovr.material_override.or_else(|| {335 for (i, face) in CUBE_FACES.iter().enumerate() {
356 [336 let mat_node = ovr.material_override.or_else(|| {
357 "MaterialInput",337 node.connected_node(&format!("{face}MaterialInput"))
358 "FrontMaterialInput",338 .and_then(|s| comp.find_node(s))
359 "BackMaterialInput",339 });
360 "RightMaterialInput",340 let mut mat = resolve_material(comp, mat_node, time, expr);
361 "LeftMaterialInput",341 if mat_node.is_none() {
362 "TopMaterialInput",342 apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr);
363 "BottomMaterialInput",343 }
364 ]344 mat.fx.wireframe = wireframe;
365 .iter()345 match groups.iter_mut().find(|(n, m, _)| *n == mat_node && *m == mat) {
366 .find_map(|k| node.connected_node(k))346 Some((_, _, mask)) => *mask |= 1 << i,
367 .and_then(|s| comp.find_node(s))347 None => groups.push((mat_node, mat, 1 << i)),
368 });348 }
369 let mut mat = resolve_material(comp, mat_node, time, expr);349 }
370 if mat_node.is_none() {350 for (_, mat, faces) in groups {
371 let r_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr);351 meshes.push(make_mesh_instance(world, ShapeKind::Cube { width, sub, faces }, mat, None, &own));
372 let g_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr);352 }
373 let b_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr);
374 let a_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Opacity", time, 1.0, expr);
375 mat.diffuse_col = [
376 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, r_def, expr) as f32,
377 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, g_def, expr) as f32,
378 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, b_def, expr) as f32,
379 comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, a_def, expr) as f32,
380 ];
381 }353 }
382 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
383 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {354 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
384 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);355 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);
385 }356 }
386 }357 }
387 "SurfaceFBXMesh" => {358 "SurfaceFBXMesh" => {
388 let import_file = node.static_str("ImportFile").unwrap_or("");359 if let Some(own) = surface_scope(comp, node, "SurfaceFBXInputs", ovr, time, expr) {
389 let obj_name = node.static_str("ObjName");360 let import_file = node.static_str("ImportFile").unwrap_or("");
390 let scale_units = comp.eval_number(node, "ScaleFileUnitsBy", time, 1.0, expr) as f32;361 let obj_name = node.static_str("ObjName");
391 let verts = load_mesh_cached(import_file, comp.path.as_deref(), obj_name, scale_units);362 let scale_units = comp.eval_number(node, "ScaleFileUnitsBy", time, 1.0, expr) as f32;
392 let shape = ShapeKind::CustomMesh(verts);363 let verts = load_mesh_cached(import_file, comp.path.as_deref(), obj_name, scale_units);
393 let mat_node = ovr.material_override.or_else(|| {364 let shape = ShapeKind::CustomMesh(verts);
394 node.connected_node("MaterialInput")365 let mat_node = ovr.material_override.or_else(|| {
395 .or_else(|| {366 node.connected_node("MaterialInput")
396 let mut slots: Vec<&String> = node367 .or_else(|| {
397 .inputs368 let mut slots: Vec<&String> = node
398 .keys()369 .inputs
399 .filter(|k| k.starts_with("Materials."))370 .keys()
400 .collect();371 .filter(|k| k.starts_with("Materials."))
401 slots.sort();372 .collect();
402 slots.into_iter().find_map(|k| node.connected_node(k))373 slots.sort();
403 })374 slots.into_iter().find_map(|k| node.connected_node(k))
404 .and_then(|s| comp.find_node(s))375 })
405 });376 .and_then(|s| comp.find_node(s))
406 let mut mat = resolve_material(comp, mat_node, time, expr);377 });
407 if mat_node.is_none() {378 let mut mat = resolve_material(comp, mat_node, time, expr);
408 mat.diffuse_col = [379 if mat_node.is_none() {
409 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32,380 apply_mtl_std(&mut mat, comp, node, "", time, expr);
410 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32,381 }
411 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32,382 meshes.push(make_mesh_instance(world, shape, mat, None, &own));
412 comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32,
413 ];
414 }383 }
415 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
416 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {384 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
417 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);385 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);
418 }386 }
...@@ -445,18 +413,16 @@ fn collect_scene_inner(...@@ -445,18 +413,16 @@ fn collect_scene_inner(
445 }413 }
446}414}
447415
416#[derive(PartialEq)]
448struct ResolvedMaterial {417struct ResolvedMaterial {
449 tex_node: Option<NodeId>,418 tex_node: Option<NodeId>,
450 diffuse_col: [f32; 4],419 diffuse_col: [f32; 4],
451 specular_col: [f32; 3],420 specular_col: [f32; 3],
452 specular_intensity: f32,421 specular_intensity: f32,
453 specular_exponent: f32,422 specular_exponent: f32,
454 uv_offset: [f32; 2],423 fx: MaterialFx,
455 uv_scale: [f32; 2],424 /// A bare texture operator used as a surface's material renders flat, ignoring lights.
456 uv_rot: f32,425 unlit: bool,
457 uv_wrap: u32,
458 bump_scale: f32,
459 bump_mode: u32,
460}426}
461427
462impl Default for ResolvedMaterial {428impl Default for ResolvedMaterial {
...@@ -465,14 +431,10 @@ impl Default for ResolvedMaterial {...@@ -465,14 +431,10 @@ impl Default for ResolvedMaterial {
465 tex_node: None,431 tex_node: None,
466 diffuse_col: [1.0, 1.0, 1.0, 1.0],432 diffuse_col: [1.0, 1.0, 1.0, 1.0],
467 specular_col: [1.0, 1.0, 1.0],433 specular_col: [1.0, 1.0, 1.0],
468 specular_intensity: 0.15,434 specular_intensity: 1.0,
469 specular_exponent: 25.0,435 specular_exponent: 50.0,
470 uv_offset: [0.0, 0.0],436 fx: MaterialFx::default(),
471 uv_scale: [1.0, 1.0],437 unlit: false,
472 uv_rot: 0.0,
473 uv_wrap: 0,
474 bump_scale: 0.0,
475 bump_mode: 0,
476 }438 }
477 }439 }
478}440}
...@@ -484,54 +446,66 @@ fn make_mesh_instance(...@@ -484,54 +446,66 @@ fn make_mesh_instance(
484 text3d: Option<Text3DSpec>,446 text3d: Option<Text3DSpec>,
485 ovr: &SceneOverrides,447 ovr: &SceneOverrides,
486) -> MeshInstance {448) -> MeshInstance {
487 let has_fx = mat.uv_offset[0].abs() > 1e-6
488 || mat.uv_offset[1].abs() > 1e-6
489 || (mat.uv_scale[0] - 1.0).abs() > 1e-6
490 || (mat.uv_scale[1] - 1.0).abs() > 1e-6
491 || mat.uv_rot.abs() > 1e-6
492 || mat.uv_wrap != 0
493 || mat.bump_scale.abs() > 1e-6;
494 let wrapped_shape = if has_fx {
495 ShapeKind::WithMaterialFx {
496 inner: Box::new(shape),
497 uv_offset: mat.uv_offset,
498 uv_scale: mat.uv_scale,
499 uv_rot: mat.uv_rot,
500 uv_wrap: mat.uv_wrap,
501 bump_scale: mat.bump_scale,
502 bump_mode: mat.bump_mode,
503 }
504 } else {
505 shape
506 };
507 MeshInstance {449 MeshInstance {
508 world,450 world,
509 shape: wrapped_shape,451 shape: ShapeKind::WithMaterialFx {
452 inner: Box::new(shape),
453 fx: MaterialFx { cull_back: ovr.cull_back, cull_front: ovr.cull_front, ..mat.fx },
454 },
510 material_node: mat.tex_node,455 material_node: mat.tex_node,
511 text3d,456 text3d,
512 diffuse_col: mat.diffuse_col,457 diffuse_col: mat.diffuse_col,
513 specular_col: mat.specular_col,458 specular_col: mat.specular_col,
514 specular_intensity: mat.specular_intensity,459 specular_intensity: mat.specular_intensity,
515 specular_exponent: mat.specular_exponent,460 specular_exponent: mat.specular_exponent,
516 affected_by_lights: ovr.affected_by_lights.unwrap_or(true),461 affected_by_lights: !mat.unlit && ovr.affected_by_lights.unwrap_or(true),
517 flip_normals: ovr.flip_normals,462 flip_normals: ovr.flip_normals,
518 displace: ovr.displace.clone(),463 displace: ovr.displace.clone(),
519 uv_offset: mat.uv_offset,
520 uv_scale: mat.uv_scale,
521 uv_rot: mat.uv_rot,
522 uv_wrap: mat.uv_wrap,
523 bump_scale: mat.bump_scale,
524 bump_mode: mat.bump_mode,
525 }464 }
526}465}
527466
528fn eval_first_present(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f32 {467/// Applies a surface's own `<group>.Visibility.*` / `<group>.Lighting.IsAffectedByLights`
529 for &k in keys {468/// inputs on top of inherited overrides; `None` when the surface is hidden.
530 if node.inputs.contains_key(k) {469fn surface_scope(
531 return comp.eval_number(node, k, time, default, expr) as f32;470 comp: &Comp,
532 }471 node: &Node,
472 group: &str,
473 ovr: &SceneOverrides,
474 time: f64,
475 expr: &ExprEngine,
476) -> Option<SceneOverrides> {
477 let flag = |k: &str, d: f64| comp.eval_number(node, &format!("{group}.{k}"), time, d, expr) > 0.5;
478 flag("Visibility.IsVisible", 1.0).then(|| SceneOverrides {
479 affected_by_lights: ovr.affected_by_lights.or(Some(flag("Lighting.IsAffectedByLights", 1.0))),
480 cull_back: flag("Visibility.CullBackFace", 0.0),
481 cull_front: flag("Visibility.CullFrontFace", 0.0),
482 ..ovr.clone()
483 })
484}
485
486/// `Intensity * RGB` of a light, or `None` when it is disabled or contributes nothing.
487fn light_color(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option<[f32; 3]> {
488 if comp.eval_number(node, "Enabled", time, 1.0, expr) < 0.5 {
489 return None;
533 }490 }
534 default as f32491 let intensity = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
492 let color = ["Red", "Green", "Blue"].map(|k| comp.eval_number(node, k, time, 1.0, expr) as f32 * intensity);
493 (color != [0.0; 3]).then_some(color)
494}
495
496/// Cells per cube edge; Fusion's cube keeps all three subdivision counts equal.
497fn cube_subdivisions(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> u32 {
498 comp.eval_number(node, "SurfaceCubeInputs.SubdivisionWidth", time, 10.0, expr).round() as u32
499}
500
501/// Reads the built-in `MtlStdInputs` material (diffuse and Blinn specular) under an optional
502/// per-face `prefix` such as `"Front."` into `mat`.
503fn apply_mtl_std(mat: &mut ResolvedMaterial, comp: &Comp, node: &Node, prefix: &str, time: f64, expr: &ExprEngine) {
504 let f = |k: &str, d: f64| comp.eval_number(node, &format!("{prefix}MtlStdInputs.{k}"), time, d, expr) as f32;
505 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)];
506 mat.specular_col = [f("Specular.Color.Red", 1.0), f("Specular.Color.Green", 1.0), f("Specular.Color.Blue", 1.0)];
507 mat.specular_intensity = f("Specular.Intensity", 1.0).clamp(0.0, 4.0);
508 mat.specular_exponent = f("Specular.Exponent", 50.0).max(1.0);
535}509}
536510
537fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option<u32> {511fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option<u32> {
...@@ -553,6 +527,20 @@ fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Op...@@ -553,6 +527,20 @@ fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Op
553 None527 None
554}528}
555529
530/// Mesh-UV -> texture-UV map for a `TextureTransformOperator`. The content is moved by
531/// translate * rotate * scale about the pivot in V-up image space, so sampling applies the inverse.
532fn texture_transform_uv(translate: [f32; 2], rot_rad: f32, scale: [f32; 2], pivot: [f32; 2]) -> UvAffine {
533 let inv = |v: f32| 1.0 / if v.abs() < 1e-4 { 1e-4 } else { v };
534 let (sn, cs) = rot_rad.sin_cos();
535 let sample = |uv: [f32; 2]| {
536 let q = [uv[0] - translate[0] - pivot[0], (1.0 - uv[1]) - translate[1] - pivot[1]];
537 let r = [cs * q[0] + sn * q[1], -sn * q[0] + cs * q[1]];
538 [pivot[0] + r[0] * inv(scale[0]), 1.0 - (pivot[1] + r[1] * inv(scale[1]))]
539 };
540 let (o, eu, ev) = (sample([0.0, 0.0]), sample([1.0, 0.0]), sample([0.0, 1.0]));
541 UvAffine { m: [eu[0] - o[0], eu[1] - o[1], ev[0] - o[0], ev[1] - o[1]], t: o }
542}
543
556/// Resolves a 3D material input (`Texture2DOperator`, `TextureTransformOperator`, `BumpMap`,544/// Resolves a 3D material input (`Texture2DOperator`, `TextureTransformOperator`, `BumpMap`,
557/// `MtlBlinn`, `MtlCookTorrance`, `MtlPhong`, or a direct 2D image node).545/// `MtlBlinn`, `MtlCookTorrance`, `MtlPhong`, or a direct 2D image node).
558fn resolve_material(546fn resolve_material(
...@@ -582,36 +570,29 @@ fn resolve_material_inner(...@@ -582,36 +570,29 @@ fn resolve_material_inner(
582 match n.kind.as_str() {570 match n.kind.as_str() {
583 "Texture2DOperator" => {571 "Texture2DOperator" => {
584 let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s));572 let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s));
585 let uv_wrap = parse_wrap_mode(comp, n, time, expr).unwrap_or(0);
586 ResolvedMaterial {573 ResolvedMaterial {
587 tex_node: tex_src,574 tex_node: tex_src,
588 uv_wrap,575 fx: MaterialFx {
576 uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0),
577 ..default_mat.fx
578 },
579 unlit: true,
589 ..default_mat580 ..default_mat
590 }581 }
591 }582 }
592 "TextureTransformOperator" => {583 "TextureTransformOperator" => {
593 let inner_id = n584 let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s));
594 .connected_node("MaterialInput")
595 .or_else(|| n.connected_node("Input"))
596 .and_then(|s| comp.find_node(s));
597 let mut mat = resolve_material_inner(comp, inner_id, time, expr, depth + 1);585 let mut mat = resolve_material_inner(comp, inner_id, time, expr, depth + 1);
598 let tx = eval_first_present(comp, n, &["TranslationOffset.X", "Translation.U", "Translation.X"], time, 0.0, expr);586 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
599 let ty = eval_first_present(comp, n, &["TranslationOffset.Y", "Translation.V", "Translation.Y"], time, 0.0, expr);587 let xf = texture_transform_uv(
600 let sx = eval_first_present(comp, n, &["Scale.X", "Scale.U"], time, 1.0, expr);588 [f("Translation.U", 0.0), f("Translation.V", 0.0)],
601 let sy = eval_first_present(comp, n, &["Scale.Y", "Scale.V"], time, 1.0, expr);589 f("Rotation.W", 0.0).to_radians(),
602 let rot_deg = eval_first_present(590 [f("Scale.U", 1.0), f("Scale.V", 1.0)],
603 comp,591 [f("Pivot.U", 0.0), f("Pivot.V", 0.0)],
604 n,
605 &["Rotation.Z", "RotationOffset", "Rotation.W", "Rotation.U"],
606 time,
607 0.0,
608 expr,
609 );592 );
610 mat.uv_offset = [mat.uv_offset[0] + tx, mat.uv_offset[1] + ty];593 mat.fx.uv = xf.then(&mat.fx.uv);
611 mat.uv_scale = [mat.uv_scale[0] * sx, mat.uv_scale[1] * sy];
612 mat.uv_rot += rot_deg.to_radians();
613 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {594 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {
614 mat.uv_wrap = w;595 mat.fx.uv_wrap = w;
615 }596 }
616 mat597 mat
617 }598 }
...@@ -625,12 +606,14 @@ fn resolve_material_inner(...@@ -625,12 +606,14 @@ fn resolve_material_inner(
625 .round()606 .round()
626 .clamp(0.0, 1.0) as u32607 .clamp(0.0, 1.0) as u32
627 };608 };
628 let uv_wrap = parse_wrap_mode(comp, n, time, expr).unwrap_or(0);
629 ResolvedMaterial {609 ResolvedMaterial {
630 tex_node: src,610 tex_node: src,
631 uv_wrap,611 fx: MaterialFx {
632 bump_scale: height_scale,612 uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0),
633 bump_mode,613 bump_scale: height_scale,
614 bump_mode,
615 ..default_mat.fx
616 },
634 ..default_mat617 ..default_mat
635 }618 }
636 }619 }
...@@ -657,45 +640,34 @@ fn resolve_material_inner(...@@ -657,45 +640,34 @@ fn resolve_material_inner(
657 comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32,640 comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32,
658 ];641 ];
659 let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32;642 let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32;
660 let (spec_exp, spec_gain) = if n.kind == "MtlCookTorrance" {643 let (spec_exp, spec_model) = match n.kind.as_str() {
661 let rough = comp.eval_number(n, "Specular.Roughness", time, 0.4, expr).clamp(0.05, 1.0) as f32;644 "MtlCookTorrance" => (
662 ((2.0 / (rough * rough) - 2.0).max(2.0), 0.15)645 comp.eval_number(n, "Specular.Roughness", time, 0.6, expr).clamp(0.05, 1.0) as f32,
663 } else {646 SpecModel::CookTorrance,
664 (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0)647 ),
648 "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong),
649 _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn),
665 };650 };
666651
667 let mut tex_node = diff_mat.tex_node;652 let mut tex_node = diff_mat.tex_node;
668 let mut uv_offset = diff_mat.uv_offset;653 let mut fx = MaterialFx { spec_model, ..diff_mat.fx };
669 let mut uv_scale = diff_mat.uv_scale;
670 let mut uv_rot = diff_mat.uv_rot;
671 let mut uv_wrap = diff_mat.uv_wrap;
672 let mut bump_scale = diff_mat.bump_scale;
673 let mut bump_mode = diff_mat.bump_mode;
674
675 if let Some(bm) = bump_mat {654 if let Some(bm) = bump_mat {
676 bump_scale = if bm.bump_scale.abs() > 1e-6 { bm.bump_scale } else { 1.0 };
677 bump_mode = bm.bump_mode;
678 if tex_node.is_none() {655 if tex_node.is_none() {
679 tex_node = bm.tex_node;656 tex_node = bm.tex_node;
680 uv_offset = bm.uv_offset;657 fx = MaterialFx { bump_only: true, spec_model, ..bm.fx };
681 uv_scale = bm.uv_scale;
682 uv_rot = bm.uv_rot;
683 uv_wrap = bm.uv_wrap;
684 }658 }
659 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };
660 fx.bump_mode = bm.fx.bump_mode;
685 }661 }
686662
687 ResolvedMaterial {663 ResolvedMaterial {
688 tex_node,664 tex_node,
689 diffuse_col: col,665 diffuse_col: col,
690 specular_col: spec_col,666 specular_col: spec_col,
691 specular_intensity: spec_int.clamp(0.0, 4.0) * spec_gain,667 specular_intensity: spec_int.clamp(0.0, 4.0),
692 specular_exponent: spec_exp,668 specular_exponent: spec_exp,
693 uv_offset,669 fx,
694 uv_scale,670 unlit: false,
695 uv_rot,
696 uv_wrap,
697 bump_scale,
698 bump_mode,
699 }671 }
700 }672 }
701 _ => ResolvedMaterial {673 _ => ResolvedMaterial {
...@@ -911,67 +883,70 @@ mod tests {...@@ -911,67 +883,70 @@ mod tests {
911883
912 #[test]884 #[test]
913 fn test_collect_fbx_cube_tex_transform_and_bump() {885 fn test_collect_fbx_cube_tex_transform_and_bump() {
914 let src = r#"Composition {886 let faces: String = CUBE_FACES
887 .iter()
888 .map(|f| format!(r#"{f}MaterialInput = Input {{ SourceOp = "BlinnBump", Source = "MaterialOutput", }},"#))
889 .collect();
890 let src = format!(
891 r#"Composition {{
915 CurrentTime = 0,892 CurrentTime = 0,
916 RenderRange = { 0, 10 },893 RenderRange = {{ 0, 10 }},
917 GlobalRange = { 0, 10 },894 GlobalRange = {{ 0, 10 }},
918 Tools = ordered() {895 Tools = ordered() {{
919 BG1 = Background {896 BG1 = Background {{
920 Inputs = {897 Inputs = {{
921 Width = Input { Value = 64, },898 Width = Input {{ Value = 64, }},
922 Height = Input { Value = 64, },899 Height = Input {{ Value = 64, }},
923 },900 }},
924 },901 }},
925 Bump1 = BumpMap {902 Bump1 = BumpMap {{
926 Inputs = {903 Inputs = {{
927 Input = Input { SourceOp = "BG1", Source = "Output", },904 Input = Input {{ SourceOp = "BG1", Source = "Output", }},
928 HeightScale = Input { Value = 4.5, },905 HeightScale = Input {{ Value = 4.5, }},
929 SourceImageType = Input { Value = 1, },906 SourceImageType = Input {{ Value = 1, }},
930 WrapMode = Input { Value = FuID { "Wrap" }, },907 WrapMode = Input {{ Value = FuID {{ "Wrap" }}, }},
931 },908 }},
932 },909 }},
933 TexXf = TextureTransformOperator {910 TexXf = TextureTransformOperator {{
934 Inputs = {911 Inputs = {{
935 MaterialInput = Input { SourceOp = "Bump1", Source = "MaterialOutput", },912 MaterialInput = Input {{ SourceOp = "Bump1", Source = "MaterialOutput", }},
936 ["TranslationOffset.X"] = Input { Value = 0.25, },913 ["Translation.U"] = Input {{ Value = 0.25, }},
937 ["TranslationOffset.Y"] = Input { Value = -0.5, },914 ["Translation.V"] = Input {{ Value = -0.5, }},
938 ["Scale.U"] = Input { Value = 2.0, },915 }},
939 ["Scale.V"] = Input { Value = 3.0, },916 }},
940 ["Rotation.Z"] = Input { Value = 90.0, },917 BlinnBump = MtlBlinn {{
941 },918 Inputs = {{
942 },919 ["Diffuse.Color.Red"] = Input {{ Value = 0.7, }},
943 BlinnBump = MtlBlinn {920 ["Bumpmap.Material"] = Input {{ SourceOp = "TexXf", Source = "MaterialOutput", }},
944 Inputs = {921 }},
945 ["Diffuse.Color.Red"] = Input { Value = 0.7, },922 }},
946 ["Bumpmap.Material"] = Input { SourceOp = "TexXf", Source = "MaterialOutput", },923 CubeNode = Cube3D {{
947 },924 Inputs = {{
948 },925 ["SurfaceCubeInputs.Width"] = Input {{ Value = 2.0, }},
949 CubeNode = Cube3D {926 ["SurfaceCubeInputs.Height"] = Input {{ Value = 4.0, }},
950 Inputs = {927 ["Transform3DOp.Translate.Y"] = Input {{ Value = 1.5, }},
951 ["SurfaceCubeInputs.Size"] = Input { Value = 2.0, },928 {faces}
952 ["SurfaceCubeInputs.Height"] = Input { Value = 4.0, },929 }},
953 ["Transform3DOp.Translate.Y"] = Input { Value = 1.5, },930 }},
954 MaterialInput = Input { SourceOp = "BlinnBump", Source = "MaterialOutput", },931 FbxNode = SurfaceFBXMesh {{
955 },932 Inputs = {{
956 },933 ImportFile = Input {{ Value = "/does/not/exist/model.fbx", }},
957 FbxNode = SurfaceFBXMesh {934 ObjName = Input {{ Value = "HeroMesh", }},
958 Inputs = {935 ScaleFileUnitsBy = Input {{ Value = 0.01, }},
959 ImportFile = Input { Value = "/does/not/exist/model.fbx", },936 ["Transform3DOp.Translate.X"] = Input {{ Value = -2.0, }},
960 ObjName = Input { Value = "HeroMesh", },937 ["Materials.Mat0_mat0"] = Input {{ SourceOp = "TexXf", Source = "MaterialOutput", }},
961 ScaleFileUnitsBy = Input { Value = 0.01, },938 }},
962 ["Transform3DOp.Translate.X"] = Input { Value = -2.0, },939 }},
963 ["Materials.Mat0_mat0"] = Input { SourceOp = "TexXf", Source = "MaterialOutput", },940 Merge1 = Merge3D {{
964 },941 Inputs = {{
965 },942 SceneInput1 = Input {{ SourceOp = "CubeNode", Source = "Output", }},
966 Merge1 = Merge3D {943 SceneInput2 = Input {{ SourceOp = "FbxNode", Source = "Output", }},
967 Inputs = {944 }},
968 SceneInput1 = Input { SourceOp = "CubeNode", Source = "Output", },945 }},
969 SceneInput2 = Input { SourceOp = "FbxNode", Source = "Output", },946 }},
970 },947 }}"#
971 },948 );
972 },949 let comp = Comp::from_fusion_str(&src).expect("parse comp");
973 }"#;
974 let comp = Comp::from_fusion_str(src).expect("parse comp");
975 let expr = ExprEngine::new();950 let expr = ExprEngine::new();
976 let merge_id = comp.find_node("Merge1").expect("Merge1");951 let merge_id = comp.find_node("Merge1").expect("Merge1");
977 let bg_id = comp.find_node("BG1").expect("BG1");952 let bg_id = comp.find_node("BG1").expect("BG1");
...@@ -990,32 +965,184 @@ mod tests {...@@ -990,32 +965,184 @@ mod tests {
990 &mut lights,965 &mut lights,
991 0,966 0,
992 );967 );
968 // Six identical face materials collapse into one cube; Height is ignored.
993 assert_eq!(meshes.len(), 2);969 assert_eq!(meshes.len(), 2);
994970
995 // Cube3D with Blinn + Bumpmap (TextureTransformOperator -> BumpMap)
996 let cube = &meshes[0];971 let cube = &meshes[0];
997 assert!(matches!(972 assert!(matches!(
998 cube.shape.base_shape(),973 cube.shape.base_shape(),
999 ShapeKind::Cube { width, height, depth }974 ShapeKind::Cube { width, faces: 0b11_1111, .. } if (*width - 2.0).abs() < 1e-4
1000 if (*width - 2.0).abs() < 1e-4 && (*height - 4.0).abs() < 1e-4 && (*depth - 2.0).abs() < 1e-4
1001 ));975 ));
1002 assert!((cube.world[13] - 1.5).abs() < 1e-4);976 assert!((cube.world[13] - 1.5).abs() < 1e-4);
1003 assert_eq!(cube.material_node, Some(bg_id));977 assert_eq!(cube.material_node, Some(bg_id));
1004 assert!((cube.diffuse_col[0] - 0.7).abs() < 1e-4);978 assert!((cube.diffuse_col[0] - 0.7).abs() < 1e-4);
1005 assert!((cube.bump_scale - 4.5).abs() < 1e-4);979 let fx = cube.shape.split_fx().1;
1006 assert_eq!(cube.bump_mode, 1);980 assert!((fx.bump_scale - 4.5).abs() < 1e-4);
1007 assert!((cube.uv_offset[0] - 0.25).abs() < 1e-4);981 assert_eq!(fx.bump_mode, 1);
1008 assert!((cube.uv_offset[1] + 0.5).abs() < 1e-4);982 assert!(!fx.bump_only || cube.material_node.is_some());
1009 assert!((cube.uv_scale[0] - 2.0).abs() < 1e-4);983 assert_eq!(fx.uv_wrap, 1);
1010 assert!((cube.uv_scale[1] - 3.0).abs() < 1e-4);984 // Content moved +0.25 in U and -0.5 in V (V up) samples from u-0.25 and v-0.5.
1011 assert!((cube.uv_rot - std::f32::consts::FRAC_PI_2).abs() < 1e-4);985 let sampled = fx.uv.apply([0.5, 0.5]);
1012 assert_eq!(cube.uv_wrap, 1);986 assert!((sampled[0] - 0.25).abs() < 1e-4 && sampled[1].abs() < 1e-4, "{sampled:?}");
1013987
1014 // SurfaceFBXMesh fallback unit box + Materials.* slot resolution
1015 let fbx = &meshes[1];988 let fbx = &meshes[1];
1016 assert!(matches!(fbx.shape.base_shape(), ShapeKind::CustomMesh(v) if v.len() == 36));989 assert!(matches!(fbx.shape.base_shape(), ShapeKind::CustomMesh(v) if v.len() == 36));
1017 assert!((fbx.world[12] + 2.0).abs() < 1e-4);990 assert!((fbx.world[12] + 2.0).abs() < 1e-4);
1018 assert_eq!(fbx.material_node, Some(bg_id));991 assert_eq!(fbx.material_node, Some(bg_id));
1019 assert!((fbx.bump_scale - 4.5).abs() < 1e-4);992 assert!((fbx.shape.split_fx().1.bump_scale - 4.5).abs() < 1e-4);
993 }
994
995 fn collect(src: &str, root: &str) -> (Vec<CameraInstance>, Vec<MeshInstance>, SceneLights) {
996 let comp = Comp::from_fusion_str(src).expect("parse comp");
997 let expr = ExprEngine::new();
998 let id = comp.find_node(root).expect("root node");
999 let (mut cams, mut meshes, mut lights) = (Vec::new(), Vec::new(), SceneLights::default());
1000 collect_scene(&comp, id, 0.0, &expr, mat4_identity(), 1.0, &mut cams, &mut meshes, &mut lights, 0);
1001 (cams, meshes, lights)
1002 }
1003
1004 fn comp_src(tools: &str) -> String {
1005 format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}")
1006 }
1007
1008 #[test]
1009 fn camera_vertical_aov_comes_from_default_35mm_focal_length() {
1010 // Serialized AoV is ignored: 35mm on a 1" gate gives 2*atan(12.7/35).
1011 let src = comp_src(
1012 r#"Cam = Camera3D { Inputs = { AoV = Input { Value = 35.0, }, ApertureW = Input { Value = 1.0, }, ApertureH = Input { Value = 1.0, }, }, },
1013 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#,
1014 );
1015 let (cams, ..) = collect(&src, "M");
1016 let expected = 2.0 * (12.7_f32 / 35.0).atan();
1017 assert!((cams[0].vfov_rad - expected).abs() < 1e-4, "{} vs {expected}", cams[0].vfov_rad);
1018
1019 let src = comp_src(
1020 r#"Cam = Camera3D { Inputs = { AoV = Input { Value = 35.0, }, ApertureH = Input { Value = 1.0, }, FLength = Input { Value = 50.0, }, }, },
1021 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#,
1022 );
1023 let (cams, ..) = collect(&src, "M");
1024 assert!((cams[0].vfov_rad - 2.0 * (12.7_f32 / 50.0).atan()).abs() < 1e-4);
1025 }
1026
1027 #[test]
1028 fn plane_is_square_and_defaults_to_ten_cells() {
1029 let src = comp_src(
1030 r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.Height"] = Input { Value = 1.0, }, ["SurfacePlaneInputs.SubdivisionHeight"] = Input { Value = 3, }, }, },
1031 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "P", Source = "Output", }, }, },"#,
1032 );
1033 let (_, meshes, _) = collect(&src, "M");
1034 assert!(matches!(
1035 meshes[0].shape.base_shape(),
1036 ShapeKind::Plane { width, height, sub_w: 10, sub_h: 10 } if *width == 2.0 && *height == 2.0
1037 ));
1038 }
1039
1040 #[test]
1041 fn cube3d_ignores_plain_material_input_and_splits_by_face_material() {
1042 let src = comp_src(
1043 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
1044 Tex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, }, },
1045 Plain = Cube3D { Inputs = { MaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },
1046 Front = Cube3D { Inputs = { FrontMaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },
1047 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Plain", Source = "Output", }, SceneInput2 = Input { SourceOp = "Front", Source = "Output", }, }, },"#,
1048 );
1049 let (_, meshes, _) = collect(&src, "M");
1050 let tex = Comp::from_fusion_str(&src).unwrap().find_node("Bg");
1051 assert_eq!(meshes.len(), 3);
1052 assert!(meshes[0].material_node.is_none(), "Cube3D has no plain MaterialInput");
1053 assert!(matches!(meshes[1].shape.base_shape(), ShapeKind::Cube { faces: 0b00_0001, .. }));
1054 assert_eq!(meshes[1].material_node, tex);
1055 assert!(matches!(meshes[2].shape.base_shape(), ShapeKind::Cube { faces: 0b11_1110, .. }));
1056 }
1057
1058 #[test]
1059 fn texture_transform_moves_content_about_a_bottom_left_pivot() {
1060 // Scale 2 about the (0, 0) pivot zooms toward the bottom-left corner (V up).
1061 let zoom = texture_transform_uv([0.0, 0.0], 0.0, [2.0, 2.0], [0.0, 0.0]);
1062 let (bl, tr) = (zoom.apply([0.0, 1.0]), zoom.apply([1.0, 0.0]));
1063 assert!(bl[0].abs() < 1e-5 && (bl[1] - 1.0).abs() < 1e-5);
1064 assert!((tr[0] - 0.5).abs() < 1e-5 && (tr[1] - 0.5).abs() < 1e-5);
1065
1066 // Content moved right and up samples from smaller u and larger raw v (V down).
1067 let shift = texture_transform_uv([0.25, 0.1], 0.0, [1.0, 1.0], [0.0, 0.0]).apply([0.5, 0.5]);
1068 assert!((shift[0] - 0.25).abs() < 1e-5 && (shift[1] - 0.6).abs() < 1e-5);
1069
1070 // Counter-clockwise content rotation about the pivot.
1071 let quarter = texture_transform_uv([0.0, 0.0], std::f32::consts::FRAC_PI_2, [1.0, 1.0], [0.0, 0.0]);
1072 let p = quarter.apply([0.0, 0.0]); // top-left corner samples from the content to its right
1073 assert!((p[0] - 1.0).abs() < 1e-5 && (p[1] - 1.0).abs() < 1e-5, "{p:?}");
1074 }
1075
1076 #[test]
1077 fn disabled_and_black_lights_do_not_take_slots() {
1078 let spot = |name: &str, extra: &str| format!("{name} = LightSpot {{ Inputs = {{ {extra} }}, }},");
1079 let src = comp_src(&format!(
1080 "{} {} {} Live = LightSpot {{ }}, M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = \"Off\", Source = \"Output\", }}, SceneInput2 = Input {{ SourceOp = \"Dark\", Source = \"Output\", }}, SceneInput3 = Input {{ SourceOp = \"Live\", Source = \"Output\", }}, }}, }},",
1081 spot("Off", "Enabled = Input { Value = 0, },"),
1082 spot("Dark", "Intensity = Input { Value = 0, },"),
1083 ""
1084 ));
1085 let (_, _, lights) = collect(&src, "M");
1086 assert_eq!(lights.spots.len(), 1);
1087 assert_eq!(lights.spots[0].color, [1.0, 1.0, 1.0]);
1088 }
1089
1090 #[test]
1091 fn surface_visibility_lighting_and_bare_texture_flags() {
1092 let src = comp_src(
1093 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
1094 Tex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, }, },
1095 Blinn = MtlBlinn { Inputs = { ["Diffuse.Color.Material"] = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },
1096 Hidden = Shape3D { Inputs = { ["SurfacePlaneInputs.Visibility.IsVisible"] = Input { Value = 0, }, }, },
1097 Unlit = Shape3D { Inputs = { ["SurfacePlaneInputs.Lighting.IsAffectedByLights"] = Input { Value = 0, }, }, },
1098 Flat = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },
1099 Shaded = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, },
1100 Forced = Override3D { Inputs = { SceneInput = Input { SourceOp = "Unlit", Source = "Output", }, ["Lighting.DoAffectedByLights"] = Input { Value = 1, }, ["Lighting.IsAffectedByLights"] = Input { Value = 1, }, }, },
1101 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", }, }, },"#,
1102 );
1103 let (_, meshes, _) = collect(&src, "M");
1104 let lit: Vec<bool> = meshes.iter().map(|m| m.affected_by_lights).collect();
1105 assert_eq!(lit, [false, false, true, true], "hidden surface dropped; own flag, bare texture, Blinn, override");
1106 }
1107
1108 #[test]
1109 fn specular_models_and_defaults() {
1110 let src = comp_src(
1111 r#"Blinn = MtlBlinn { }, Phong = MtlPhong { }, Cook = MtlCookTorrance { },
1112 A = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, },
1113 B = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Phong", Source = "MaterialOutput", }, }, },
1114 C = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Cook", Source = "MaterialOutput", }, }, },
1115 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output", }, SceneInput2 = Input { SourceOp = "B", Source = "Output", }, SceneInput3 = Input { SourceOp = "C", Source = "Output", }, }, },"#,
1116 );
1117 let (_, meshes, _) = collect(&src, "M");
1118 let models: Vec<_> = meshes.iter().map(|m| (m.shape.split_fx().1.spec_model, m.specular_exponent)).collect();
1119 assert_eq!(models, [(SpecModel::Blinn, 50.0), (SpecModel::Phong, 50.0), (SpecModel::CookTorrance, 0.6)]);
1120 }
1121
1122 #[test]
1123 fn bump_only_material_does_not_color_the_surface_and_wireframe_follows_shape_input() {
1124 let src = comp_src(
1125 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
1126 Bump = BumpMap { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, HeightScale = Input { Value = 2.0, }, }, },
1127 Blinn = MtlBlinn { Inputs = { ["Bumpmap.Material"] = Input { SourceOp = "Bump", Source = "MaterialOutput", }, }, },
1128 S = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Wireframe"] = Input { Value = 1, }, MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, },
1129 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, }, },"#,
1130 );
1131 let (_, meshes, _) = collect(&src, "M");
1132 let fx = meshes[0].shape.split_fx().1;
1133 assert!(fx.bump_only && fx.wireframe);
1134 assert_eq!(fx.bump_scale, 2.0);
1135 }
1136
1137 #[test]
1138 fn hidden_cube_still_passes_its_scene_input_through() {
1139 let src = comp_src(
1140 r#"Inner = Shape3D { },
1141 C = Cube3D { Inputs = { ["SurfaceCubeInputs.Visibility.IsVisible"] = Input { Value = 0, }, SceneInput = Input { SourceOp = "Inner", Source = "Output", }, }, },
1142 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "C", Source = "Output", }, }, },"#,
1143 );
1144 let (_, meshes, _) = collect(&src, "M");
1145 assert_eq!(meshes.len(), 1);
1146 assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::Plane { .. }));
1020 }1147 }
1021}1148}
crates/engine/src/scene3d/mesh.rs+114-49
...@@ -20,7 +20,7 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Verte...@@ -20,7 +20,7 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Verte
20 end_sweep_deg,20 end_sweep_deg,
21 sub_base,21 sub_base,
22 } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base),22 } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base),
23 ShapeKind::Cube { width, height, depth } => build_cube(*width, *height, *depth),23 ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces),
24 ShapeKind::CustomMesh(verts) => {24 ShapeKind::CustomMesh(verts) => {
25 let v = verts.as_ref().clone();25 let v = verts.as_ref().clone();
26 let idx = (0..v.len() as u32).collect();26 let idx = (0..v.len() as u32).collect();
...@@ -42,32 +42,46 @@ fn build_image_plane(tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) {...@@ -42,32 +42,46 @@ fn build_image_plane(tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) {
42 (verts, vec![0, 1, 2, 0, 2, 3])42 (verts, vec![0, 1, 2, 0, 2, 3])
43}43}
4444
45fn build_plane(width: f32, height: f32, sub_w: u32, sub_h: u32) -> (Vec<Vertex3D>, Vec<u32>) {45/// Appends a `sub_w` x `sub_h` grid spanning the quad `tl`/`tr`/`bl` (UV `(0,0)` at `tl`, V down),
46 let sw = sub_w.clamp(1, 64);46/// splitting each cell along its bottom-left to top-right diagonal.
47 let sh = sub_h.clamp(1, 64);47fn push_quad_grid(
48 let hx = width * 0.5;48 verts: &mut Vec<Vertex3D>,
49 let hy = height * 0.5;49 idx: &mut Vec<u32>,
50 let mut verts = Vec::with_capacity(((sw + 1) * (sh + 1)) as usize);50 normal: [f32; 3],
51 let mut idx = Vec::with_capacity((sw * sh * 6) as usize);51 [tl, tr, bl]: [[f32; 3]; 3],
52 for iy in 0..=sh {52 sub_w: u32,
53 let v = iy as f32 / sh as f32;53 sub_h: u32,
54 let y = hy - v * height;54) {
55 for ix in 0..=sw {55 let base = verts.len() as u32;
56 let u = ix as f32 / sw as f32;56 for iy in 0..=sub_h {
57 let x = -hx + u * width;57 let v = iy as f32 / sub_h as f32;
58 verts.push(Vertex3D { pos: [x, y, 0.0], normal: [0.0, 0.0, 1.0], uv: [u, v] });58 for ix in 0..=sub_w {
59 let u = ix as f32 / sub_w as f32;
60 let pos = std::array::from_fn(|k| tl[k] + (tr[k] - tl[k]) * u + (bl[k] - tl[k]) * v);
61 verts.push(Vertex3D { pos, normal, uv: [u, v] });
59 }62 }
60 }63 }
61 let row = sw + 1;64 let row = sub_w + 1;
62 for iy in 0..sh {65 for iy in 0..sub_h {
63 for ix in 0..sw {66 for ix in 0..sub_w {
64 let a = iy * row + ix;67 let a = base + iy * row + ix;
65 let b = (iy + 1) * row + ix;68 let (b, c, d) = (a + row, a + row + 1, a + 1);
66 let c = (iy + 1) * row + ix + 1;69 idx.extend_from_slice(&[a, b, d, b, c, d]);
67 let d = iy * row + ix + 1;
68 idx.extend_from_slice(&[a, b, c, a, c, d]);
69 }70 }
70 }71 }
72}
73
74fn build_plane(width: f32, height: f32, sub_w: u32, sub_h: u32) -> (Vec<Vertex3D>, Vec<u32>) {
75 let (hx, hy) = (width * 0.5, height * 0.5);
76 let (mut verts, mut idx) = (Vec::new(), Vec::new());
77 push_quad_grid(
78 &mut verts,
79 &mut idx,
80 [0.0, 0.0, 1.0],
81 [[-hx, hy, 0.0], [hx, hy, 0.0], [-hx, -hy, 0.0]],
82 sub_w.clamp(1, 64),
83 sub_h.clamp(1, 64),
84 );
71 (verts, idx)85 (verts, idx)
72}86}
7387
...@@ -123,7 +137,7 @@ fn build_sphere(radius: f32, sub_base: u32, sub_height: u32) -> (Vec<Vertex3D>,...@@ -123,7 +137,7 @@ fn build_sphere(radius: f32, sub_base: u32, sub_height: u32) -> (Vec<Vertex3D>,
123 let b = (iv + 1) * row + iu;137 let b = (iv + 1) * row + iu;
124 let c = (iv + 1) * row + iu + 1;138 let c = (iv + 1) * row + iu + 1;
125 let d = iv * row + iu + 1;139 let d = iv * row + iu + 1;
126 idx.extend_from_slice(&[a, b, c, a, c, d]);140 idx.extend_from_slice(&[a, b, d, b, c, d]);
127 }141 }
128 }142 }
129 (verts, idx)143 (verts, idx)
...@@ -165,36 +179,45 @@ fn build_cylinder(...@@ -165,36 +179,45 @@ fn build_cylinder(
165 let b = a + 1;179 let b = a + 1;
166 let c = a + 3;180 let c = a + 3;
167 let d = a + 2;181 let d = a + 2;
168 idx.extend_from_slice(&[a, b, c, a, c, d]);182 idx.extend_from_slice(&[a, b, d, b, c, d]);
169 }183 }
170 (verts, idx)184 (verts, idx)
171}185}
172186
173fn build_cube(width: f32, height: f32, depth: f32) -> (Vec<Vertex3D>, Vec<u32>) {187fn build_cube(width: f32, sub: u32, faces_mask: u8) -> (Vec<Vertex3D>, Vec<u32>) {
174 let hx = width * 0.5;188 let h = width * 0.5;
175 let hy = height * 0.5;189 // `[tl, tr, bl]` per face in `CUBE_FACES` order.
176 let hz = depth * 0.5;190 let faces: [([f32; 3], [[f32; 3]; 3]); 6] = [
177 let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [191 ([0.0, 0.0, 1.0], [[-h, h, h], [h, h, h], [-h, -h, h]]),
178 ([0.0, 0.0, 1.0], [[-hx, hy, hz], [-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz]]),192 ([0.0, 0.0, -1.0], [[h, h, -h], [-h, h, -h], [h, -h, -h]]),
179 ([0.0, 0.0, -1.0], [[hx, hy, -hz], [hx, -hy, -hz], [-hx, -hy, -hz], [-hx, hy, -hz]]),193 ([1.0, 0.0, 0.0], [[h, h, h], [h, h, -h], [h, -h, h]]),
180 ([1.0, 0.0, 0.0], [[hx, hy, hz], [hx, -hy, hz], [hx, -hy, -hz], [hx, hy, -hz]]),194 ([-1.0, 0.0, 0.0], [[-h, h, -h], [-h, h, h], [-h, -h, -h]]),
181 ([-1.0, 0.0, 0.0], [[-hx, hy, -hz], [-hx, -hy, -hz], [-hx, -hy, hz], [-hx, hy, hz]]),195 ([0.0, 1.0, 0.0], [[-h, h, -h], [h, h, -h], [-h, h, h]]),
182 ([0.0, 1.0, 0.0], [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]]),196 ([0.0, -1.0, 0.0], [[-h, -h, h], [h, -h, h], [-h, -h, -h]]),
183 ([0.0, -1.0, 0.0], [[-hx, -hy, hz], [-hx, -hy, -hz], [hx, -hy, -hz], [hx, -hy, hz]]),
184 ];197 ];
185 let mut verts = Vec::with_capacity(24);198 let (mut verts, mut idx) = (Vec::new(), Vec::new());
186 let mut idx = Vec::with_capacity(36);199 for (i, (n, corners)) in faces.into_iter().enumerate() {
187 for (n, corners) in faces {200 if faces_mask & (1 << i) != 0 {
188 let base = verts.len() as u32;201 push_quad_grid(&mut verts, &mut idx, n, corners, sub, sub);
189 let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]];
190 for (p, uv) in corners.into_iter().zip(uvs) {
191 verts.push(Vertex3D { pos: p, normal: n, uv });
192 }202 }
193 idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
194 }203 }
195 (verts, idx)204 (verts, idx)
196}205}
197206
207/// Unique triangle edges as a line-list index buffer.
208pub(super) fn triangle_edges(indices: &[u32]) -> Vec<u32> {
209 let mut seen = std::collections::HashSet::new();
210 let mut edges = Vec::new();
211 for tri in indices.chunks_exact(3) {
212 for (a, b) in [(tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])] {
213 if seen.insert((a.min(b), a.max(b))) {
214 edges.extend_from_slice(&[a, b]);
215 }
216 }
217 }
218 edges
219}
220
198pub(super) fn apply_heightmap_displace(221pub(super) fn apply_heightmap_displace(
199 verts: &mut [Vertex3D],222 verts: &mut [Vertex3D],
200 indices: &[u32],223 indices: &[u32],
...@@ -214,13 +237,13 @@ pub(super) fn apply_heightmap_displace(...@@ -214,13 +237,13 @@ pub(super) fn apply_heightmap_displace(
214 let b = disp.rgba[off + 2] as f32 / 255.0;237 let b = disp.rgba[off + 2] as f32 / 255.0;
215 let a = disp.rgba[off + 3] as f32 / 255.0;238 let a = disp.rgba[off + 3] as f32 / 255.0;
216 let sample = match disp.channel {239 let sample = match disp.channel {
217 0 => r,240 1 => r,
218 1 => g,241 2 => g,
219 2 => b,242 3 => b,
220 3 => a,243 4 => a,
221 _ => 0.299 * r + 0.587 * g + 0.114 * b,244 _ => 0.299 * r + 0.587 * g + 0.114 * b,
222 };245 };
223 let d = (sample - 0.5 + disp.bias) * disp.scale;246 let d = (sample + disp.bias) * disp.scale;
224 v.pos[0] += v.normal[0] * d;247 v.pos[0] += v.normal[0] * d;
225 v.pos[1] += v.normal[1] * d;248 v.pos[1] += v.normal[1] * d;
226 v.pos[2] += v.normal[2] * d;249 v.pos[2] += v.normal[2] * d;
...@@ -255,3 +278,45 @@ pub(super) fn apply_heightmap_displace(...@@ -255,3 +278,45 @@ pub(super) fn apply_heightmap_displace(
255 }278 }
256 }279 }
257}280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 #[test]
287 fn plane_grid_splits_cells_along_bottom_left_to_top_right() {
288 let (verts, idx) = build_plane(2.0, 2.0, 2, 2);
289 assert_eq!(verts.len(), 9);
290 assert_eq!(idx.len(), 2 * 2 * 6);
291 // First cell: a = top-left (0), b = bottom-left (3), c = bottom-right (4), d = top-right (1).
292 assert_eq!(&idx[..6], &[0, 3, 1, 3, 4, 1]);
293 }
294
295 #[test]
296 fn cube_face_mask_and_subdivision_counts() {
297 let (all, all_idx) = build_cube(1.0, 3, 0b11_1111);
298 assert_eq!(all.len(), 6 * 16);
299 assert_eq!(all_idx.len(), 6 * 3 * 3 * 6);
300 let (front, _) = build_cube(1.0, 1, 0b00_0001);
301 assert!(front.iter().all(|v| v.normal == [0.0, 0.0, 1.0]));
302 }
303
304 #[test]
305 fn triangle_edges_are_deduplicated() {
306 // Two triangles sharing edge 1-2.
307 let edges = triangle_edges(&[0, 1, 2, 1, 3, 2]);
308 assert_eq!(edges.len(), 5 * 2);
309 }
310
311 #[test]
312 fn displace_channel_zero_is_luma_and_one_is_red() {
313 let displace = |channel| {
314 let (mut verts, idx) = build_plane(1.0, 1.0, 1, 1);
315 let disp = DisplaceHeightmap { size: [1, 1], rgba: vec![255, 0, 0, 255], scale: 1.0, bias: 0.0, channel };
316 apply_heightmap_displace(&mut verts, &idx, &disp);
317 verts[0].pos[2]
318 };
319 assert!((displace(1) - 1.0).abs() < 1e-4, "red channel");
320 assert!((displace(0) - 0.299).abs() < 1e-3, "luma");
321 }
322}
crates/engine/src/scene3d/mod.rs+227-68
...@@ -22,15 +22,17 @@ pub use shader::Vertex3D;...@@ -22,15 +22,17 @@ pub use shader::Vertex3D;
22use std::sync::Arc;22use std::sync::Arc;
2323
24use crate::cache::CachedTexture;24use crate::cache::CachedTexture;
25use mesh::{apply_heightmap_displace, build_shape_mesh};25use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};
26use model::NodeId;26use model::NodeId;
27use shader::{MeshUniform, SHADER_3D};27use shader::{MeshUniform, MAX_LIGHTS, SHADER_3D};
2828
29pub type Mat4 = [f32; 16]; // Column-major 4x429pub type Mat4 = [f32; 16]; // Column-major 4x4
3030
31pub struct Scene3DRenderer {31pub struct Scene3DRenderer {
32 bgl: wgpu::BindGroupLayout,32 bgl: wgpu::BindGroupLayout,
33 pipeline: wgpu::RenderPipeline,33 /// `[triangles, lines][back-facing, front-facing]`; back faces draw first so translucent
34 /// faces show the inside of closed meshes.
35 pipelines: [[wgpu::RenderPipeline; 2]; 2],
34 sampler: wgpu::Sampler,36 sampler: wgpu::Sampler,
35}37}
3638
...@@ -48,51 +50,102 @@ pub enum ShapeKind {...@@ -48,51 +50,102 @@ pub enum ShapeKind {
48 Sphere { radius: f32, sub_base: u32, sub_height: u32 },50 Sphere { radius: f32, sub_base: u32, sub_height: u32 },
49 Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 },51 Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 },
50 Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 },52 Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 },
51 Cube { width: f32, height: f32, depth: f32 },53 /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order.
54 Cube { width: f32, sub: u32, faces: u8 },
52 TextPlate { width: f32, height: f32, depth: f32, slices: u32 },55 TextPlate { width: f32, height: f32, depth: f32, slices: u32 },
53 CustomMesh(Arc<Vec<Vertex3D>>),56 CustomMesh(Arc<Vec<Vertex3D>>),
54 /// Wraps a base `ShapeKind` with UV transform and bump parameters so they travel57 /// Carries the material's UV transform and bump parameters through `DrawMesh`.
55 /// cleanly through `DrawMesh` into `Scene3DRenderer::render_meshes`.58 WithMaterialFx { inner: Box<ShapeKind>, fx: MaterialFx },
56 WithMaterialFx {59}
57 inner: Box<ShapeKind>,60
58 uv_offset: [f32; 2],61/// Face order shared by `Cube3D` material inputs and `build_cube`.
59 uv_scale: [f32; 2],62pub const CUBE_FACES: [&str; 6] = ["Front", "Back", "Right", "Left", "Top", "Bottom"];
60 uv_rot: f32,63
61 uv_wrap: u32,64/// Affine map from mesh UV (V down) to texture UV: `uv' = m * uv + t`, `m` column-major.
62 bump_scale: f32,65#[derive(Clone, Copy, Debug, PartialEq)]
63 bump_mode: u32,66pub struct UvAffine {
64 },67 pub m: [f32; 4],
68 pub t: [f32; 2],
69}
70
71impl UvAffine {
72 pub const IDENTITY: Self = Self { m: [1.0, 0.0, 0.0, 1.0], t: [0.0, 0.0] };
73
74 pub fn apply(&self, uv: [f32; 2]) -> [f32; 2] {
75 [
76 self.m[0] * uv[0] + self.m[2] * uv[1] + self.t[0],
77 self.m[1] * uv[0] + self.m[3] * uv[1] + self.t[1],
78 ]
79 }
80
81 /// The map applying `self` first, then `outer`.
82 pub fn then(&self, outer: &Self) -> Self {
83 let o = outer.apply(self.t);
84 Self {
85 m: [
86 outer.m[0] * self.m[0] + outer.m[2] * self.m[1],
87 outer.m[1] * self.m[0] + outer.m[3] * self.m[1],
88 outer.m[0] * self.m[2] + outer.m[2] * self.m[3],
89 outer.m[1] * self.m[2] + outer.m[3] * self.m[3],
90 ],
91 t: o,
92 }
93 }
94}
95
96/// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for
97/// `Blinn`/`Phong` and the roughness for `CookTorrance`.
98#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
99pub enum SpecModel {
100 #[default]
101 Blinn,
102 Phong,
103 CookTorrance,
104}
105
106#[derive(Clone, Copy, Debug, PartialEq)]
107pub struct MaterialFx {
108 pub uv: UvAffine,
109 /// 0 = clamp, 1 = wrap, 2 = mirror
110 pub uv_wrap: u32,
111 pub bump_scale: f32,
112 /// 0 = height map, 1 = normal map
113 pub bump_mode: u32,
114 /// The bound texture only perturbs normals; it does not color the surface.
115 pub bump_only: bool,
116 pub spec_model: SpecModel,
117 /// Draw the mesh edges as lines instead of filled triangles.
118 pub wireframe: bool,
119 pub cull_back: bool,
120 pub cull_front: bool,
121}
122
123impl Default for MaterialFx {
124 fn default() -> Self {
125 Self {
126 uv: UvAffine::IDENTITY,
127 uv_wrap: 0,
128 bump_scale: 0.0,
129 bump_mode: 0,
130 bump_only: false,
131 spec_model: SpecModel::Blinn,
132 wireframe: false,
133 cull_back: false,
134 cull_front: false,
135 }
136 }
65}137}
66138
67impl ShapeKind {139impl ShapeKind {
68 /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper.140 /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper.
69 pub fn base_shape(&self) -> &ShapeKind {141 pub fn base_shape(&self) -> &ShapeKind {
70 match self {142 self.split_fx().0
71 ShapeKind::WithMaterialFx { inner, .. } => inner.base_shape(),
72 other => other,
73 }
74 }143 }
75144
76 pub(super) fn unwrap_fx(&self) -> (&ShapeKind, [f32; 2], [f32; 2], f32, u32, f32, u32) {145 pub fn split_fx(&self) -> (&ShapeKind, MaterialFx) {
77 match self {146 match self {
78 ShapeKind::WithMaterialFx {147 ShapeKind::WithMaterialFx { inner, fx } => (inner.base_shape(), *fx),
79 inner,148 other => (other, MaterialFx::default()),
80 uv_offset,
81 uv_scale,
82 uv_rot,
83 uv_wrap,
84 bump_scale,
85 bump_mode,
86 } => (
87 inner.base_shape(),
88 *uv_offset,
89 *uv_scale,
90 *uv_rot,
91 *uv_wrap,
92 *bump_scale,
93 *bump_mode,
94 ),
95 other => (other, [0.0, 0.0], [1.0, 1.0], 0.0, 0, 0.0, 0),
96 }149 }
97 }150 }
98}151}
...@@ -102,7 +155,7 @@ pub struct Displace3DSpec {...@@ -102,7 +155,7 @@ pub struct Displace3DSpec {
102 pub input_node: NodeId,155 pub input_node: NodeId,
103 pub scale: f32,156 pub scale: f32,
104 pub bias: f32,157 pub bias: f32,
105 pub channel: i32, // 0=R, 1=G, 2=B, 3=A, 4=Luma (default)158 pub channel: i32, // 0=Luma (default), 1=R, 2=G, 3=B, 4=A
106}159}
107160
108#[derive(Clone, Debug)]161#[derive(Clone, Debug)]
...@@ -132,19 +185,15 @@ pub struct MeshInstance {...@@ -132,19 +185,15 @@ pub struct MeshInstance {
132 pub affected_by_lights: bool,185 pub affected_by_lights: bool,
133 pub flip_normals: bool,186 pub flip_normals: bool,
134 pub displace: Option<Displace3DSpec>,187 pub displace: Option<Displace3DSpec>,
135 pub uv_offset: [f32; 2],
136 pub uv_scale: [f32; 2],
137 pub uv_rot: f32,
138 pub uv_wrap: u32,
139 pub bump_scale: f32,
140 pub bump_mode: u32,
141}188}
142189
143#[derive(Clone, Copy, Debug)]190#[derive(Clone, Copy, Debug)]
144pub struct PointLight {191pub struct PointLight {
145 pub pos: [f32; 3],192 pub pos: [f32; 3],
146 pub color: [f32; 3],193 pub color: [f32; 3],
194 /// 0 = none, 1 = linear (1/d), 2 = quadratic (1/d²)
147 pub decay_type: f32,195 pub decay_type: f32,
196 /// Unused by the shader; `Renderer3D` still folds it into its cache key.
148 pub decay_rate: f32,197 pub decay_rate: f32,
149}198}
150199
...@@ -198,7 +247,7 @@ impl Scene3DRenderer {...@@ -198,7 +247,7 @@ impl Scene3DRenderer {
198 pub fn new(device: &wgpu::Device) -> Self {247 pub fn new(device: &wgpu::Device) -> Self {
199 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {248 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
200 label: Some("scene3d-shader"),249 label: Some("scene3d-shader"),
201 source: wgpu::ShaderSource::Wgsl(SHADER_3D.into()),250 source: wgpu::ShaderSource::Wgsl(SHADER_3D.replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()).into()),
202 });251 });
203 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {252 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
204 label: Some("scene3d-bgl"),253 label: Some("scene3d-bgl"),
...@@ -245,19 +294,22 @@ impl Scene3DRenderer {...@@ -245,19 +294,22 @@ impl Scene3DRenderer {
245 wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 },294 wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 },
246 ],295 ],
247 };296 };
248 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {297 let make_pipeline = |topology: wgpu::PrimitiveTopology, back_pass: bool| device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
249 label: Some("scene3d-mesh"),298 label: Some("scene3d-mesh"),
250 layout: Some(&pl),299 layout: Some(&pl),
251 vertex: wgpu::VertexState {300 vertex: wgpu::VertexState {
252 module: &shader,301 module: &shader,
253 entry_point: Some("vs_mesh"),302 entry_point: Some("vs_mesh"),
254 compilation_options: Default::default(),303 compilation_options: Default::default(),
255 buffers: &[Some(vbuf_layout)],304 buffers: &[Some(vbuf_layout.clone())],
256 },305 },
257 fragment: Some(wgpu::FragmentState {306 fragment: Some(wgpu::FragmentState {
258 module: &shader,307 module: &shader,
259 entry_point: Some("fs_mesh"),308 entry_point: Some("fs_mesh"),
260 compilation_options: Default::default(),309 compilation_options: wgpu::PipelineCompilationOptions {
310 constants: &[("BACK_PASS", if back_pass { 1.0 } else { 0.0 })],
311 ..Default::default()
312 },
261 targets: &[Some(wgpu::ColorTargetState {313 targets: &[Some(wgpu::ColorTargetState {
262 format: wgpu::TextureFormat::Rgba8Unorm,314 format: wgpu::TextureFormat::Rgba8Unorm,
263 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),315 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
...@@ -265,7 +317,7 @@ impl Scene3DRenderer {...@@ -265,7 +317,7 @@ impl Scene3DRenderer {
265 })],317 })],
266 }),318 }),
267 primitive: wgpu::PrimitiveState {319 primitive: wgpu::PrimitiveState {
268 topology: wgpu::PrimitiveTopology::TriangleList,320 topology,
269 cull_mode: None,321 cull_mode: None,
270 ..Default::default()322 ..Default::default()
271 },323 },
...@@ -280,6 +332,8 @@ impl Scene3DRenderer {...@@ -280,6 +332,8 @@ impl Scene3DRenderer {
280 multiview_mask: None,332 multiview_mask: None,
281 cache: None,333 cache: None,
282 });334 });
335 let pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList]
336 .map(|topology| [make_pipeline(topology, true), make_pipeline(topology, false)]);
283 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {337 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
284 label: Some("scene3d-linear"),338 label: Some("scene3d-linear"),
285 address_mode_u: wgpu::AddressMode::ClampToEdge,339 address_mode_u: wgpu::AddressMode::ClampToEdge,
...@@ -289,7 +343,7 @@ impl Scene3DRenderer {...@@ -289,7 +343,7 @@ impl Scene3DRenderer {
289 mipmap_filter: wgpu::MipmapFilterMode::Linear,343 mipmap_filter: wgpu::MipmapFilterMode::Linear,
290 ..Default::default()344 ..Default::default()
291 });345 });
292 Self { bgl, pipeline, sampler }346 Self { bgl, pipelines, sampler }
293 }347 }
294348
295 #[allow(clippy::too_many_arguments)]349 #[allow(clippy::too_many_arguments)]
...@@ -338,6 +392,9 @@ impl Scene3DRenderer {...@@ -338,6 +392,9 @@ impl Scene3DRenderer {
338 order.sort_by(|a, b| a.1.total_cmp(&b.1));392 order.sort_by(|a, b| a.1.total_cmp(&b.1));
339393
340 struct GpuDraw {394 struct GpuDraw {
395 wireframe: bool,
396 /// Skip the `[back-facing, front-facing]` pass.
397 cull: [bool; 2],
341 bg: wgpu::BindGroup,398 bg: wgpu::BindGroup,
342 vbuf: wgpu::Buffer,399 vbuf: wgpu::Buffer,
343 ibuf: wgpu::Buffer,400 ibuf: wgpu::Buffer,
...@@ -351,15 +408,17 @@ impl Scene3DRenderer {...@@ -351,15 +408,17 @@ impl Scene3DRenderer {
351 .as_ref()408 .as_ref()
352 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))409 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))
353 .unwrap_or(16.0 / 9.0);410 .unwrap_or(16.0 / 9.0);
354 let (base_shape, uv_offset, uv_scale, uv_rot, uv_wrap, bump_scale, bump_mode) =411 let (base_shape, fx) = m.shape.split_fx();
355 m.shape.unwrap_fx();412 let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect);
356 let (mut verts, indices) = build_shape_mesh(base_shape, aspect);
357 if indices.is_empty() {413 if indices.is_empty() {
358 continue;414 continue;
359 }415 }
360 if let Some(disp) = &m.displace {416 if let Some(disp) = &m.displace {
361 apply_heightmap_displace(&mut verts, &indices, disp);417 apply_heightmap_displace(&mut verts, &indices, disp);
362 }418 }
419 if fx.wireframe {
420 indices = triangle_edges(&indices);
421 }
363 let vbytes = bytemuck::cast_slice(&verts);422 let vbytes = bytemuck::cast_slice(&verts);
364 let ibytes = bytemuck::cast_slice(&indices);423 let ibytes = bytemuck::cast_slice(&indices);
365 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {424 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {
...@@ -387,18 +446,18 @@ impl Scene3DRenderer {...@@ -387,18 +446,18 @@ impl Scene3DRenderer {
387 } else {446 } else {
388 [0.0; 4]447 [0.0; 4]
389 };448 };
390 let mut point_pos = [[0.0_f32; 4]; 4];449 let mut point_pos = [[0.0_f32; 4]; MAX_LIGHTS];
391 let mut point_col = [[0.0_f32; 4]; 4];450 let mut point_col = [[0.0_f32; 4]; MAX_LIGHTS];
392 let n_pt = lights.points.len().min(4);451 let n_pt = lights.points.len().min(MAX_LIGHTS);
393 for (pi, pl) in lights.points.iter().take(4).enumerate() {452 for (pi, pl) in lights.points.iter().take(MAX_LIGHTS).enumerate() {
394 point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type];453 point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type];
395 point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], pl.decay_rate];454 point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], 0.0];
396 }455 }
397 let mut spot_pos = [[0.0_f32; 4]; 4];456 let mut spot_pos = [[0.0_f32; 4]; MAX_LIGHTS];
398 let mut spot_dir = [[0.0_f32; 4]; 4];457 let mut spot_dir = [[0.0_f32; 4]; MAX_LIGHTS];
399 let mut spot_col = [[0.0_f32; 4]; 4];458 let mut spot_col = [[0.0_f32; 4]; MAX_LIGHTS];
400 let n_sp = lights.spots.len().min(4);459 let n_sp = lights.spots.len().min(MAX_LIGHTS);
401 for (si, sl) in lights.spots.iter().take(4).enumerate() {460 for (si, sl) in lights.spots.iter().take(MAX_LIGHTS).enumerate() {
402 spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner];461 spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner];
403 spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer];462 spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer];
404 spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type];463 spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type];
...@@ -430,8 +489,9 @@ impl Scene3DRenderer {...@@ -430,8 +489,9 @@ impl Scene3DRenderer {
430 dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0],489 dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0],
431 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],490 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],
432 light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0],491 light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0],
433 uv_xform: [uv_offset[0], uv_offset[1], uv_scale[0], uv_scale[1]],492 uv_xform: fx.uv.m,
434 mat_fx: [uv_rot, uv_wrap as f32, bump_scale, bump_mode as f32],493 uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, 0.0],
494 mat_fx: [fx.bump_scale, fx.bump_mode as f32, if fx.bump_only { 1.0 } else { 0.0 }, fx.spec_model as u32 as f32],
435 point_pos,495 point_pos,
436 point_col,496 point_col,
437 spot_pos,497 spot_pos,
...@@ -456,6 +516,8 @@ impl Scene3DRenderer {...@@ -456,6 +516,8 @@ impl Scene3DRenderer {
456 ],516 ],
457 });517 });
458 draw_items.push(GpuDraw {518 draw_items.push(GpuDraw {
519 wireframe: fx.wireframe,
520 cull: [fx.cull_back, fx.cull_front],
459 bg,521 bg,
460 vbuf,522 vbuf,
461 ibuf,523 ibuf,
...@@ -486,12 +548,109 @@ impl Scene3DRenderer {...@@ -486,12 +548,109 @@ impl Scene3DRenderer {
486 occlusion_query_set: None,548 occlusion_query_set: None,
487 multiview_mask: None,549 multiview_mask: None,
488 });550 });
489 pass.set_pipeline(&self.pipeline);
490 for d in &draw_items {551 for d in &draw_items {
491 pass.set_bind_group(0, &d.bg, &[]);552 pass.set_bind_group(0, &d.bg, &[]);
492 pass.set_vertex_buffer(0, d.vbuf.slice(..));553 pass.set_vertex_buffer(0, d.vbuf.slice(..));
493 pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32);554 pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32);
494 pass.draw_indexed(0..d.idx_count, 0, 0..1);555 for (pipeline, culled) in self.pipelines[d.wireframe as usize].iter().zip(d.cull) {
556 if !culled {
557 pass.set_pipeline(pipeline);
558 pass.draw_indexed(0..d.idx_count, 0, 0..1);
559 }
560 }
495 }561 }
496 }562 }
497}563}
564
565#[cfg(test)]
566mod tests {
567 use super::*;
568 use crate::Engine;
569 use model::Comp;
570
571 /// Renders `Renderer3D` node `R` of a 64x64 scene viewed by a camera at z=4.2 (35mm lens, 1" gate).
572 fn render(lighting: bool, scene: &str) -> Option<Vec<u8>> {
573 let src = format!(
574 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{
575 Bg = Background {{ Inputs = {{ Width = Input {{ Value = 8, }}, Height = Input {{ Value = 8, }}, TopLeftRed = Input {{ Value = 1, }}, TopLeftGreen = Input {{ Value = 0.5, }}, TopLeftBlue = Input {{ Value = 0.25, }}, TopLeftAlpha = Input {{ Value = 1, }}, }}, }},
576 Tex = Texture2DOperator {{ Inputs = {{ Input = Input {{ SourceOp = "Bg", Source = "Output", }}, }}, }},
577 Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }},
578 Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.2, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }},
579 {scene}
580 R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, ["RendererSoftware.LightingEnabled"] = Input {{ Value = {}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }},
581 }} }}"#,
582 lighting as u8
583 );
584 let comp = Comp::from_fusion_str(&src).expect("parse render comp");
585 let mut eng = Engine::new_headless().ok()?;
586 let id = comp.find_node("R").expect("R");
587 let (tex, _) = eng.evaluate(&comp, id, 0.0);
588 eng.readback_rgba(&tex).ok()
589 }
590
591 fn center(px: &[u8]) -> [u8; 4] {
592 let i = (32 * 64 + 32) * 4;
593 [px[i], px[i + 1], px[i + 2], px[i + 3]]
594 }
595
596 const PLANE: &str = r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2, }, MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", }, }, },"#;
597
598 #[test]
599 fn point_light_decay_is_inverse_distance_and_inverse_square() {
600 for (decay, expected) in [(0, 255.0), (1, 127.5), (2, 63.75)] {
601 let scene = format!(
602 r#"{PLANE} L = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 2, }}, DecayType = Input {{ Value = {decay}, }}, }}, }},
603 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"#
604 );
605 let Some(px) = render(true, &scene) else { return };
606 let c = center(&px);
607 assert!((c[0] as f32 - expected).abs() <= 3.0, "decay {decay}: {c:?}");
608 }
609 }
610
611 #[test]
612 fn bare_texture_renders_unlit_but_blinn_diffuse_is_lit() {
613 let scene = |mat: &str| {
614 format!(
615 r#"Shaded = MtlBlinn {{ Inputs = {{ ["Diffuse.Color.Material"] = Input {{ SourceOp = "Tex", Source = "MaterialOutput", }}, }}, }},
616 P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 2, }}, MaterialInput = Input {{ SourceOp = "{mat}", Source = "MaterialOutput", }}, }}, }},
617 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"#
618 )
619 };
620 let (Some(flat), Some(shaded)) = (render(true, &scene("Tex")), render(true, &scene("Shaded"))) else { return };
621 assert_eq!(center(&flat), [255, 128, 64, 255]);
622 assert_eq!(center(&shaded)[..3], [0, 0, 0], "lighting on with no lights is black");
623 }
624
625 #[test]
626 fn wireframe_draws_edges_only() {
627 let scene = |wire: u8| {
628 format!(
629 r#"P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 2, }}, ["SurfacePlaneInputs.SubdivisionWidth"] = Input {{ Value = 2, }}, ["SurfacePlaneInputs.Wireframe"] = Input {{ Value = {wire}, }}, }}, }},
630 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"#
631 )
632 };
633 let (Some(solid), Some(wire)) = (render(false, &scene(0)), render(false, &scene(1))) else { return };
634 let coverage = |px: &[u8]| px.chunks_exact(4).filter(|c| c[3] > 0).count();
635 assert_eq!(center(&solid)[3], 255);
636 assert!(coverage(&wire) > 0 && coverage(&wire) < coverage(&solid) / 4, "{} vs {}", coverage(&wire), coverage(&solid));
637 }
638
639 #[test]
640 fn translucent_front_faces_show_the_inside_of_a_closed_mesh() {
641 // Half-opaque cube: front and back faces both blend, so coverage accumulates to 0.75.
642 let scene = r#"B = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, ["MtlStdInputs.Diffuse.Opacity"] = Input { Value = 0.5, }, }, },
643 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "B", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#;
644 let Some(px) = render(false, scene) else { return };
645 let alpha = center(&px)[3] as i32;
646 assert!((alpha - 191).abs() <= 3, "alpha {alpha}");
647 }
648
649 #[test]
650 fn uv_affine_then_applies_self_first() {
651 let shift = UvAffine { m: [1.0, 0.0, 0.0, 1.0], t: [0.5, 0.0] };
652 let double = UvAffine { m: [2.0, 0.0, 0.0, 2.0], t: [0.0, 0.0] };
653 assert_eq!(shift.then(&double).apply([0.0, 0.0]), [1.0, 0.0]);
654 assert_eq!(double.then(&shift).apply([0.0, 0.0]), [0.5, 0.0]);
655 }
656}
crates/engine/src/scene3d/shader.rs+57-37
...@@ -2,6 +2,9 @@...@@ -2,6 +2,9 @@
22
3use bytemuck::{Pod, Zeroable};3use bytemuck::{Pod, Zeroable};
44
5/// Point and spot lights each get this many shader slots.
6pub(super) const MAX_LIGHTS: usize = 8;
7
5#[repr(C)]8#[repr(C)]
6#[derive(Clone, Copy, Debug, Pod, Zeroable)]9#[derive(Clone, Copy, Debug, Pod, Zeroable)]
7pub struct Vertex3D {10pub struct Vertex3D {
...@@ -33,22 +36,25 @@ pub(super) struct MeshUniform {...@@ -33,22 +36,25 @@ pub(super) struct MeshUniform {
33 pub(super) cam_pos: [f32; 4],36 pub(super) cam_pos: [f32; 4],
34 /// `[num_point_lights, num_spot_lights, 0, 0]`37 /// `[num_point_lights, num_spot_lights, 0, 0]`
35 pub(super) light_counts: [f32; 4],38 pub(super) light_counts: [f32; 4],
36 /// UV transform `[offset_x, offset_y, scale_x, scale_y]`39 /// UV affine matrix, column-major `[m00, m10, m01, m11]`
37 pub(super) uv_xform: [f32; 4],40 pub(super) uv_xform: [f32; 4],
38 /// Material effects `[uv_rot_rad, uv_wrap_mode, bump_scale, bump_mode]`41 /// UV translation and wrap mode `[tx, ty, wrap, 0]`
42 pub(super) uv_off_wrap: [f32; 4],
43 /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance]`
39 pub(super) mat_fx: [f32; 4],44 pub(super) mat_fx: [f32; 4],
40 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`45 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`
41 pub(super) point_pos: [[f32; 4]; 4],46 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],
42 /// Point light colors * intensity `(r, g, b, decay_rate)`47 /// Point light colors * intensity `(r, g, b, 0)`
43 pub(super) point_col: [[f32; 4]; 4],48 pub(super) point_col: [[f32; 4]; MAX_LIGHTS],
44 /// Spot light positions `(x, y, z, cos_inner)`49 /// Spot light positions `(x, y, z, cos_inner)`
45 pub(super) spot_pos: [[f32; 4]; 4],50 pub(super) spot_pos: [[f32; 4]; MAX_LIGHTS],
46 /// Spot light forward directions `(dx, dy, dz, cos_outer)`51 /// Spot light forward directions `(dx, dy, dz, cos_outer)`
47 pub(super) spot_dir: [[f32; 4]; 4],52 pub(super) spot_dir: [[f32; 4]; MAX_LIGHTS],
48 /// Spot light colors * intensity `(r, g, b, decay_type)`53 /// Spot light colors * intensity `(r, g, b, decay_type)`
49 pub(super) spot_col: [[f32; 4]; 4],54 pub(super) spot_col: [[f32; 4]; MAX_LIGHTS],
50}55}
5156
57/// WGSL source; `MAX_LIGHTS` is substituted with the Rust constant at pipeline creation.
52pub(super) const SHADER_3D: &str = r#"58pub(super) const SHADER_3D: &str = r#"
53struct MeshUniform {59struct MeshUniform {
54 mvp: mat4x4<f32>,60 mvp: mat4x4<f32>,
...@@ -63,14 +69,17 @@ struct MeshUniform {...@@ -63,14 +69,17 @@ struct MeshUniform {
63 cam_pos: vec4<f32>,69 cam_pos: vec4<f32>,
64 light_counts: vec4<f32>,70 light_counts: vec4<f32>,
65 uv_xform: vec4<f32>,71 uv_xform: vec4<f32>,
72 uv_off_wrap: vec4<f32>,
66 mat_fx: vec4<f32>,73 mat_fx: vec4<f32>,
67 point_pos: array<vec4<f32>, 4>,74 point_pos: array<vec4<f32>, MAX_LIGHTS>,
68 point_col: array<vec4<f32>, 4>,75 point_col: array<vec4<f32>, MAX_LIGHTS>,
69 spot_pos: array<vec4<f32>, 4>,76 spot_pos: array<vec4<f32>, MAX_LIGHTS>,
70 spot_dir: array<vec4<f32>, 4>,77 spot_dir: array<vec4<f32>, MAX_LIGHTS>,
71 spot_col: array<vec4<f32>, 4>,78 spot_col: array<vec4<f32>, MAX_LIGHTS>,
72};79};
7380
81override BACK_PASS: bool = false;
82
74@group(0) @binding(0) var<uniform> u: MeshUniform;83@group(0) @binding(0) var<uniform> u: MeshUniform;
75@group(0) @binding(1) var mat_tex: texture_2d<f32>;84@group(0) @binding(1) var mat_tex: texture_2d<f32>;
76@group(0) @binding(2) var mat_samp: sampler;85@group(0) @binding(2) var mat_samp: sampler;
...@@ -105,14 +114,13 @@ fn vs_mesh(v: VsIn) -> VsOut {...@@ -105,14 +114,13 @@ fn vs_mesh(v: VsIn) -> VsOut {
105 return out;114 return out;
106}115}
107116
108fn light_attenuation(dist: f32, decay_type: f32, decay_rate: f32) -> f32 {117fn light_attenuation(dist: f32, decay_type: f32) -> f32 {
109 let dt = i32(decay_type + 0.5);118 let dt = i32(decay_type + 0.5);
110 let rate = max(decay_rate, 0.001);119 let d = max(dist, 1e-3);
111 if (dt == 1) {120 if (dt == 1) {
112 return 1.0 / max(1.0 + dist * rate, 1e-4);121 return 1.0 / d;
113 } else if (dt == 2) {122 } else if (dt == 2) {
114 let d = dist * rate;123 return 1.0 / (d * d);
115 return 1.0 / max(1.0 + d * d, 1e-4);
116 }124 }
117 return 1.0;125 return 1.0;
118}126}
...@@ -134,19 +142,27 @@ fn eval_light_contrib(...@@ -134,19 +142,27 @@ fn eval_light_contrib(
134 var out = albedo * light_rgb * ndotl;142 var out = albedo * light_rgb * ndotl;
135 if (spec_int > 1e-4) {143 if (spec_int > 1e-4) {
136 let h = normalize(l + v);144 let h = normalize(l + v);
137 let spec = pow(max(dot(n, h), 0.0), shininess) * spec_int;145 let model = i32(u.mat_fx.w + 0.5);
138 out = out + light_rgb * spec_rgb * spec;146 var lobe: f32;
147 if (model == 1) {
148 lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess);
149 } else if (model == 2) {
150 // Beckmann distribution; shininess carries roughness.
151 let nh = max(dot(n, h), 1e-3);
152 let m2 = max(shininess * shininess, 1e-3);
153 lobe = 0.03 * exp(-(1.0 - nh * nh) / (nh * nh * m2)) / (3.14159265 * m2 * nh * nh * nh * nh);
154 } else {
155 lobe = pow(max(dot(n, h), 0.0), shininess);
156 }
157 out = out + light_rgb * spec_rgb * (lobe * spec_int);
139 }158 }
140 return out;159 return out;
141}160}
142161
143fn apply_uv_xform(raw_uv: vec2<f32>, uv_xform: vec4<f32>, rot_wrap: vec2<f32>) -> vec2<f32> {162fn apply_uv_xform(raw_uv: vec2<f32>) -> vec2<f32> {
144 let p = raw_uv - vec2<f32>(0.5, 0.5);163 let m = u.uv_xform;
145 let c = cos(rot_wrap.x);164 var uv = vec2<f32>(m.x * raw_uv.x + m.z * raw_uv.y, m.y * raw_uv.x + m.w * raw_uv.y) + u.uv_off_wrap.xy;
146 let s = sin(rot_wrap.x);165 let wrap = i32(u.uv_off_wrap.z + 0.5);
147 let r = vec2<f32>(p.x * c - p.y * s, p.x * s + p.y * c);
148 var uv = r * uv_xform.zw + vec2<f32>(0.5, 0.5) + uv_xform.xy;
149 let wrap = i32(rot_wrap.y + 0.5);
150 if (wrap == 1) {166 if (wrap == 1) {
151 uv = fract(uv);167 uv = fract(uv);
152 } else if (wrap == 2) {168 } else if (wrap == 2) {
...@@ -210,7 +226,11 @@ fn perturb_bump_normal(...@@ -210,7 +226,11 @@ fn perturb_bump_normal(
210226
211@fragment227@fragment
212fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {228fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
213 let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.mat_fx.xy);229 let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0;
230 if (facing_away != BACK_PASS) {
231 discard;
232 }
233 let uv_xformed = apply_uv_xform(in.uv);
214 let dpdx_w = dpdx(in.world_pos);234 let dpdx_w = dpdx(in.world_pos);
215 let dpdy_w = dpdy(in.world_pos);235 let dpdy_w = dpdy(in.world_pos);
216 let duvdx = dpdx(uv_xformed);236 let duvdx = dpdx(uv_xformed);
...@@ -229,7 +249,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -229,7 +249,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
229 }249 }
230 }250 }
231 tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0);251 tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0);
232 col = tex_col * u.diffuse_col;252 col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col;
233 }253 }
234 if (col.a <= 0.002) {254 if (col.a <= 0.002) {
235 discard;255 discard;
...@@ -239,7 +259,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -239,7 +259,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
239 // Premultiplied -> unpremultiplied albedo for lighting259 // Premultiplied -> unpremultiplied albedo for lighting
240 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);260 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);
241 var n = normalize(in.world_n);261 var n = normalize(in.world_n);
242 if (u.flags.x > 0.5 && abs(u.mat_fx.z) > 1e-5) {262 if (u.flags.x > 0.5 && abs(u.mat_fx.x) > 1e-5) {
243 n = perturb_bump_normal(263 n = perturb_bump_normal(
244 n,264 n,
245 dpdx_w,265 dpdx_w,
...@@ -248,13 +268,13 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -248,13 +268,13 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
248 duvdy,268 duvdy,
249 uv_samp,269 uv_samp,
250 tex_col,270 tex_col,
251 u.mat_fx.z,271 u.mat_fx.x,
252 u.mat_fx.w,272 u.mat_fx.y,
253 );273 );
254 }274 }
255 let v = normalize(u.cam_pos.xyz - in.world_pos);275 let v = normalize(u.cam_pos.xyz - in.world_pos);
256 let spec_rgb = u.specular_col.rgb;276 let spec_rgb = u.specular_col.rgb;
257 let shininess = max(u.specular_col.w, 1.0);277 let shininess = select(max(u.specular_col.w, 1.0), u.specular_col.w, u.mat_fx.w > 1.5);
258 let spec_int = u.flags.z;278 let spec_int = u.flags.z;
259279
260 var lit = albedo * u.ambient.rgb;280 var lit = albedo * u.ambient.rgb;
...@@ -264,16 +284,16 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -264,16 +284,16 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
264 }284 }
265285
266 let n_pt = i32(u.light_counts.x + 0.5);286 let n_pt = i32(u.light_counts.x + 0.5);
267 for (var i: i32 = 0; i < 4; i = i + 1) {287 for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) {
268 if (i >= n_pt) { break; }288 if (i >= n_pt) { break; }
269 let to_l = u.point_pos[i].xyz - in.world_pos;289 let to_l = u.point_pos[i].xyz - in.world_pos;
270 let dist = max(length(to_l), 1e-4);290 let dist = max(length(to_l), 1e-4);
271 let att = light_attenuation(dist, u.point_pos[i].w, u.point_col[i].w);291 let att = light_attenuation(dist, u.point_pos[i].w);
272 lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);292 lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);
273 }293 }
274294
275 let n_sp = i32(u.light_counts.y + 0.5);295 let n_sp = i32(u.light_counts.y + 0.5);
276 for (var i: i32 = 0; i < 4; i = i + 1) {296 for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) {
277 if (i >= n_sp) { break; }297 if (i >= n_sp) { break; }
278 let to_l = u.spot_pos[i].xyz - in.world_pos;298 let to_l = u.spot_pos[i].xyz - in.world_pos;
279 let dist = max(length(to_l), 1e-4);299 let dist = max(length(to_l), 1e-4);
...@@ -284,7 +304,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -284,7 +304,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
284 let cos_outer = u.spot_dir[i].w;304 let cos_outer = u.spot_dir[i].w;
285 let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0);305 let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0);
286 if (cone > 0.0) {306 if (cone > 0.0) {
287 let att = light_attenuation(dist, u.spot_col[i].w, 1.0) * cone;307 let att = light_attenuation(dist, u.spot_col[i].w) * cone;
288 lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);308 lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);
289 }309 }
290 }310 }