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::{
55 mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
66};
77use super::{
8 CameraInstance, Displace3DSpec, Mat4, MeshInstance, PointLight, SceneLights, ShapeKind,
9 SpotLight, Text3DSpec,
8 CameraInstance, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights,
9 ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, CUBE_FACES,
1010};
1111use model::{Comp, ExprEngine, Node, NodeId};
1212
......@@ -16,6 +16,8 @@ struct SceneOverrides {
1616 affected_by_lights: Option<bool>,
1717 flip_normals: bool,
1818 displace: Option<Displace3DSpec>,
19 cull_back: bool,
20 cull_front: bool,
1921}
2022
2123fn splitmix64(mut x: u64) -> f32 {
......@@ -135,7 +137,7 @@ fn collect_scene_inner(
135137 if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {
136138 let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32;
137139 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;
139141 next_ovr.displace = Some(Displace3DSpec {
140142 input_node: in_id,
141143 scale,
......@@ -190,18 +192,19 @@ fn collect_scene_inner(
190192 "Camera3D" => {
191193 let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32;
192194 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).
194 // When AoV is omitted, compute from FLength if present, else Fusion 21's default Camera3D vertical AoV (~24.302°).
195 let has_aov = node.inputs.contains_key("AoV");
196 let has_fl = node.inputs.contains_key("FLength");
197 let aov_deg = if has_aov {
198 comp.eval_number(node, "AoV", time, 24.302, expr) as f32
199 } else if has_fl {
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()
195 // Fusion derives the vertical AoV from FLength (default 35mm) and the film-gate height;
196 // a serialized AoV is only an echo of that, so it is the fallback when neither FLength
197 // nor ApertureH is serialized (default Camera3D vertical AoV ~24.302°).
198 let fl_mm = if node.inputs.contains_key("FLength") {
199 Some(comp.eval_number(node, "FLength", time, 35.0, expr).max(0.5) as f32)
200 } else if node.inputs.contains_key("ApertureH") {
201 Some(35.0)
203202 } else {
204 24.302
203 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,
205208 };
206209 // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders)
207210 let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height");
......@@ -220,47 +223,34 @@ fn collect_scene_inner(
220223 cameras.push(CameraInstance { world, vfov_rad, near, far });
221224 }
222225 "LightAmbient" => {
223 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
224 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
225 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
226 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
227 lights.ambient[0] += r * inten;
228 lights.ambient[1] += g * inten;
229 lights.ambient[2] += b * inten;
226 let Some(color) = light_color(comp, node, time, expr) else { return };
227 for (acc, c) in lights.ambient.iter_mut().zip(color) {
228 *acc += c;
229 }
230230 }
231231 "LightDirectional" => {
232 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
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;
232 let Some(color) = light_color(comp, node, time, expr) else { return };
236233 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!
237234 let dx = world[8];
238235 let dy = world[9];
239236 let dz = world[10];
240237 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
241238 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;
243240 lights.has_dir = true;
244241 }
245242 "LightPoint" => {
246 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
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;
243 let Some(color) = light_color(comp, node, time, expr) else { return };
250244 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;
252245 lights.points.push(PointLight {
253246 pos: [world[12], world[13], world[14]],
254 color: [r * inten, g * inten, b * inten],
247 color,
255248 decay_type,
256 decay_rate,
249 decay_rate: 1.0,
257250 });
258251 }
259252 "LightSpot" => {
260 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
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;
253 let Some(color) = light_color(comp, node, time, expr) else { return };
264254 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;
265255 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;
266256 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
......@@ -275,59 +265,53 @@ fn collect_scene_inner(
275265 lights.spots.push(SpotLight {
276266 pos: [world[12], world[13], world[14]],
277267 dir: [dx / len, dy / len, dz / len],
278 color: [r * inten, g * inten, b * inten],
268 color,
279269 cos_inner: inner_deg.to_radians().cos(),
280270 cos_outer: outer_deg.to_radians().cos(),
281271 decay_type,
282272 });
283273 }
284274 "ImagePlane3D" => {
275 let Some(own) = surface_scope(comp, node, "SurfacePlaneInputs", ovr, time, expr) else { return };
285276 let mat_node = ovr.material_override.or_else(|| {
286277 node.connected_node("MaterialInput")
287278 .or_else(|| node.connected_node("SceneInput"))
288279 .and_then(|s| comp.find_node(s))
289280 });
290281 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));
292283 }
293284 "Shape3D" => {
294285 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 };
296287 let shape = match shape_name {
297288 "SurfaceSphereInputs" => ShapeKind::Sphere {
298289 // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00)
299290 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,
301 sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32,
291 sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,
292 sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 20.0, expr).round() as u32,
302293 },
303294 "SurfaceCylinderInputs" => {
304295 let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32;
305296 let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32;
306297 ShapeKind::Cylinder {
307 radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 0.5, expr) as f32,
308 height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 1.0, expr) as f32,
298 radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 1.0, expr) as f32,
299 height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 2.0, expr) as f32,
309300 start_sweep_deg: start_sw,
310301 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,
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,
302 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,
320303 }
321304 }
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 },
322310 _ => {
323 let sw = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32;
324 let sh = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionHeight", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32;
325 ShapeKind::Plane {
326 width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32,
327 height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32,
328 sub_w: sw,
329 sub_h: sh,
330 }
311 // Fusion's plane is square: Height and SubdivisionHeight follow Width.
312 let sub = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, 10.0, expr).round() as u32;
313 let 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 }
331315 }
332316 };
333317 let mat_node = ovr.material_override.or_else(|| {
......@@ -336,83 +320,67 @@ fn collect_scene_inner(
336320 });
337321 let mut mat = resolve_material(comp, mat_node, time, expr);
338322 if mat_node.is_none() {
339 mat.diffuse_col = [
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 ];
323 apply_mtl_std(&mut mat, comp, node, "", time, expr);
345324 }
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));
347327 }
348328 "Cube3D" => {
349 let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr);
350 let shape = ShapeKind::Cube {
351 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32,
352 height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32,
353 depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32,
354 };
355 let mat_node = ovr.material_override.or_else(|| {
356 [
357 "MaterialInput",
358 "FrontMaterialInput",
359 "BackMaterialInput",
360 "RightMaterialInput",
361 "LeftMaterialInput",
362 "TopMaterialInput",
363 "BottomMaterialInput",
364 ]
365 .iter()
366 .find_map(|k| node.connected_node(k))
367 .and_then(|s| comp.find_node(s))
368 });
369 let mut mat = resolve_material(comp, mat_node, time, expr);
370 if mat_node.is_none() {
371 let r_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr);
372 let g_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr);
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 ];
329 if let Some(own) = surface_scope(comp, node, "SurfaceCubeInputs", ovr, time, expr) {
330 // Fusion's Cube3D only honors Width (all edges) and takes one material per face.
331 let width = comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32;
332 let wireframe = comp.eval_number(node, "SurfaceCubeInputs.Wireframe", time, 0.0, expr) > 0.5;
333 let sub = cube_subdivisions(comp, node, time, expr);
334 let mut groups: Vec<(Option<NodeId>, ResolvedMaterial, u8)> = Vec::new();
335 for (i, face) in CUBE_FACES.iter().enumerate() {
336 let mat_node = ovr.material_override.or_else(|| {
337 node.connected_node(&format!("{face}MaterialInput"))
338 .and_then(|s| comp.find_node(s))
339 });
340 let mut mat = resolve_material(comp, mat_node, time, expr);
341 if mat_node.is_none() {
342 apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr);
343 }
344 mat.fx.wireframe = wireframe;
345 match groups.iter_mut().find(|(n, m, _)| *n == mat_node && *m == mat) {
346 Some((_, _, mask)) => *mask |= 1 << i,
347 None => groups.push((mat_node, mat, 1 << i)),
348 }
349 }
350 for (_, mat, faces) in groups {
351 meshes.push(make_mesh_instance(world, ShapeKind::Cube { width, sub, faces }, mat, None, &own));
352 }
381353 }
382 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
383354 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
384355 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);
385356 }
386357 }
387358 "SurfaceFBXMesh" => {
388 let import_file = node.static_str("ImportFile").unwrap_or("");
389 let obj_name = node.static_str("ObjName");
390 let scale_units = comp.eval_number(node, "ScaleFileUnitsBy", time, 1.0, expr) as f32;
391 let verts = load_mesh_cached(import_file, comp.path.as_deref(), obj_name, scale_units);
392 let shape = ShapeKind::CustomMesh(verts);
393 let mat_node = ovr.material_override.or_else(|| {
394 node.connected_node("MaterialInput")
395 .or_else(|| {
396 let mut slots: Vec<&String> = node
397 .inputs
398 .keys()
399 .filter(|k| k.starts_with("Materials."))
400 .collect();
401 slots.sort();
402 slots.into_iter().find_map(|k| node.connected_node(k))
403 })
404 .and_then(|s| comp.find_node(s))
405 });
406 let mut mat = resolve_material(comp, mat_node, time, expr);
407 if mat_node.is_none() {
408 mat.diffuse_col = [
409 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32,
410 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32,
411 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32,
412 comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32,
413 ];
359 if let Some(own) = surface_scope(comp, node, "SurfaceFBXInputs", ovr, time, expr) {
360 let import_file = node.static_str("ImportFile").unwrap_or("");
361 let obj_name = node.static_str("ObjName");
362 let scale_units = comp.eval_number(node, "ScaleFileUnitsBy", time, 1.0, expr) as f32;
363 let verts = load_mesh_cached(import_file, comp.path.as_deref(), obj_name, scale_units);
364 let shape = ShapeKind::CustomMesh(verts);
365 let mat_node = ovr.material_override.or_else(|| {
366 node.connected_node("MaterialInput")
367 .or_else(|| {
368 let mut slots: Vec<&String> = node
369 .inputs
370 .keys()
371 .filter(|k| k.starts_with("Materials."))
372 .collect();
373 slots.sort();
374 slots.into_iter().find_map(|k| node.connected_node(k))
375 })
376 .and_then(|s| comp.find_node(s))
377 });
378 let mut mat = resolve_material(comp, mat_node, time, expr);
379 if mat_node.is_none() {
380 apply_mtl_std(&mut mat, comp, node, "", time, expr);
381 }
382 meshes.push(make_mesh_instance(world, shape, mat, None, &own));
414383 }
415 meshes.push(make_mesh_instance(world, shape, mat, None, ovr));
416384 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
417385 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);
418386 }
......@@ -445,18 +413,16 @@ fn collect_scene_inner(
445413 }
446414}
447415
416#[derive(PartialEq)]
448417struct ResolvedMaterial {
449418 tex_node: Option<NodeId>,
450419 diffuse_col: [f32; 4],
451420 specular_col: [f32; 3],
452421 specular_intensity: f32,
453422 specular_exponent: f32,
454 uv_offset: [f32; 2],
455 uv_scale: [f32; 2],
456 uv_rot: f32,
457 uv_wrap: u32,
458 bump_scale: f32,
459 bump_mode: u32,
423 fx: MaterialFx,
424 /// A bare texture operator used as a surface's material renders flat, ignoring lights.
425 unlit: bool,
460426}
461427
462428impl Default for ResolvedMaterial {
......@@ -465,14 +431,10 @@ impl Default for ResolvedMaterial {
465431 tex_node: None,
466432 diffuse_col: [1.0, 1.0, 1.0, 1.0],
467433 specular_col: [1.0, 1.0, 1.0],
468 specular_intensity: 0.15,
469 specular_exponent: 25.0,
470 uv_offset: [0.0, 0.0],
471 uv_scale: [1.0, 1.0],
472 uv_rot: 0.0,
473 uv_wrap: 0,
474 bump_scale: 0.0,
475 bump_mode: 0,
434 specular_intensity: 1.0,
435 specular_exponent: 50.0,
436 fx: MaterialFx::default(),
437 unlit: false,
476438 }
477439 }
478440}
......@@ -484,54 +446,66 @@ fn make_mesh_instance(
484446 text3d: Option<Text3DSpec>,
485447 ovr: &SceneOverrides,
486448) -> 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 };
507449 MeshInstance {
508450 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 },
510455 material_node: mat.tex_node,
511456 text3d,
512457 diffuse_col: mat.diffuse_col,
513458 specular_col: mat.specular_col,
514459 specular_intensity: mat.specular_intensity,
515460 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),
517462 flip_normals: ovr.flip_normals,
518463 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,
525464 }
526465}
527466
528fn eval_first_present(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f32 {
529 for &k in keys {
530 if node.inputs.contains_key(k) {
531 return comp.eval_number(node, k, time, default, expr) as f32;
532 }
467/// Applies a surface's own `<group>.Visibility.*` / `<group>.Lighting.IsAffectedByLights`
468/// inputs on top of inherited overrides; `None` when the surface is hidden.
469fn surface_scope(
470 comp: &Comp,
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;
533490 }
534 default as f32
491 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);
535509}
536510
537511fn 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
553527 None
554528}
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
556544/// Resolves a 3D material input (`Texture2DOperator`, `TextureTransformOperator`, `BumpMap`,
557545/// `MtlBlinn`, `MtlCookTorrance`, `MtlPhong`, or a direct 2D image node).
558546fn resolve_material(
......@@ -582,36 +570,29 @@ fn resolve_material_inner(
582570 match n.kind.as_str() {
583571 "Texture2DOperator" => {
584572 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);
586573 ResolvedMaterial {
587574 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,
589580 ..default_mat
590581 }
591582 }
592583 "TextureTransformOperator" => {
593 let inner_id = n
594 .connected_node("MaterialInput")
595 .or_else(|| n.connected_node("Input"))
596 .and_then(|s| comp.find_node(s));
584 let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s));
597585 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);
599 let ty = eval_first_present(comp, n, &["TranslationOffset.Y", "Translation.V", "Translation.Y"], time, 0.0, expr);
600 let sx = eval_first_present(comp, n, &["Scale.X", "Scale.U"], time, 1.0, expr);
601 let sy = eval_first_present(comp, n, &["Scale.Y", "Scale.V"], time, 1.0, expr);
602 let rot_deg = eval_first_present(
603 comp,
604 n,
605 &["Rotation.Z", "RotationOffset", "Rotation.W", "Rotation.U"],
606 time,
607 0.0,
608 expr,
586 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
587 let xf = texture_transform_uv(
588 [f("Translation.U", 0.0), f("Translation.V", 0.0)],
589 f("Rotation.W", 0.0).to_radians(),
590 [f("Scale.U", 1.0), f("Scale.V", 1.0)],
591 [f("Pivot.U", 0.0), f("Pivot.V", 0.0)],
609592 );
610 mat.uv_offset = [mat.uv_offset[0] + tx, mat.uv_offset[1] + ty];
611 mat.uv_scale = [mat.uv_scale[0] * sx, mat.uv_scale[1] * sy];
612 mat.uv_rot += rot_deg.to_radians();
593 mat.fx.uv = xf.then(&mat.fx.uv);
613594 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {
614 mat.uv_wrap = w;
595 mat.fx.uv_wrap = w;
615596 }
616597 mat
617598 }
......@@ -625,12 +606,14 @@ fn resolve_material_inner(
625606 .round()
626607 .clamp(0.0, 1.0) as u32
627608 };
628 let uv_wrap = parse_wrap_mode(comp, n, time, expr).unwrap_or(0);
629609 ResolvedMaterial {
630610 tex_node: src,
631 uv_wrap,
632 bump_scale: height_scale,
633 bump_mode,
611 fx: MaterialFx {
612 uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0),
613 bump_scale: height_scale,
614 bump_mode,
615 ..default_mat.fx
616 },
634617 ..default_mat
635618 }
636619 }
......@@ -657,45 +640,34 @@ fn resolve_material_inner(
657640 comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32,
658641 ];
659642 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" {
661 let rough = comp.eval_number(n, "Specular.Roughness", time, 0.4, expr).clamp(0.05, 1.0) as f32;
662 ((2.0 / (rough * rough) - 2.0).max(2.0), 0.15)
663 } else {
664 (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0)
643 let (spec_exp, spec_model) = match n.kind.as_str() {
644 "MtlCookTorrance" => (
645 comp.eval_number(n, "Specular.Roughness", time, 0.6, expr).clamp(0.05, 1.0) as f32,
646 SpecModel::CookTorrance,
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),
665650 };
666651
667652 let mut tex_node = diff_mat.tex_node;
668 let mut uv_offset = diff_mat.uv_offset;
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
653 let mut fx = MaterialFx { spec_model, ..diff_mat.fx };
675654 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;
678655 if tex_node.is_none() {
679656 tex_node = bm.tex_node;
680 uv_offset = bm.uv_offset;
681 uv_scale = bm.uv_scale;
682 uv_rot = bm.uv_rot;
683 uv_wrap = bm.uv_wrap;
657 fx = MaterialFx { bump_only: true, spec_model, ..bm.fx };
684658 }
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;
685661 }
686662
687663 ResolvedMaterial {
688664 tex_node,
689665 diffuse_col: col,
690666 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),
692668 specular_exponent: spec_exp,
693 uv_offset,
694 uv_scale,
695 uv_rot,
696 uv_wrap,
697 bump_scale,
698 bump_mode,
669 fx,
670 unlit: false,
699671 }
700672 }
701673 _ => ResolvedMaterial {
......@@ -911,67 +883,70 @@ mod tests {
911883
912884 #[test]
913885 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 {{
915892 CurrentTime = 0,
916 RenderRange = { 0, 10 },
917 GlobalRange = { 0, 10 },
918 Tools = ordered() {
919 BG1 = Background {
920 Inputs = {
921 Width = Input { Value = 64, },
922 Height = Input { Value = 64, },
923 },
924 },
925 Bump1 = BumpMap {
926 Inputs = {
927 Input = Input { SourceOp = "BG1", Source = "Output", },
928 HeightScale = Input { Value = 4.5, },
929 SourceImageType = Input { Value = 1, },
930 WrapMode = Input { Value = FuID { "Wrap" }, },
931 },
932 },
933 TexXf = TextureTransformOperator {
934 Inputs = {
935 MaterialInput = Input { SourceOp = "Bump1", Source = "MaterialOutput", },
936 ["TranslationOffset.X"] = Input { Value = 0.25, },
937 ["TranslationOffset.Y"] = Input { Value = -0.5, },
938 ["Scale.U"] = Input { Value = 2.0, },
939 ["Scale.V"] = Input { Value = 3.0, },
940 ["Rotation.Z"] = Input { Value = 90.0, },
941 },
942 },
943 BlinnBump = MtlBlinn {
944 Inputs = {
945 ["Diffuse.Color.Red"] = Input { Value = 0.7, },
946 ["Bumpmap.Material"] = Input { SourceOp = "TexXf", Source = "MaterialOutput", },
947 },
948 },
949 CubeNode = Cube3D {
950 Inputs = {
951 ["SurfaceCubeInputs.Size"] = Input { Value = 2.0, },
952 ["SurfaceCubeInputs.Height"] = Input { Value = 4.0, },
953 ["Transform3DOp.Translate.Y"] = Input { Value = 1.5, },
954 MaterialInput = Input { SourceOp = "BlinnBump", Source = "MaterialOutput", },
955 },
956 },
957 FbxNode = SurfaceFBXMesh {
958 Inputs = {
959 ImportFile = Input { Value = "/does/not/exist/model.fbx", },
960 ObjName = Input { Value = "HeroMesh", },
961 ScaleFileUnitsBy = Input { Value = 0.01, },
962 ["Transform3DOp.Translate.X"] = Input { Value = -2.0, },
963 ["Materials.Mat0_mat0"] = Input { SourceOp = "TexXf", Source = "MaterialOutput", },
964 },
965 },
966 Merge1 = Merge3D {
967 Inputs = {
968 SceneInput1 = Input { SourceOp = "CubeNode", Source = "Output", },
969 SceneInput2 = Input { SourceOp = "FbxNode", Source = "Output", },
970 },
971 },
972 },
973 }"#;
974 let comp = Comp::from_fusion_str(src).expect("parse comp");
893 RenderRange = {{ 0, 10 }},
894 GlobalRange = {{ 0, 10 }},
895 Tools = ordered() {{
896 BG1 = Background {{
897 Inputs = {{
898 Width = Input {{ Value = 64, }},
899 Height = Input {{ Value = 64, }},
900 }},
901 }},
902 Bump1 = BumpMap {{
903 Inputs = {{
904 Input = Input {{ SourceOp = "BG1", Source = "Output", }},
905 HeightScale = Input {{ Value = 4.5, }},
906 SourceImageType = Input {{ Value = 1, }},
907 WrapMode = Input {{ Value = FuID {{ "Wrap" }}, }},
908 }},
909 }},
910 TexXf = TextureTransformOperator {{
911 Inputs = {{
912 MaterialInput = Input {{ SourceOp = "Bump1", Source = "MaterialOutput", }},
913 ["Translation.U"] = Input {{ Value = 0.25, }},
914 ["Translation.V"] = Input {{ Value = -0.5, }},
915 }},
916 }},
917 BlinnBump = MtlBlinn {{
918 Inputs = {{
919 ["Diffuse.Color.Red"] = Input {{ Value = 0.7, }},
920 ["Bumpmap.Material"] = Input {{ SourceOp = "TexXf", Source = "MaterialOutput", }},
921 }},
922 }},
923 CubeNode = Cube3D {{
924 Inputs = {{
925 ["SurfaceCubeInputs.Width"] = Input {{ Value = 2.0, }},
926 ["SurfaceCubeInputs.Height"] = Input {{ Value = 4.0, }},
927 ["Transform3DOp.Translate.Y"] = Input {{ Value = 1.5, }},
928 {faces}
929 }},
930 }},
931 FbxNode = SurfaceFBXMesh {{
932 Inputs = {{
933 ImportFile = Input {{ Value = "/does/not/exist/model.fbx", }},
934 ObjName = Input {{ Value = "HeroMesh", }},
935 ScaleFileUnitsBy = Input {{ Value = 0.01, }},
936 ["Transform3DOp.Translate.X"] = Input {{ Value = -2.0, }},
937 ["Materials.Mat0_mat0"] = Input {{ SourceOp = "TexXf", Source = "MaterialOutput", }},
938 }},
939 }},
940 Merge1 = Merge3D {{
941 Inputs = {{
942 SceneInput1 = Input {{ SourceOp = "CubeNode", Source = "Output", }},
943 SceneInput2 = Input {{ SourceOp = "FbxNode", Source = "Output", }},
944 }},
945 }},
946 }},
947 }}"#
948 );
949 let comp = Comp::from_fusion_str(&src).expect("parse comp");
975950 let expr = ExprEngine::new();
976951 let merge_id = comp.find_node("Merge1").expect("Merge1");
977952 let bg_id = comp.find_node("BG1").expect("BG1");
......@@ -990,32 +965,184 @@ mod tests {
990965 &mut lights,
991966 0,
992967 );
968 // Six identical face materials collapse into one cube; Height is ignored.
993969 assert_eq!(meshes.len(), 2);
994970
995 // Cube3D with Blinn + Bumpmap (TextureTransformOperator -> BumpMap)
996971 let cube = &meshes[0];
997972 assert!(matches!(
998973 cube.shape.base_shape(),
999 ShapeKind::Cube { width, height, depth }
1000 if (*width - 2.0).abs() < 1e-4 && (*height - 4.0).abs() < 1e-4 && (*depth - 2.0).abs() < 1e-4
974 ShapeKind::Cube { width, faces: 0b11_1111, .. } if (*width - 2.0).abs() < 1e-4
1001975 ));
1002976 assert!((cube.world[13] - 1.5).abs() < 1e-4);
1003977 assert_eq!(cube.material_node, Some(bg_id));
1004978 assert!((cube.diffuse_col[0] - 0.7).abs() < 1e-4);
1005 assert!((cube.bump_scale - 4.5).abs() < 1e-4);
1006 assert_eq!(cube.bump_mode, 1);
1007 assert!((cube.uv_offset[0] - 0.25).abs() < 1e-4);
1008 assert!((cube.uv_offset[1] + 0.5).abs() < 1e-4);
1009 assert!((cube.uv_scale[0] - 2.0).abs() < 1e-4);
1010 assert!((cube.uv_scale[1] - 3.0).abs() < 1e-4);
1011 assert!((cube.uv_rot - std::f32::consts::FRAC_PI_2).abs() < 1e-4);
1012 assert_eq!(cube.uv_wrap, 1);
1013
1014 // SurfaceFBXMesh fallback unit box + Materials.* slot resolution
979 let fx = cube.shape.split_fx().1;
980 assert!((fx.bump_scale - 4.5).abs() < 1e-4);
981 assert_eq!(fx.bump_mode, 1);
982 assert!(!fx.bump_only || cube.material_node.is_some());
983 assert_eq!(fx.uv_wrap, 1);
984 // Content moved +0.25 in U and -0.5 in V (V up) samples from u-0.25 and v-0.5.
985 let sampled = fx.uv.apply([0.5, 0.5]);
986 assert!((sampled[0] - 0.25).abs() < 1e-4 && sampled[1].abs() < 1e-4, "{sampled:?}");
987
1015988 let fbx = &meshes[1];
1016989 assert!(matches!(fbx.shape.base_shape(), ShapeKind::CustomMesh(v) if v.len() == 36));
1017990 assert!((fbx.world[12] + 2.0).abs() < 1e-4);
1018991 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 { .. }));
10201147 }
10211148}
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
2020 end_sweep_deg,
2121 sub_base,
2222 } => 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),
2424 ShapeKind::CustomMesh(verts) => {
2525 let v = verts.as_ref().clone();
2626 let idx = (0..v.len() as u32).collect();
......@@ -42,32 +42,46 @@ fn build_image_plane(tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) {
4242 (verts, vec![0, 1, 2, 0, 2, 3])
4343}
4444
45fn build_plane(width: f32, height: f32, sub_w: u32, sub_h: u32) -> (Vec<Vertex3D>, Vec<u32>) {
46 let sw = sub_w.clamp(1, 64);
47 let sh = sub_h.clamp(1, 64);
48 let hx = width * 0.5;
49 let hy = height * 0.5;
50 let mut verts = Vec::with_capacity(((sw + 1) * (sh + 1)) as usize);
51 let mut idx = Vec::with_capacity((sw * sh * 6) as usize);
52 for iy in 0..=sh {
53 let v = iy as f32 / sh as f32;
54 let y = hy - v * height;
55 for ix in 0..=sw {
56 let u = ix as f32 / sw as f32;
57 let x = -hx + u * width;
58 verts.push(Vertex3D { pos: [x, y, 0.0], normal: [0.0, 0.0, 1.0], uv: [u, v] });
45/// Appends a `sub_w` x `sub_h` grid spanning the quad `tl`/`tr`/`bl` (UV `(0,0)` at `tl`, V down),
46/// splitting each cell along its bottom-left to top-right diagonal.
47fn push_quad_grid(
48 verts: &mut Vec<Vertex3D>,
49 idx: &mut Vec<u32>,
50 normal: [f32; 3],
51 [tl, tr, bl]: [[f32; 3]; 3],
52 sub_w: u32,
53 sub_h: u32,
54) {
55 let base = verts.len() as u32;
56 for iy in 0..=sub_h {
57 let v = iy as f32 / sub_h as f32;
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] });
5962 }
6063 }
61 let row = sw + 1;
62 for iy in 0..sh {
63 for ix in 0..sw {
64 let a = iy * row + ix;
65 let b = (iy + 1) * row + ix;
66 let c = (iy + 1) * row + ix + 1;
67 let d = iy * row + ix + 1;
68 idx.extend_from_slice(&[a, b, c, a, c, d]);
64 let row = sub_w + 1;
65 for iy in 0..sub_h {
66 for ix in 0..sub_w {
67 let a = base + iy * row + ix;
68 let (b, c, d) = (a + row, a + row + 1, a + 1);
69 idx.extend_from_slice(&[a, b, d, b, c, d]);
6970 }
7071 }
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 );
7185 (verts, idx)
7286}
7387
......@@ -123,7 +137,7 @@ fn build_sphere(radius: f32, sub_base: u32, sub_height: u32) -> (Vec<Vertex3D>,
123137 let b = (iv + 1) * row + iu;
124138 let c = (iv + 1) * row + iu + 1;
125139 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]);
127141 }
128142 }
129143 (verts, idx)
......@@ -165,36 +179,45 @@ fn build_cylinder(
165179 let b = a + 1;
166180 let c = a + 3;
167181 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]);
169183 }
170184 (verts, idx)
171185}
172186
173fn build_cube(width: f32, height: f32, depth: f32) -> (Vec<Vertex3D>, Vec<u32>) {
174 let hx = width * 0.5;
175 let hy = height * 0.5;
176 let hz = depth * 0.5;
177 let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [
178 ([0.0, 0.0, 1.0], [[-hx, hy, hz], [-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz]]),
179 ([0.0, 0.0, -1.0], [[hx, hy, -hz], [hx, -hy, -hz], [-hx, -hy, -hz], [-hx, hy, -hz]]),
180 ([1.0, 0.0, 0.0], [[hx, hy, hz], [hx, -hy, hz], [hx, -hy, -hz], [hx, hy, -hz]]),
181 ([-1.0, 0.0, 0.0], [[-hx, hy, -hz], [-hx, -hy, -hz], [-hx, -hy, hz], [-hx, hy, hz]]),
182 ([0.0, 1.0, 0.0], [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]]),
183 ([0.0, -1.0, 0.0], [[-hx, -hy, hz], [-hx, -hy, -hz], [hx, -hy, -hz], [hx, -hy, hz]]),
187fn build_cube(width: f32, sub: u32, faces_mask: u8) -> (Vec<Vertex3D>, Vec<u32>) {
188 let h = width * 0.5;
189 // `[tl, tr, bl]` per face in `CUBE_FACES` order.
190 let faces: [([f32; 3], [[f32; 3]; 3]); 6] = [
191 ([0.0, 0.0, 1.0], [[-h, h, h], [h, h, h], [-h, -h, h]]),
192 ([0.0, 0.0, -1.0], [[h, h, -h], [-h, h, -h], [h, -h, -h]]),
193 ([1.0, 0.0, 0.0], [[h, h, h], [h, h, -h], [h, -h, h]]),
194 ([-1.0, 0.0, 0.0], [[-h, h, -h], [-h, h, h], [-h, -h, -h]]),
195 ([0.0, 1.0, 0.0], [[-h, h, -h], [h, h, -h], [-h, h, h]]),
196 ([0.0, -1.0, 0.0], [[-h, -h, h], [h, -h, h], [-h, -h, -h]]),
184197 ];
185 let mut verts = Vec::with_capacity(24);
186 let mut idx = Vec::with_capacity(36);
187 for (n, corners) in faces {
188 let base = verts.len() as u32;
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 });
198 let (mut verts, mut idx) = (Vec::new(), Vec::new());
199 for (i, (n, corners)) in faces.into_iter().enumerate() {
200 if faces_mask & (1 << i) != 0 {
201 push_quad_grid(&mut verts, &mut idx, n, corners, sub, sub);
192202 }
193 idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
194203 }
195204 (verts, idx)
196205}
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
198221pub(super) fn apply_heightmap_displace(
199222 verts: &mut [Vertex3D],
200223 indices: &[u32],
......@@ -214,13 +237,13 @@ pub(super) fn apply_heightmap_displace(
214237 let b = disp.rgba[off + 2] as f32 / 255.0;
215238 let a = disp.rgba[off + 3] as f32 / 255.0;
216239 let sample = match disp.channel {
217 0 => r,
218 1 => g,
219 2 => b,
220 3 => a,
240 1 => r,
241 2 => g,
242 3 => b,
243 4 => a,
221244 _ => 0.299 * r + 0.587 * g + 0.114 * b,
222245 };
223 let d = (sample - 0.5 + disp.bias) * disp.scale;
246 let d = (sample + disp.bias) * disp.scale;
224247 v.pos[0] += v.normal[0] * d;
225248 v.pos[1] += v.normal[1] * d;
226249 v.pos[2] += v.normal[2] * d;
......@@ -255,3 +278,45 @@ pub(super) fn apply_heightmap_displace(
255278 }
256279 }
257280}
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;
2222use std::sync::Arc;
2323
2424use crate::cache::CachedTexture;
25use mesh::{apply_heightmap_displace, build_shape_mesh};
25use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};
2626use model::NodeId;
27use shader::{MeshUniform, SHADER_3D};
27use shader::{MeshUniform, MAX_LIGHTS, SHADER_3D};
2828
2929pub type Mat4 = [f32; 16]; // Column-major 4x4
3030
3131pub struct Scene3DRenderer {
3232 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],
3436 sampler: wgpu::Sampler,
3537}
3638
......@@ -48,51 +50,102 @@ pub enum ShapeKind {
4850 Sphere { radius: f32, sub_base: u32, sub_height: u32 },
4951 Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 },
5052 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 },
5255 TextPlate { width: f32, height: f32, depth: f32, slices: u32 },
5356 CustomMesh(Arc<Vec<Vertex3D>>),
54 /// Wraps a base `ShapeKind` with UV transform and bump parameters so they travel
55 /// cleanly through `DrawMesh` into `Scene3DRenderer::render_meshes`.
56 WithMaterialFx {
57 inner: Box<ShapeKind>,
58 uv_offset: [f32; 2],
59 uv_scale: [f32; 2],
60 uv_rot: f32,
61 uv_wrap: u32,
62 bump_scale: f32,
63 bump_mode: u32,
64 },
57 /// Carries the material's UV transform and bump parameters through `DrawMesh`.
58 WithMaterialFx { inner: Box<ShapeKind>, fx: MaterialFx },
59}
60
61/// Face order shared by `Cube3D` material inputs and `build_cube`.
62pub const CUBE_FACES: [&str; 6] = ["Front", "Back", "Right", "Left", "Top", "Bottom"];
63
64/// Affine map from mesh UV (V down) to texture UV: `uv' = m * uv + t`, `m` column-major.
65#[derive(Clone, Copy, Debug, PartialEq)]
66pub struct UvAffine {
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 }
65137}
66138
67139impl ShapeKind {
68140 /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper.
69141 pub fn base_shape(&self) -> &ShapeKind {
70 match self {
71 ShapeKind::WithMaterialFx { inner, .. } => inner.base_shape(),
72 other => other,
73 }
142 self.split_fx().0
74143 }
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) {
77146 match self {
78 ShapeKind::WithMaterialFx {
79 inner,
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),
147 ShapeKind::WithMaterialFx { inner, fx } => (inner.base_shape(), *fx),
148 other => (other, MaterialFx::default()),
96149 }
97150 }
98151}
......@@ -102,7 +155,7 @@ pub struct Displace3DSpec {
102155 pub input_node: NodeId,
103156 pub scale: f32,
104157 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
106159}
107160
108161#[derive(Clone, Debug)]
......@@ -132,19 +185,15 @@ pub struct MeshInstance {
132185 pub affected_by_lights: bool,
133186 pub flip_normals: bool,
134187 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,
141188}
142189
143190#[derive(Clone, Copy, Debug)]
144191pub struct PointLight {
145192 pub pos: [f32; 3],
146193 pub color: [f32; 3],
194 /// 0 = none, 1 = linear (1/d), 2 = quadratic (1/d²)
147195 pub decay_type: f32,
196 /// Unused by the shader; `Renderer3D` still folds it into its cache key.
148197 pub decay_rate: f32,
149198}
150199
......@@ -198,7 +247,7 @@ impl Scene3DRenderer {
198247 pub fn new(device: &wgpu::Device) -> Self {
199248 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
200249 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()),
202251 });
203252 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
204253 label: Some("scene3d-bgl"),
......@@ -245,19 +294,22 @@ impl Scene3DRenderer {
245294 wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 },
246295 ],
247296 };
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 {
249298 label: Some("scene3d-mesh"),
250299 layout: Some(&pl),
251300 vertex: wgpu::VertexState {
252301 module: &shader,
253302 entry_point: Some("vs_mesh"),
254303 compilation_options: Default::default(),
255 buffers: &[Some(vbuf_layout)],
304 buffers: &[Some(vbuf_layout.clone())],
256305 },
257306 fragment: Some(wgpu::FragmentState {
258307 module: &shader,
259308 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 },
261313 targets: &[Some(wgpu::ColorTargetState {
262314 format: wgpu::TextureFormat::Rgba8Unorm,
263315 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
......@@ -265,7 +317,7 @@ impl Scene3DRenderer {
265317 })],
266318 }),
267319 primitive: wgpu::PrimitiveState {
268 topology: wgpu::PrimitiveTopology::TriangleList,
320 topology,
269321 cull_mode: None,
270322 ..Default::default()
271323 },
......@@ -280,6 +332,8 @@ impl Scene3DRenderer {
280332 multiview_mask: None,
281333 cache: None,
282334 });
335 let pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList]
336 .map(|topology| [make_pipeline(topology, true), make_pipeline(topology, false)]);
283337 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
284338 label: Some("scene3d-linear"),
285339 address_mode_u: wgpu::AddressMode::ClampToEdge,
......@@ -289,7 +343,7 @@ impl Scene3DRenderer {
289343 mipmap_filter: wgpu::MipmapFilterMode::Linear,
290344 ..Default::default()
291345 });
292 Self { bgl, pipeline, sampler }
346 Self { bgl, pipelines, sampler }
293347 }
294348
295349 #[allow(clippy::too_many_arguments)]
......@@ -338,6 +392,9 @@ impl Scene3DRenderer {
338392 order.sort_by(|a, b| a.1.total_cmp(&b.1));
339393
340394 struct GpuDraw {
395 wireframe: bool,
396 /// Skip the `[back-facing, front-facing]` pass.
397 cull: [bool; 2],
341398 bg: wgpu::BindGroup,
342399 vbuf: wgpu::Buffer,
343400 ibuf: wgpu::Buffer,
......@@ -351,15 +408,17 @@ impl Scene3DRenderer {
351408 .as_ref()
352409 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))
353410 .unwrap_or(16.0 / 9.0);
354 let (base_shape, uv_offset, uv_scale, uv_rot, uv_wrap, bump_scale, bump_mode) =
355 m.shape.unwrap_fx();
356 let (mut verts, indices) = build_shape_mesh(base_shape, aspect);
411 let (base_shape, fx) = m.shape.split_fx();
412 let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect);
357413 if indices.is_empty() {
358414 continue;
359415 }
360416 if let Some(disp) = &m.displace {
361417 apply_heightmap_displace(&mut verts, &indices, disp);
362418 }
419 if fx.wireframe {
420 indices = triangle_edges(&indices);
421 }
363422 let vbytes = bytemuck::cast_slice(&verts);
364423 let ibytes = bytemuck::cast_slice(&indices);
365424 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {
......@@ -387,18 +446,18 @@ impl Scene3DRenderer {
387446 } else {
388447 [0.0; 4]
389448 };
390 let mut point_pos = [[0.0_f32; 4]; 4];
391 let mut point_col = [[0.0_f32; 4]; 4];
392 let n_pt = lights.points.len().min(4);
393 for (pi, pl) in lights.points.iter().take(4).enumerate() {
449 let mut point_pos = [[0.0_f32; 4]; MAX_LIGHTS];
450 let mut point_col = [[0.0_f32; 4]; MAX_LIGHTS];
451 let n_pt = lights.points.len().min(MAX_LIGHTS);
452 for (pi, pl) in lights.points.iter().take(MAX_LIGHTS).enumerate() {
394453 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];
396455 }
397 let mut spot_pos = [[0.0_f32; 4]; 4];
398 let mut spot_dir = [[0.0_f32; 4]; 4];
399 let mut spot_col = [[0.0_f32; 4]; 4];
400 let n_sp = lights.spots.len().min(4);
401 for (si, sl) in lights.spots.iter().take(4).enumerate() {
456 let mut spot_pos = [[0.0_f32; 4]; MAX_LIGHTS];
457 let mut spot_dir = [[0.0_f32; 4]; MAX_LIGHTS];
458 let mut spot_col = [[0.0_f32; 4]; MAX_LIGHTS];
459 let n_sp = lights.spots.len().min(MAX_LIGHTS);
460 for (si, sl) in lights.spots.iter().take(MAX_LIGHTS).enumerate() {
402461 spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner];
403462 spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer];
404463 spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type];
......@@ -430,8 +489,9 @@ impl Scene3DRenderer {
430489 dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0],
431490 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],
432491 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]],
434 mat_fx: [uv_rot, uv_wrap as f32, bump_scale, bump_mode as f32],
492 uv_xform: fx.uv.m,
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],
435495 point_pos,
436496 point_col,
437497 spot_pos,
......@@ -456,6 +516,8 @@ impl Scene3DRenderer {
456516 ],
457517 });
458518 draw_items.push(GpuDraw {
519 wireframe: fx.wireframe,
520 cull: [fx.cull_back, fx.cull_front],
459521 bg,
460522 vbuf,
461523 ibuf,
......@@ -486,12 +548,109 @@ impl Scene3DRenderer {
486548 occlusion_query_set: None,
487549 multiview_mask: None,
488550 });
489 pass.set_pipeline(&self.pipeline);
490551 for d in &draw_items {
491552 pass.set_bind_group(0, &d.bg, &[]);
492553 pass.set_vertex_buffer(0, d.vbuf.slice(..));
493554 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 }
495561 }
496562 }
497563}
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 @@
22
33use bytemuck::{Pod, Zeroable};
44
5/// Point and spot lights each get this many shader slots.
6pub(super) const MAX_LIGHTS: usize = 8;
7
58#[repr(C)]
69#[derive(Clone, Copy, Debug, Pod, Zeroable)]
710pub struct Vertex3D {
......@@ -33,22 +36,25 @@ pub(super) struct MeshUniform {
3336 pub(super) cam_pos: [f32; 4],
3437 /// `[num_point_lights, num_spot_lights, 0, 0]`
3538 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]`
3740 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]`
3944 pub(super) mat_fx: [f32; 4],
4045 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`
41 pub(super) point_pos: [[f32; 4]; 4],
42 /// Point light colors * intensity `(r, g, b, decay_rate)`
43 pub(super) point_col: [[f32; 4]; 4],
46 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],
47 /// Point light colors * intensity `(r, g, b, 0)`
48 pub(super) point_col: [[f32; 4]; MAX_LIGHTS],
4449 /// 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],
4651 /// 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],
4853 /// 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],
5055}
5156
57/// WGSL source; `MAX_LIGHTS` is substituted with the Rust constant at pipeline creation.
5258pub(super) const SHADER_3D: &str = r#"
5359struct MeshUniform {
5460 mvp: mat4x4<f32>,
......@@ -63,14 +69,17 @@ struct MeshUniform {
6369 cam_pos: vec4<f32>,
6470 light_counts: vec4<f32>,
6571 uv_xform: vec4<f32>,
72 uv_off_wrap: vec4<f32>,
6673 mat_fx: vec4<f32>,
67 point_pos: array<vec4<f32>, 4>,
68 point_col: array<vec4<f32>, 4>,
69 spot_pos: array<vec4<f32>, 4>,
70 spot_dir: array<vec4<f32>, 4>,
71 spot_col: array<vec4<f32>, 4>,
74 point_pos: array<vec4<f32>, MAX_LIGHTS>,
75 point_col: array<vec4<f32>, MAX_LIGHTS>,
76 spot_pos: array<vec4<f32>, MAX_LIGHTS>,
77 spot_dir: array<vec4<f32>, MAX_LIGHTS>,
78 spot_col: array<vec4<f32>, MAX_LIGHTS>,
7279};
7380
81override BACK_PASS: bool = false;
82
7483@group(0) @binding(0) var<uniform> u: MeshUniform;
7584@group(0) @binding(1) var mat_tex: texture_2d<f32>;
7685@group(0) @binding(2) var mat_samp: sampler;
......@@ -105,14 +114,13 @@ fn vs_mesh(v: VsIn) -> VsOut {
105114 return out;
106115}
107116
108fn light_attenuation(dist: f32, decay_type: f32, decay_rate: f32) -> f32 {
117fn light_attenuation(dist: f32, decay_type: f32) -> f32 {
109118 let dt = i32(decay_type + 0.5);
110 let rate = max(decay_rate, 0.001);
119 let d = max(dist, 1e-3);
111120 if (dt == 1) {
112 return 1.0 / max(1.0 + dist * rate, 1e-4);
121 return 1.0 / d;
113122 } else if (dt == 2) {
114 let d = dist * rate;
115 return 1.0 / max(1.0 + d * d, 1e-4);
123 return 1.0 / (d * d);
116124 }
117125 return 1.0;
118126}
......@@ -134,19 +142,27 @@ fn eval_light_contrib(
134142 var out = albedo * light_rgb * ndotl;
135143 if (spec_int > 1e-4) {
136144 let h = normalize(l + v);
137 let spec = pow(max(dot(n, h), 0.0), shininess) * spec_int;
138 out = out + light_rgb * spec_rgb * spec;
145 let model = i32(u.mat_fx.w + 0.5);
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);
139158 }
140159 return out;
141160}
142161
143fn apply_uv_xform(raw_uv: vec2<f32>, uv_xform: vec4<f32>, rot_wrap: vec2<f32>) -> vec2<f32> {
144 let p = raw_uv - vec2<f32>(0.5, 0.5);
145 let c = cos(rot_wrap.x);
146 let s = sin(rot_wrap.x);
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);
162fn apply_uv_xform(raw_uv: vec2<f32>) -> vec2<f32> {
163 let m = u.uv_xform;
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;
165 let wrap = i32(u.uv_off_wrap.z + 0.5);
150166 if (wrap == 1) {
151167 uv = fract(uv);
152168 } else if (wrap == 2) {
......@@ -210,7 +226,11 @@ fn perturb_bump_normal(
210226
211227@fragment
212228fn 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);
214234 let dpdx_w = dpdx(in.world_pos);
215235 let dpdy_w = dpdy(in.world_pos);
216236 let duvdx = dpdx(uv_xformed);
......@@ -229,7 +249,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
229249 }
230250 }
231251 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;
233253 }
234254 if (col.a <= 0.002) {
235255 discard;
......@@ -239,7 +259,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
239259 // Premultiplied -> unpremultiplied albedo for lighting
240260 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);
241261 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) {
243263 n = perturb_bump_normal(
244264 n,
245265 dpdx_w,
......@@ -248,13 +268,13 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
248268 duvdy,
249269 uv_samp,
250270 tex_col,
251 u.mat_fx.z,
252 u.mat_fx.w,
271 u.mat_fx.x,
272 u.mat_fx.y,
253273 );
254274 }
255275 let v = normalize(u.cam_pos.xyz - in.world_pos);
256276 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);
258278 let spec_int = u.flags.z;
259279
260280 var lit = albedo * u.ambient.rgb;
......@@ -264,16 +284,16 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
264284 }
265285
266286 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) {
268288 if (i >= n_pt) { break; }
269289 let to_l = u.point_pos[i].xyz - in.world_pos;
270290 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);
272292 lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);
273293 }
274294
275295 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) {
277297 if (i >= n_sp) { break; }
278298 let to_l = u.spot_pos[i].xyz - in.world_pos;
279299 let dist = max(length(to_l), 1e-4);
......@@ -284,7 +304,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
284304 let cos_outer = u.spot_dir[i].w;
285305 let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0);
286306 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;
288308 lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);
289309 }
290310 }