diff --git a/crates/engine/src/scene3d/collect.rs b/crates/engine/src/scene3d/collect.rs index ed050a562c4bbaa1863a0c8e006509c13901d418..ebc9f7fcb647a35279f0c04af8a187895eaeb58e 100644 --- a/crates/engine/src/scene3d/collect.rs +++ b/crates/engine/src/scene3d/collect.rs @@ -5,8 +5,8 @@ use super::math::{ mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, }; use super::{ - CameraInstance, Displace3DSpec, Mat4, MeshInstance, PointLight, SceneLights, ShapeKind, - SpotLight, Text3DSpec, + CameraInstance, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights, + ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, CUBE_FACES, }; use model::{Comp, ExprEngine, Node, NodeId}; @@ -16,6 +16,8 @@ struct SceneOverrides { affected_by_lights: Option, flip_normals: bool, displace: Option, + cull_back: bool, + cull_front: bool, } fn splitmix64(mut x: u64) -> f32 { @@ -135,7 +137,7 @@ fn collect_scene_inner( if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32; let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32; - let channel = comp.eval_number(node, "Channel", time, 4.0, expr).round() as i32; + let channel = comp.eval_number(node, "Channel", time, 0.0, expr).round() as i32; next_ovr.displace = Some(Displace3DSpec { input_node: in_id, scale, @@ -190,18 +192,19 @@ fn collect_scene_inner( "Camera3D" => { let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32; let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32; - // In Fusion .comp files, serialized AoV is always vertical degrees (AoVType only changes UI display). - // When AoV is omitted, compute from FLength if present, else Fusion 21's default Camera3D vertical AoV (~24.302°). - let has_aov = node.inputs.contains_key("AoV"); - let has_fl = node.inputs.contains_key("FLength"); - let aov_deg = if has_aov { - comp.eval_number(node, "AoV", time, 24.302, expr) as f32 - } else if has_fl { - let fl_mm = comp.eval_number(node, "FLength", time, 24.0, expr).max(0.5) as f32; - let sensor_h_mm = ap_h * 25.4; - 2.0 * (sensor_h_mm * 0.5 / fl_mm).atan().to_degrees() + // Fusion derives the vertical AoV from FLength (default 35mm) and the film-gate height; + // a serialized AoV is only an echo of that, so it is the fallback when neither FLength + // nor ApertureH is serialized (default Camera3D vertical AoV ~24.302°). + let fl_mm = if node.inputs.contains_key("FLength") { + Some(comp.eval_number(node, "FLength", time, 35.0, expr).max(0.5) as f32) + } else if node.inputs.contains_key("ApertureH") { + Some(35.0) } else { - 24.302 + None + }; + let aov_deg = match fl_mm { + Some(fl) => 2.0 * (ap_h * 25.4 * 0.5 / fl).atan().to_degrees(), + None => comp.eval_number(node, "AoV", time, 24.302, expr) as f32, }; // Fusion Camera3D defaults ResolutionGateFit to "Height" (vertical AoV is preserved on square/tall renders) let gate_fit = node.static_str("ResolutionGateFit").unwrap_or("Height"); @@ -220,47 +223,34 @@ fn collect_scene_inner( cameras.push(CameraInstance { world, vfov_rad, near, far }); } "LightAmbient" => { - let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; - lights.ambient[0] += r * inten; - lights.ambient[1] += g * inten; - lights.ambient[2] += b * inten; + let Some(color) = light_color(comp, node, time, expr) else { return }; + for (acc, c) in lights.ambient.iter_mut().zip(color) { + *acc += c; + } } "LightDirectional" => { - let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let Some(color) = light_color(comp, node, time, expr) else { return }; // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! let dx = world[8]; let dy = world[9]; let dz = world[10]; let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); lights.dir_to_light = [dx / len, dy / len, dz / len]; - lights.dir_color = [r * inten, g * inten, b * inten]; + lights.dir_color = color; lights.has_dir = true; } "LightPoint" => { - let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let Some(color) = light_color(comp, node, time, expr) else { return }; let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; - let decay_rate = comp.eval_number(node, "DecayRate", time, 1.0, expr) as f32; lights.points.push(PointLight { pos: [world[12], world[13], world[14]], - color: [r * inten, g * inten, b * inten], + color, decay_type, - decay_rate, + decay_rate: 1.0, }); } "LightSpot" => { - let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let Some(color) = light_color(comp, node, time, expr) else { return }; let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; @@ -275,59 +265,53 @@ fn collect_scene_inner( lights.spots.push(SpotLight { pos: [world[12], world[13], world[14]], dir: [dx / len, dy / len, dz / len], - color: [r * inten, g * inten, b * inten], + color, cos_inner: inner_deg.to_radians().cos(), cos_outer: outer_deg.to_radians().cos(), decay_type, }); } "ImagePlane3D" => { + let Some(own) = surface_scope(comp, node, "SurfacePlaneInputs", ovr, time, expr) else { return }; let mat_node = ovr.material_override.or_else(|| { node.connected_node("MaterialInput") .or_else(|| node.connected_node("SceneInput")) .and_then(|s| comp.find_node(s)) }); let mat = resolve_material(comp, mat_node, time, expr); - meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, ovr)); + meshes.push(make_mesh_instance(world, ShapeKind::ImagePlane, mat, None, &own)); } "Shape3D" => { let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); - let disp_sub = if ovr.displace.is_some() { 32 } else { 1 }; + let Some(own) = surface_scope(comp, node, shape_name, ovr, time, expr) else { return }; let shape = match shape_name { "SurfaceSphereInputs" => ShapeKind::Sphere { // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) radius: comp.eval_number(node, "SurfaceSphereInputs.Radius", time, 1.0, expr) as f32, - sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 32.0, expr).round() as u32, - sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 24.0, expr).round() as u32, + sub_base: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, + sub_height: comp.eval_number(node, "SurfaceSphereInputs.SubdivisionLevelHeight", time, 20.0, expr).round() as u32, }, "SurfaceCylinderInputs" => { let start_sw = comp.eval_number(node, "SurfaceCylinderInputs.StartSweep", time, 0.0, expr) as f32; let end_sw = comp.eval_number(node, "SurfaceCylinderInputs.EndSweep", time, 360.0, expr) as f32; ShapeKind::Cylinder { - radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 0.5, expr) as f32, - height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 1.0, expr) as f32, + radius: comp.eval_number(node, "SurfaceCylinderInputs.Radius", time, 1.0, expr) as f32, + height: comp.eval_number(node, "SurfaceCylinderInputs.Height", time, 2.0, expr) as f32, start_sweep_deg: start_sw, end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, - sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32, - } - } - "SurfaceCubeInputs" => { - let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr); - ShapeKind::Cube { - width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32, - height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32, - depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32, + sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, } } + "SurfaceCubeInputs" => ShapeKind::Cube { + width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32, + sub: cube_subdivisions(comp, node, time, expr), + faces: 0b11_1111, + }, _ => { - let sw = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; - let sh = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionHeight", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; - ShapeKind::Plane { - width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32, - height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32, - sub_w: sw, - sub_h: sh, - } + // Fusion's plane is square: Height and SubdivisionHeight follow Width. + let sub = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, 10.0, expr).round() as u32; + let width = comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32; + ShapeKind::Plane { width, height: width, sub_w: sub, sub_h: sub } } }; let mat_node = ovr.material_override.or_else(|| { @@ -336,83 +320,67 @@ fn collect_scene_inner( }); let mut mat = resolve_material(comp, mat_node, time, expr); if mat_node.is_none() { - mat.diffuse_col = [ - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32, - ]; + apply_mtl_std(&mut mat, comp, node, "", time, expr); } - meshes.push(make_mesh_instance(world, shape, mat, None, ovr)); + mat.fx.wireframe = comp.eval_number(node, &format!("{shape_name}.Wireframe"), time, 0.0, expr) > 0.5; + meshes.push(make_mesh_instance(world, shape, mat, None, &own)); } "Cube3D" => { - let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr); - let shape = ShapeKind::Cube { - width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32, - height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32, - depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32, - }; - let mat_node = ovr.material_override.or_else(|| { - [ - "MaterialInput", - "FrontMaterialInput", - "BackMaterialInput", - "RightMaterialInput", - "LeftMaterialInput", - "TopMaterialInput", - "BottomMaterialInput", - ] - .iter() - .find_map(|k| node.connected_node(k)) - .and_then(|s| comp.find_node(s)) - }); - let mut mat = resolve_material(comp, mat_node, time, expr); - if mat_node.is_none() { - let r_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr); - let g_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr); - let b_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr); - let a_def = comp.eval_number(node, "Front.MtlStdInputs.Diffuse.Opacity", time, 1.0, expr); - mat.diffuse_col = [ - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, r_def, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, g_def, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, b_def, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, a_def, expr) as f32, - ]; + if let Some(own) = surface_scope(comp, node, "SurfaceCubeInputs", ovr, time, expr) { + // Fusion's Cube3D only honors Width (all edges) and takes one material per face. + let width = comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32; + let wireframe = comp.eval_number(node, "SurfaceCubeInputs.Wireframe", time, 0.0, expr) > 0.5; + let sub = cube_subdivisions(comp, node, time, expr); + let mut groups: Vec<(Option, ResolvedMaterial, u8)> = Vec::new(); + for (i, face) in CUBE_FACES.iter().enumerate() { + let mat_node = ovr.material_override.or_else(|| { + node.connected_node(&format!("{face}MaterialInput")) + .and_then(|s| comp.find_node(s)) + }); + let mut mat = resolve_material(comp, mat_node, time, expr); + if mat_node.is_none() { + apply_mtl_std(&mut mat, comp, node, &format!("{face}."), time, expr); + } + mat.fx.wireframe = wireframe; + match groups.iter_mut().find(|(n, m, _)| *n == mat_node && *m == mat) { + Some((_, _, mask)) => *mask |= 1 << i, + None => groups.push((mat_node, mat, 1 << i)), + } + } + for (_, mat, faces) in groups { + meshes.push(make_mesh_instance(world, ShapeKind::Cube { width, sub, faces }, mat, None, &own)); + } } - meshes.push(make_mesh_instance(world, shape, mat, None, ovr)); if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); } } "SurfaceFBXMesh" => { - let import_file = node.static_str("ImportFile").unwrap_or(""); - let obj_name = node.static_str("ObjName"); - let scale_units = comp.eval_number(node, "ScaleFileUnitsBy", time, 1.0, expr) as f32; - let verts = load_mesh_cached(import_file, comp.path.as_deref(), obj_name, scale_units); - let shape = ShapeKind::CustomMesh(verts); - let mat_node = ovr.material_override.or_else(|| { - node.connected_node("MaterialInput") - .or_else(|| { - let mut slots: Vec<&String> = node - .inputs - .keys() - .filter(|k| k.starts_with("Materials.")) - .collect(); - slots.sort(); - slots.into_iter().find_map(|k| node.connected_node(k)) - }) - .and_then(|s| comp.find_node(s)) - }); - let mut mat = resolve_material(comp, mat_node, time, expr); - if mat_node.is_none() { - mat.diffuse_col = [ - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32, - comp.eval_number(node, "MtlStdInputs.Diffuse.Opacity", time, 1.0, expr) as f32, - ]; + if let Some(own) = surface_scope(comp, node, "SurfaceFBXInputs", ovr, time, expr) { + let import_file = node.static_str("ImportFile").unwrap_or(""); + let obj_name = node.static_str("ObjName"); + let scale_units = comp.eval_number(node, "ScaleFileUnitsBy", time, 1.0, expr) as f32; + let verts = load_mesh_cached(import_file, comp.path.as_deref(), obj_name, scale_units); + let shape = ShapeKind::CustomMesh(verts); + let mat_node = ovr.material_override.or_else(|| { + node.connected_node("MaterialInput") + .or_else(|| { + let mut slots: Vec<&String> = node + .inputs + .keys() + .filter(|k| k.starts_with("Materials.")) + .collect(); + slots.sort(); + slots.into_iter().find_map(|k| node.connected_node(k)) + }) + .and_then(|s| comp.find_node(s)) + }); + let mut mat = resolve_material(comp, mat_node, time, expr); + if mat_node.is_none() { + apply_mtl_std(&mut mat, comp, node, "", time, expr); + } + meshes.push(make_mesh_instance(world, shape, mat, None, &own)); } - meshes.push(make_mesh_instance(world, shape, mat, None, ovr)); if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); } @@ -445,18 +413,16 @@ fn collect_scene_inner( } } +#[derive(PartialEq)] struct ResolvedMaterial { tex_node: Option, diffuse_col: [f32; 4], specular_col: [f32; 3], specular_intensity: f32, specular_exponent: f32, - uv_offset: [f32; 2], - uv_scale: [f32; 2], - uv_rot: f32, - uv_wrap: u32, - bump_scale: f32, - bump_mode: u32, + fx: MaterialFx, + /// A bare texture operator used as a surface's material renders flat, ignoring lights. + unlit: bool, } impl Default for ResolvedMaterial { @@ -465,14 +431,10 @@ impl Default for ResolvedMaterial { tex_node: None, diffuse_col: [1.0, 1.0, 1.0, 1.0], specular_col: [1.0, 1.0, 1.0], - specular_intensity: 0.15, - specular_exponent: 25.0, - uv_offset: [0.0, 0.0], - uv_scale: [1.0, 1.0], - uv_rot: 0.0, - uv_wrap: 0, - bump_scale: 0.0, - bump_mode: 0, + specular_intensity: 1.0, + specular_exponent: 50.0, + fx: MaterialFx::default(), + unlit: false, } } } @@ -484,54 +446,66 @@ fn make_mesh_instance( text3d: Option, ovr: &SceneOverrides, ) -> MeshInstance { - let has_fx = mat.uv_offset[0].abs() > 1e-6 - || mat.uv_offset[1].abs() > 1e-6 - || (mat.uv_scale[0] - 1.0).abs() > 1e-6 - || (mat.uv_scale[1] - 1.0).abs() > 1e-6 - || mat.uv_rot.abs() > 1e-6 - || mat.uv_wrap != 0 - || mat.bump_scale.abs() > 1e-6; - let wrapped_shape = if has_fx { - ShapeKind::WithMaterialFx { - inner: Box::new(shape), - uv_offset: mat.uv_offset, - uv_scale: mat.uv_scale, - uv_rot: mat.uv_rot, - uv_wrap: mat.uv_wrap, - bump_scale: mat.bump_scale, - bump_mode: mat.bump_mode, - } - } else { - shape - }; MeshInstance { world, - shape: wrapped_shape, + shape: ShapeKind::WithMaterialFx { + inner: Box::new(shape), + fx: MaterialFx { cull_back: ovr.cull_back, cull_front: ovr.cull_front, ..mat.fx }, + }, material_node: mat.tex_node, text3d, diffuse_col: mat.diffuse_col, specular_col: mat.specular_col, specular_intensity: mat.specular_intensity, specular_exponent: mat.specular_exponent, - affected_by_lights: ovr.affected_by_lights.unwrap_or(true), + affected_by_lights: !mat.unlit && ovr.affected_by_lights.unwrap_or(true), flip_normals: ovr.flip_normals, displace: ovr.displace.clone(), - uv_offset: mat.uv_offset, - uv_scale: mat.uv_scale, - uv_rot: mat.uv_rot, - uv_wrap: mat.uv_wrap, - bump_scale: mat.bump_scale, - bump_mode: mat.bump_mode, } } -fn eval_first_present(comp: &Comp, node: &Node, keys: &[&str], time: f64, default: f64, expr: &ExprEngine) -> f32 { - for &k in keys { - if node.inputs.contains_key(k) { - return comp.eval_number(node, k, time, default, expr) as f32; - } +/// Applies a surface's own `.Visibility.*` / `.Lighting.IsAffectedByLights` +/// inputs on top of inherited overrides; `None` when the surface is hidden. +fn surface_scope( + comp: &Comp, + node: &Node, + group: &str, + ovr: &SceneOverrides, + time: f64, + expr: &ExprEngine, +) -> Option { + let flag = |k: &str, d: f64| comp.eval_number(node, &format!("{group}.{k}"), time, d, expr) > 0.5; + flag("Visibility.IsVisible", 1.0).then(|| SceneOverrides { + affected_by_lights: ovr.affected_by_lights.or(Some(flag("Lighting.IsAffectedByLights", 1.0))), + cull_back: flag("Visibility.CullBackFace", 0.0), + cull_front: flag("Visibility.CullFrontFace", 0.0), + ..ovr.clone() + }) +} + +/// `Intensity * RGB` of a light, or `None` when it is disabled or contributes nothing. +fn light_color(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option<[f32; 3]> { + if comp.eval_number(node, "Enabled", time, 1.0, expr) < 0.5 { + return None; } - default as f32 + let intensity = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; + let color = ["Red", "Green", "Blue"].map(|k| comp.eval_number(node, k, time, 1.0, expr) as f32 * intensity); + (color != [0.0; 3]).then_some(color) +} + +/// Cells per cube edge; Fusion's cube keeps all three subdivision counts equal. +fn cube_subdivisions(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> u32 { + comp.eval_number(node, "SurfaceCubeInputs.SubdivisionWidth", time, 10.0, expr).round() as u32 +} + +/// Reads the built-in `MtlStdInputs` material (diffuse and Blinn specular) under an optional +/// per-face `prefix` such as `"Front."` into `mat`. +fn apply_mtl_std(mat: &mut ResolvedMaterial, comp: &Comp, node: &Node, prefix: &str, time: f64, expr: &ExprEngine) { + let f = |k: &str, d: f64| comp.eval_number(node, &format!("{prefix}MtlStdInputs.{k}"), time, d, expr) as f32; + 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)]; + mat.specular_col = [f("Specular.Color.Red", 1.0), f("Specular.Color.Green", 1.0), f("Specular.Color.Blue", 1.0)]; + mat.specular_intensity = f("Specular.Intensity", 1.0).clamp(0.0, 4.0); + mat.specular_exponent = f("Specular.Exponent", 50.0).max(1.0); } fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option { @@ -553,6 +527,20 @@ fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Op None } +/// Mesh-UV -> texture-UV map for a `TextureTransformOperator`. The content is moved by +/// translate * rotate * scale about the pivot in V-up image space, so sampling applies the inverse. +fn texture_transform_uv(translate: [f32; 2], rot_rad: f32, scale: [f32; 2], pivot: [f32; 2]) -> UvAffine { + let inv = |v: f32| 1.0 / if v.abs() < 1e-4 { 1e-4 } else { v }; + let (sn, cs) = rot_rad.sin_cos(); + let sample = |uv: [f32; 2]| { + let q = [uv[0] - translate[0] - pivot[0], (1.0 - uv[1]) - translate[1] - pivot[1]]; + let r = [cs * q[0] + sn * q[1], -sn * q[0] + cs * q[1]]; + [pivot[0] + r[0] * inv(scale[0]), 1.0 - (pivot[1] + r[1] * inv(scale[1]))] + }; + let (o, eu, ev) = (sample([0.0, 0.0]), sample([1.0, 0.0]), sample([0.0, 1.0])); + UvAffine { m: [eu[0] - o[0], eu[1] - o[1], ev[0] - o[0], ev[1] - o[1]], t: o } +} + /// Resolves a 3D material input (`Texture2DOperator`, `TextureTransformOperator`, `BumpMap`, /// `MtlBlinn`, `MtlCookTorrance`, `MtlPhong`, or a direct 2D image node). fn resolve_material( @@ -582,36 +570,29 @@ fn resolve_material_inner( match n.kind.as_str() { "Texture2DOperator" => { let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s)); - let uv_wrap = parse_wrap_mode(comp, n, time, expr).unwrap_or(0); ResolvedMaterial { tex_node: tex_src, - uv_wrap, + fx: MaterialFx { + uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0), + ..default_mat.fx + }, + unlit: true, ..default_mat } } "TextureTransformOperator" => { - let inner_id = n - .connected_node("MaterialInput") - .or_else(|| n.connected_node("Input")) - .and_then(|s| comp.find_node(s)); + let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s)); let mut mat = resolve_material_inner(comp, inner_id, time, expr, depth + 1); - let tx = eval_first_present(comp, n, &["TranslationOffset.X", "Translation.U", "Translation.X"], time, 0.0, expr); - let ty = eval_first_present(comp, n, &["TranslationOffset.Y", "Translation.V", "Translation.Y"], time, 0.0, expr); - let sx = eval_first_present(comp, n, &["Scale.X", "Scale.U"], time, 1.0, expr); - let sy = eval_first_present(comp, n, &["Scale.Y", "Scale.V"], time, 1.0, expr); - let rot_deg = eval_first_present( - comp, - n, - &["Rotation.Z", "RotationOffset", "Rotation.W", "Rotation.U"], - time, - 0.0, - expr, + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + let xf = texture_transform_uv( + [f("Translation.U", 0.0), f("Translation.V", 0.0)], + f("Rotation.W", 0.0).to_radians(), + [f("Scale.U", 1.0), f("Scale.V", 1.0)], + [f("Pivot.U", 0.0), f("Pivot.V", 0.0)], ); - mat.uv_offset = [mat.uv_offset[0] + tx, mat.uv_offset[1] + ty]; - mat.uv_scale = [mat.uv_scale[0] * sx, mat.uv_scale[1] * sy]; - mat.uv_rot += rot_deg.to_radians(); + mat.fx.uv = xf.then(&mat.fx.uv); if let Some(w) = parse_wrap_mode(comp, n, time, expr) { - mat.uv_wrap = w; + mat.fx.uv_wrap = w; } mat } @@ -625,12 +606,14 @@ fn resolve_material_inner( .round() .clamp(0.0, 1.0) as u32 }; - let uv_wrap = parse_wrap_mode(comp, n, time, expr).unwrap_or(0); ResolvedMaterial { tex_node: src, - uv_wrap, - bump_scale: height_scale, - bump_mode, + fx: MaterialFx { + uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0), + bump_scale: height_scale, + bump_mode, + ..default_mat.fx + }, ..default_mat } } @@ -657,45 +640,34 @@ fn resolve_material_inner( comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32, ]; let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32; - let (spec_exp, spec_gain) = if n.kind == "MtlCookTorrance" { - let rough = comp.eval_number(n, "Specular.Roughness", time, 0.4, expr).clamp(0.05, 1.0) as f32; - ((2.0 / (rough * rough) - 2.0).max(2.0), 0.15) - } else { - (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0) + let (spec_exp, spec_model) = match n.kind.as_str() { + "MtlCookTorrance" => ( + comp.eval_number(n, "Specular.Roughness", time, 0.6, expr).clamp(0.05, 1.0) as f32, + SpecModel::CookTorrance, + ), + "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong), + _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn), }; let mut tex_node = diff_mat.tex_node; - let mut uv_offset = diff_mat.uv_offset; - let mut uv_scale = diff_mat.uv_scale; - let mut uv_rot = diff_mat.uv_rot; - let mut uv_wrap = diff_mat.uv_wrap; - let mut bump_scale = diff_mat.bump_scale; - let mut bump_mode = diff_mat.bump_mode; - + let mut fx = MaterialFx { spec_model, ..diff_mat.fx }; if let Some(bm) = bump_mat { - bump_scale = if bm.bump_scale.abs() > 1e-6 { bm.bump_scale } else { 1.0 }; - bump_mode = bm.bump_mode; if tex_node.is_none() { tex_node = bm.tex_node; - uv_offset = bm.uv_offset; - uv_scale = bm.uv_scale; - uv_rot = bm.uv_rot; - uv_wrap = bm.uv_wrap; + fx = MaterialFx { bump_only: true, spec_model, ..bm.fx }; } + fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 }; + fx.bump_mode = bm.fx.bump_mode; } ResolvedMaterial { tex_node, diffuse_col: col, specular_col: spec_col, - specular_intensity: spec_int.clamp(0.0, 4.0) * spec_gain, + specular_intensity: spec_int.clamp(0.0, 4.0), specular_exponent: spec_exp, - uv_offset, - uv_scale, - uv_rot, - uv_wrap, - bump_scale, - bump_mode, + fx, + unlit: false, } } _ => ResolvedMaterial { @@ -911,67 +883,70 @@ mod tests { #[test] fn test_collect_fbx_cube_tex_transform_and_bump() { - let src = r#"Composition { + let faces: String = CUBE_FACES + .iter() + .map(|f| format!(r#"{f}MaterialInput = Input {{ SourceOp = "BlinnBump", Source = "MaterialOutput", }},"#)) + .collect(); + let src = format!( + r#"Composition {{ CurrentTime = 0, - RenderRange = { 0, 10 }, - GlobalRange = { 0, 10 }, - Tools = ordered() { - BG1 = Background { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - }, - }, - Bump1 = BumpMap { - Inputs = { - Input = Input { SourceOp = "BG1", Source = "Output", }, - HeightScale = Input { Value = 4.5, }, - SourceImageType = Input { Value = 1, }, - WrapMode = Input { Value = FuID { "Wrap" }, }, - }, - }, - TexXf = TextureTransformOperator { - Inputs = { - MaterialInput = Input { SourceOp = "Bump1", Source = "MaterialOutput", }, - ["TranslationOffset.X"] = Input { Value = 0.25, }, - ["TranslationOffset.Y"] = Input { Value = -0.5, }, - ["Scale.U"] = Input { Value = 2.0, }, - ["Scale.V"] = Input { Value = 3.0, }, - ["Rotation.Z"] = Input { Value = 90.0, }, - }, - }, - BlinnBump = MtlBlinn { - Inputs = { - ["Diffuse.Color.Red"] = Input { Value = 0.7, }, - ["Bumpmap.Material"] = Input { SourceOp = "TexXf", Source = "MaterialOutput", }, - }, - }, - CubeNode = Cube3D { - Inputs = { - ["SurfaceCubeInputs.Size"] = Input { Value = 2.0, }, - ["SurfaceCubeInputs.Height"] = Input { Value = 4.0, }, - ["Transform3DOp.Translate.Y"] = Input { Value = 1.5, }, - MaterialInput = Input { SourceOp = "BlinnBump", Source = "MaterialOutput", }, - }, - }, - FbxNode = SurfaceFBXMesh { - Inputs = { - ImportFile = Input { Value = "/does/not/exist/model.fbx", }, - ObjName = Input { Value = "HeroMesh", }, - ScaleFileUnitsBy = Input { Value = 0.01, }, - ["Transform3DOp.Translate.X"] = Input { Value = -2.0, }, - ["Materials.Mat0_mat0"] = Input { SourceOp = "TexXf", Source = "MaterialOutput", }, - }, - }, - Merge1 = Merge3D { - Inputs = { - SceneInput1 = Input { SourceOp = "CubeNode", Source = "Output", }, - SceneInput2 = Input { SourceOp = "FbxNode", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse comp"); + RenderRange = {{ 0, 10 }}, + GlobalRange = {{ 0, 10 }}, + Tools = ordered() {{ + BG1 = Background {{ + Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 64, }}, + }}, + }}, + Bump1 = BumpMap {{ + Inputs = {{ + Input = Input {{ SourceOp = "BG1", Source = "Output", }}, + HeightScale = Input {{ Value = 4.5, }}, + SourceImageType = Input {{ Value = 1, }}, + WrapMode = Input {{ Value = FuID {{ "Wrap" }}, }}, + }}, + }}, + TexXf = TextureTransformOperator {{ + Inputs = {{ + MaterialInput = Input {{ SourceOp = "Bump1", Source = "MaterialOutput", }}, + ["Translation.U"] = Input {{ Value = 0.25, }}, + ["Translation.V"] = Input {{ Value = -0.5, }}, + }}, + }}, + BlinnBump = MtlBlinn {{ + Inputs = {{ + ["Diffuse.Color.Red"] = Input {{ Value = 0.7, }}, + ["Bumpmap.Material"] = Input {{ SourceOp = "TexXf", Source = "MaterialOutput", }}, + }}, + }}, + CubeNode = Cube3D {{ + Inputs = {{ + ["SurfaceCubeInputs.Width"] = Input {{ Value = 2.0, }}, + ["SurfaceCubeInputs.Height"] = Input {{ Value = 4.0, }}, + ["Transform3DOp.Translate.Y"] = Input {{ Value = 1.5, }}, + {faces} + }}, + }}, + FbxNode = SurfaceFBXMesh {{ + Inputs = {{ + ImportFile = Input {{ Value = "/does/not/exist/model.fbx", }}, + ObjName = Input {{ Value = "HeroMesh", }}, + ScaleFileUnitsBy = Input {{ Value = 0.01, }}, + ["Transform3DOp.Translate.X"] = Input {{ Value = -2.0, }}, + ["Materials.Mat0_mat0"] = Input {{ SourceOp = "TexXf", Source = "MaterialOutput", }}, + }}, + }}, + Merge1 = Merge3D {{ + Inputs = {{ + SceneInput1 = Input {{ SourceOp = "CubeNode", Source = "Output", }}, + SceneInput2 = Input {{ SourceOp = "FbxNode", Source = "Output", }}, + }}, + }}, + }}, + }}"# + ); + let comp = Comp::from_fusion_str(&src).expect("parse comp"); let expr = ExprEngine::new(); let merge_id = comp.find_node("Merge1").expect("Merge1"); let bg_id = comp.find_node("BG1").expect("BG1"); @@ -990,32 +965,184 @@ mod tests { &mut lights, 0, ); + // Six identical face materials collapse into one cube; Height is ignored. assert_eq!(meshes.len(), 2); - // Cube3D with Blinn + Bumpmap (TextureTransformOperator -> BumpMap) let cube = &meshes[0]; assert!(matches!( cube.shape.base_shape(), - ShapeKind::Cube { width, height, depth } - if (*width - 2.0).abs() < 1e-4 && (*height - 4.0).abs() < 1e-4 && (*depth - 2.0).abs() < 1e-4 + ShapeKind::Cube { width, faces: 0b11_1111, .. } if (*width - 2.0).abs() < 1e-4 )); assert!((cube.world[13] - 1.5).abs() < 1e-4); assert_eq!(cube.material_node, Some(bg_id)); assert!((cube.diffuse_col[0] - 0.7).abs() < 1e-4); - assert!((cube.bump_scale - 4.5).abs() < 1e-4); - assert_eq!(cube.bump_mode, 1); - assert!((cube.uv_offset[0] - 0.25).abs() < 1e-4); - assert!((cube.uv_offset[1] + 0.5).abs() < 1e-4); - assert!((cube.uv_scale[0] - 2.0).abs() < 1e-4); - assert!((cube.uv_scale[1] - 3.0).abs() < 1e-4); - assert!((cube.uv_rot - std::f32::consts::FRAC_PI_2).abs() < 1e-4); - assert_eq!(cube.uv_wrap, 1); + let fx = cube.shape.split_fx().1; + assert!((fx.bump_scale - 4.5).abs() < 1e-4); + assert_eq!(fx.bump_mode, 1); + assert!(!fx.bump_only || cube.material_node.is_some()); + assert_eq!(fx.uv_wrap, 1); + // Content moved +0.25 in U and -0.5 in V (V up) samples from u-0.25 and v-0.5. + let sampled = fx.uv.apply([0.5, 0.5]); + assert!((sampled[0] - 0.25).abs() < 1e-4 && sampled[1].abs() < 1e-4, "{sampled:?}"); - // SurfaceFBXMesh fallback unit box + Materials.* slot resolution let fbx = &meshes[1]; assert!(matches!(fbx.shape.base_shape(), ShapeKind::CustomMesh(v) if v.len() == 36)); assert!((fbx.world[12] + 2.0).abs() < 1e-4); assert_eq!(fbx.material_node, Some(bg_id)); - assert!((fbx.bump_scale - 4.5).abs() < 1e-4); + assert!((fbx.shape.split_fx().1.bump_scale - 4.5).abs() < 1e-4); + } + + fn collect(src: &str, root: &str) -> (Vec, Vec, SceneLights) { + let comp = Comp::from_fusion_str(src).expect("parse comp"); + let expr = ExprEngine::new(); + let id = comp.find_node(root).expect("root node"); + let (mut cams, mut meshes, mut lights) = (Vec::new(), Vec::new(), SceneLights::default()); + collect_scene(&comp, id, 0.0, &expr, mat4_identity(), 1.0, &mut cams, &mut meshes, &mut lights, 0); + (cams, meshes, lights) + } + + fn comp_src(tools: &str) -> String { + format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}") + } + + #[test] + fn camera_vertical_aov_comes_from_default_35mm_focal_length() { + // Serialized AoV is ignored: 35mm on a 1" gate gives 2*atan(12.7/35). + let src = comp_src( + r#"Cam = Camera3D { Inputs = { AoV = Input { Value = 35.0, }, ApertureW = Input { Value = 1.0, }, ApertureH = Input { Value = 1.0, }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#, + ); + let (cams, ..) = collect(&src, "M"); + let expected = 2.0 * (12.7_f32 / 35.0).atan(); + assert!((cams[0].vfov_rad - expected).abs() < 1e-4, "{} vs {expected}", cams[0].vfov_rad); + + let src = comp_src( + r#"Cam = Camera3D { Inputs = { AoV = Input { Value = 35.0, }, ApertureH = Input { Value = 1.0, }, FLength = Input { Value = 50.0, }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#, + ); + let (cams, ..) = collect(&src, "M"); + assert!((cams[0].vfov_rad - 2.0 * (12.7_f32 / 50.0).atan()).abs() < 1e-4); + } + + #[test] + fn plane_is_square_and_defaults_to_ten_cells() { + let src = comp_src( + r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.Height"] = Input { Value = 1.0, }, ["SurfacePlaneInputs.SubdivisionHeight"] = Input { Value = 3, }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "P", Source = "Output", }, }, },"#, + ); + let (_, meshes, _) = collect(&src, "M"); + assert!(matches!( + meshes[0].shape.base_shape(), + ShapeKind::Plane { width, height, sub_w: 10, sub_h: 10 } if *width == 2.0 && *height == 2.0 + )); + } + + #[test] + fn cube3d_ignores_plain_material_input_and_splits_by_face_material() { + let src = comp_src( + r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, }, + Tex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, }, }, + Plain = Cube3D { Inputs = { MaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, }, + Front = Cube3D { Inputs = { FrontMaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Plain", Source = "Output", }, SceneInput2 = Input { SourceOp = "Front", Source = "Output", }, }, },"#, + ); + let (_, meshes, _) = collect(&src, "M"); + let tex = Comp::from_fusion_str(&src).unwrap().find_node("Bg"); + assert_eq!(meshes.len(), 3); + assert!(meshes[0].material_node.is_none(), "Cube3D has no plain MaterialInput"); + assert!(matches!(meshes[1].shape.base_shape(), ShapeKind::Cube { faces: 0b00_0001, .. })); + assert_eq!(meshes[1].material_node, tex); + assert!(matches!(meshes[2].shape.base_shape(), ShapeKind::Cube { faces: 0b11_1110, .. })); + } + + #[test] + fn texture_transform_moves_content_about_a_bottom_left_pivot() { + // Scale 2 about the (0, 0) pivot zooms toward the bottom-left corner (V up). + let zoom = texture_transform_uv([0.0, 0.0], 0.0, [2.0, 2.0], [0.0, 0.0]); + let (bl, tr) = (zoom.apply([0.0, 1.0]), zoom.apply([1.0, 0.0])); + assert!(bl[0].abs() < 1e-5 && (bl[1] - 1.0).abs() < 1e-5); + assert!((tr[0] - 0.5).abs() < 1e-5 && (tr[1] - 0.5).abs() < 1e-5); + + // Content moved right and up samples from smaller u and larger raw v (V down). + let shift = texture_transform_uv([0.25, 0.1], 0.0, [1.0, 1.0], [0.0, 0.0]).apply([0.5, 0.5]); + assert!((shift[0] - 0.25).abs() < 1e-5 && (shift[1] - 0.6).abs() < 1e-5); + + // Counter-clockwise content rotation about the pivot. + let quarter = texture_transform_uv([0.0, 0.0], std::f32::consts::FRAC_PI_2, [1.0, 1.0], [0.0, 0.0]); + let p = quarter.apply([0.0, 0.0]); // top-left corner samples from the content to its right + assert!((p[0] - 1.0).abs() < 1e-5 && (p[1] - 1.0).abs() < 1e-5, "{p:?}"); + } + + #[test] + fn disabled_and_black_lights_do_not_take_slots() { + let spot = |name: &str, extra: &str| format!("{name} = LightSpot {{ Inputs = {{ {extra} }}, }},"); + let src = comp_src(&format!( + "{} {} {} Live = LightSpot {{ }}, M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = \"Off\", Source = \"Output\", }}, SceneInput2 = Input {{ SourceOp = \"Dark\", Source = \"Output\", }}, SceneInput3 = Input {{ SourceOp = \"Live\", Source = \"Output\", }}, }}, }},", + spot("Off", "Enabled = Input { Value = 0, },"), + spot("Dark", "Intensity = Input { Value = 0, },"), + "" + )); + let (_, _, lights) = collect(&src, "M"); + assert_eq!(lights.spots.len(), 1); + assert_eq!(lights.spots[0].color, [1.0, 1.0, 1.0]); + } + + #[test] + fn surface_visibility_lighting_and_bare_texture_flags() { + let src = comp_src( + r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, }, + Tex = Texture2DOperator { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, }, }, + Blinn = MtlBlinn { Inputs = { ["Diffuse.Color.Material"] = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, }, + Hidden = Shape3D { Inputs = { ["SurfacePlaneInputs.Visibility.IsVisible"] = Input { Value = 0, }, }, }, + Unlit = Shape3D { Inputs = { ["SurfacePlaneInputs.Lighting.IsAffectedByLights"] = Input { Value = 0, }, }, }, + Flat = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, }, + Shaded = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, }, + Forced = Override3D { Inputs = { SceneInput = Input { SourceOp = "Unlit", Source = "Output", }, ["Lighting.DoAffectedByLights"] = Input { Value = 1, }, ["Lighting.IsAffectedByLights"] = Input { Value = 1, }, }, }, + 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", }, }, },"#, + ); + let (_, meshes, _) = collect(&src, "M"); + let lit: Vec = meshes.iter().map(|m| m.affected_by_lights).collect(); + assert_eq!(lit, [false, false, true, true], "hidden surface dropped; own flag, bare texture, Blinn, override"); + } + + #[test] + fn specular_models_and_defaults() { + let src = comp_src( + r#"Blinn = MtlBlinn { }, Phong = MtlPhong { }, Cook = MtlCookTorrance { }, + A = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, }, + B = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Phong", Source = "MaterialOutput", }, }, }, + C = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Cook", Source = "MaterialOutput", }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output", }, SceneInput2 = Input { SourceOp = "B", Source = "Output", }, SceneInput3 = Input { SourceOp = "C", Source = "Output", }, }, },"#, + ); + let (_, meshes, _) = collect(&src, "M"); + let models: Vec<_> = meshes.iter().map(|m| (m.shape.split_fx().1.spec_model, m.specular_exponent)).collect(); + assert_eq!(models, [(SpecModel::Blinn, 50.0), (SpecModel::Phong, 50.0), (SpecModel::CookTorrance, 0.6)]); + } + + #[test] + fn bump_only_material_does_not_color_the_surface_and_wireframe_follows_shape_input() { + let src = comp_src( + r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, }, + Bump = BumpMap { Inputs = { Input = Input { SourceOp = "Bg", Source = "Output", }, HeightScale = Input { Value = 2.0, }, }, }, + Blinn = MtlBlinn { Inputs = { ["Bumpmap.Material"] = Input { SourceOp = "Bump", Source = "MaterialOutput", }, }, }, + S = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, ["SurfaceSphereInputs.Wireframe"] = Input { Value = 1, }, MaterialInput = Input { SourceOp = "Blinn", Source = "MaterialOutput", }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, }, },"#, + ); + let (_, meshes, _) = collect(&src, "M"); + let fx = meshes[0].shape.split_fx().1; + assert!(fx.bump_only && fx.wireframe); + assert_eq!(fx.bump_scale, 2.0); + } + + #[test] + fn hidden_cube_still_passes_its_scene_input_through() { + let src = comp_src( + r#"Inner = Shape3D { }, + C = Cube3D { Inputs = { ["SurfaceCubeInputs.Visibility.IsVisible"] = Input { Value = 0, }, SceneInput = Input { SourceOp = "Inner", Source = "Output", }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "C", Source = "Output", }, }, },"#, + ); + let (_, meshes, _) = collect(&src, "M"); + assert_eq!(meshes.len(), 1); + assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::Plane { .. })); } } diff --git a/crates/engine/src/scene3d/mesh.rs b/crates/engine/src/scene3d/mesh.rs index 0981020bc8518638e0191a65e1bd68872b06da86..2ccc46cd2897cae53c6de0976439e9517e240395 100644 --- a/crates/engine/src/scene3d/mesh.rs +++ b/crates/engine/src/scene3d/mesh.rs @@ -20,7 +20,7 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base), - ShapeKind::Cube { width, height, depth } => build_cube(*width, *height, *depth), + ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces), ShapeKind::CustomMesh(verts) => { let v = verts.as_ref().clone(); let idx = (0..v.len() as u32).collect(); @@ -42,32 +42,46 @@ fn build_image_plane(tex_aspect: f32) -> (Vec, Vec) { (verts, vec![0, 1, 2, 0, 2, 3]) } +/// Appends a `sub_w` x `sub_h` grid spanning the quad `tl`/`tr`/`bl` (UV `(0,0)` at `tl`, V down), +/// splitting each cell along its bottom-left to top-right diagonal. +fn push_quad_grid( + verts: &mut Vec, + idx: &mut Vec, + normal: [f32; 3], + [tl, tr, bl]: [[f32; 3]; 3], + sub_w: u32, + sub_h: u32, +) { + let base = verts.len() as u32; + for iy in 0..=sub_h { + let v = iy as f32 / sub_h as f32; + for ix in 0..=sub_w { + let u = ix as f32 / sub_w as f32; + let pos = std::array::from_fn(|k| tl[k] + (tr[k] - tl[k]) * u + (bl[k] - tl[k]) * v); + verts.push(Vertex3D { pos, normal, uv: [u, v] }); + } + } + let row = sub_w + 1; + for iy in 0..sub_h { + for ix in 0..sub_w { + let a = base + iy * row + ix; + let (b, c, d) = (a + row, a + row + 1, a + 1); + idx.extend_from_slice(&[a, b, d, b, c, d]); + } + } +} + fn build_plane(width: f32, height: f32, sub_w: u32, sub_h: u32) -> (Vec, Vec) { - let sw = sub_w.clamp(1, 64); - let sh = sub_h.clamp(1, 64); - let hx = width * 0.5; - let hy = height * 0.5; - let mut verts = Vec::with_capacity(((sw + 1) * (sh + 1)) as usize); - let mut idx = Vec::with_capacity((sw * sh * 6) as usize); - for iy in 0..=sh { - let v = iy as f32 / sh as f32; - let y = hy - v * height; - for ix in 0..=sw { - let u = ix as f32 / sw as f32; - let x = -hx + u * width; - verts.push(Vertex3D { pos: [x, y, 0.0], normal: [0.0, 0.0, 1.0], uv: [u, v] }); - } - } - let row = sw + 1; - for iy in 0..sh { - for ix in 0..sw { - let a = iy * row + ix; - let b = (iy + 1) * row + ix; - let c = (iy + 1) * row + ix + 1; - let d = iy * row + ix + 1; - idx.extend_from_slice(&[a, b, c, a, c, d]); - } - } + let (hx, hy) = (width * 0.5, height * 0.5); + let (mut verts, mut idx) = (Vec::new(), Vec::new()); + push_quad_grid( + &mut verts, + &mut idx, + [0.0, 0.0, 1.0], + [[-hx, hy, 0.0], [hx, hy, 0.0], [-hx, -hy, 0.0]], + sub_w.clamp(1, 64), + sub_h.clamp(1, 64), + ); (verts, idx) } @@ -123,7 +137,7 @@ fn build_sphere(radius: f32, sub_base: u32, sub_height: u32) -> (Vec, let b = (iv + 1) * row + iu; let c = (iv + 1) * row + iu + 1; let d = iv * row + iu + 1; - idx.extend_from_slice(&[a, b, c, a, c, d]); + idx.extend_from_slice(&[a, b, d, b, c, d]); } } (verts, idx) @@ -165,36 +179,45 @@ fn build_cylinder( let b = a + 1; let c = a + 3; let d = a + 2; - idx.extend_from_slice(&[a, b, c, a, c, d]); + idx.extend_from_slice(&[a, b, d, b, c, d]); } (verts, idx) } -fn build_cube(width: f32, height: f32, depth: f32) -> (Vec, Vec) { - let hx = width * 0.5; - let hy = height * 0.5; - let hz = depth * 0.5; - let faces: [([f32; 3], [[f32; 3]; 4]); 6] = [ - ([0.0, 0.0, 1.0], [[-hx, hy, hz], [-hx, -hy, hz], [hx, -hy, hz], [hx, hy, hz]]), - ([0.0, 0.0, -1.0], [[hx, hy, -hz], [hx, -hy, -hz], [-hx, -hy, -hz], [-hx, hy, -hz]]), - ([1.0, 0.0, 0.0], [[hx, hy, hz], [hx, -hy, hz], [hx, -hy, -hz], [hx, hy, -hz]]), - ([-1.0, 0.0, 0.0], [[-hx, hy, -hz], [-hx, -hy, -hz], [-hx, -hy, hz], [-hx, hy, hz]]), - ([0.0, 1.0, 0.0], [[-hx, hy, -hz], [-hx, hy, hz], [hx, hy, hz], [hx, hy, -hz]]), - ([0.0, -1.0, 0.0], [[-hx, -hy, hz], [-hx, -hy, -hz], [hx, -hy, -hz], [hx, -hy, hz]]), +fn build_cube(width: f32, sub: u32, faces_mask: u8) -> (Vec, Vec) { + let h = width * 0.5; + // `[tl, tr, bl]` per face in `CUBE_FACES` order. + let faces: [([f32; 3], [[f32; 3]; 3]); 6] = [ + ([0.0, 0.0, 1.0], [[-h, h, h], [h, h, h], [-h, -h, h]]), + ([0.0, 0.0, -1.0], [[h, h, -h], [-h, h, -h], [h, -h, -h]]), + ([1.0, 0.0, 0.0], [[h, h, h], [h, h, -h], [h, -h, h]]), + ([-1.0, 0.0, 0.0], [[-h, h, -h], [-h, h, h], [-h, -h, -h]]), + ([0.0, 1.0, 0.0], [[-h, h, -h], [h, h, -h], [-h, h, h]]), + ([0.0, -1.0, 0.0], [[-h, -h, h], [h, -h, h], [-h, -h, -h]]), ]; - let mut verts = Vec::with_capacity(24); - let mut idx = Vec::with_capacity(36); - for (n, corners) in faces { - let base = verts.len() as u32; - let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]]; - for (p, uv) in corners.into_iter().zip(uvs) { - verts.push(Vertex3D { pos: p, normal: n, uv }); + let (mut verts, mut idx) = (Vec::new(), Vec::new()); + for (i, (n, corners)) in faces.into_iter().enumerate() { + if faces_mask & (1 << i) != 0 { + push_quad_grid(&mut verts, &mut idx, n, corners, sub, sub); } - idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); } (verts, idx) } +/// Unique triangle edges as a line-list index buffer. +pub(super) fn triangle_edges(indices: &[u32]) -> Vec { + let mut seen = std::collections::HashSet::new(); + let mut edges = Vec::new(); + for tri in indices.chunks_exact(3) { + for (a, b) in [(tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])] { + if seen.insert((a.min(b), a.max(b))) { + edges.extend_from_slice(&[a, b]); + } + } + } + edges +} + pub(super) fn apply_heightmap_displace( verts: &mut [Vertex3D], indices: &[u32], @@ -214,13 +237,13 @@ pub(super) fn apply_heightmap_displace( let b = disp.rgba[off + 2] as f32 / 255.0; let a = disp.rgba[off + 3] as f32 / 255.0; let sample = match disp.channel { - 0 => r, - 1 => g, - 2 => b, - 3 => a, + 1 => r, + 2 => g, + 3 => b, + 4 => a, _ => 0.299 * r + 0.587 * g + 0.114 * b, }; - let d = (sample - 0.5 + disp.bias) * disp.scale; + let d = (sample + disp.bias) * disp.scale; v.pos[0] += v.normal[0] * d; v.pos[1] += v.normal[1] * d; v.pos[2] += v.normal[2] * d; @@ -255,3 +278,45 @@ pub(super) fn apply_heightmap_displace( } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plane_grid_splits_cells_along_bottom_left_to_top_right() { + let (verts, idx) = build_plane(2.0, 2.0, 2, 2); + assert_eq!(verts.len(), 9); + assert_eq!(idx.len(), 2 * 2 * 6); + // First cell: a = top-left (0), b = bottom-left (3), c = bottom-right (4), d = top-right (1). + assert_eq!(&idx[..6], &[0, 3, 1, 3, 4, 1]); + } + + #[test] + fn cube_face_mask_and_subdivision_counts() { + let (all, all_idx) = build_cube(1.0, 3, 0b11_1111); + assert_eq!(all.len(), 6 * 16); + assert_eq!(all_idx.len(), 6 * 3 * 3 * 6); + let (front, _) = build_cube(1.0, 1, 0b00_0001); + assert!(front.iter().all(|v| v.normal == [0.0, 0.0, 1.0])); + } + + #[test] + fn triangle_edges_are_deduplicated() { + // Two triangles sharing edge 1-2. + let edges = triangle_edges(&[0, 1, 2, 1, 3, 2]); + assert_eq!(edges.len(), 5 * 2); + } + + #[test] + fn displace_channel_zero_is_luma_and_one_is_red() { + let displace = |channel| { + let (mut verts, idx) = build_plane(1.0, 1.0, 1, 1); + let disp = DisplaceHeightmap { size: [1, 1], rgba: vec![255, 0, 0, 255], scale: 1.0, bias: 0.0, channel }; + apply_heightmap_displace(&mut verts, &idx, &disp); + verts[0].pos[2] + }; + assert!((displace(1) - 1.0).abs() < 1e-4, "red channel"); + assert!((displace(0) - 0.299).abs() < 1e-3, "luma"); + } +} diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index 840ea3e2e79f6bfa62b977644ba50a2baf8448bb..370196f1e3f7b9b5b2f912004f4be77b9b5e97e3 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -22,15 +22,17 @@ pub use shader::Vertex3D; use std::sync::Arc; use crate::cache::CachedTexture; -use mesh::{apply_heightmap_displace, build_shape_mesh}; +use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; use model::NodeId; -use shader::{MeshUniform, SHADER_3D}; +use shader::{MeshUniform, MAX_LIGHTS, SHADER_3D}; pub type Mat4 = [f32; 16]; // Column-major 4x4 pub struct Scene3DRenderer { bgl: wgpu::BindGroupLayout, - pipeline: wgpu::RenderPipeline, + /// `[triangles, lines][back-facing, front-facing]`; back faces draw first so translucent + /// faces show the inside of closed meshes. + pipelines: [[wgpu::RenderPipeline; 2]; 2], sampler: wgpu::Sampler, } @@ -48,51 +50,102 @@ pub enum ShapeKind { Sphere { radius: f32, sub_base: u32, sub_height: u32 }, Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 }, Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, - Cube { width: f32, height: f32, depth: f32 }, + /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order. + Cube { width: f32, sub: u32, faces: u8 }, TextPlate { width: f32, height: f32, depth: f32, slices: u32 }, CustomMesh(Arc>), - /// Wraps a base `ShapeKind` with UV transform and bump parameters so they travel - /// cleanly through `DrawMesh` into `Scene3DRenderer::render_meshes`. - WithMaterialFx { - inner: Box, - uv_offset: [f32; 2], - uv_scale: [f32; 2], - uv_rot: f32, - uv_wrap: u32, - bump_scale: f32, - bump_mode: u32, - }, + /// Carries the material's UV transform and bump parameters through `DrawMesh`. + WithMaterialFx { inner: Box, fx: MaterialFx }, +} + +/// Face order shared by `Cube3D` material inputs and `build_cube`. +pub const CUBE_FACES: [&str; 6] = ["Front", "Back", "Right", "Left", "Top", "Bottom"]; + +/// Affine map from mesh UV (V down) to texture UV: `uv' = m * uv + t`, `m` column-major. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvAffine { + pub m: [f32; 4], + pub t: [f32; 2], +} + +impl UvAffine { + pub const IDENTITY: Self = Self { m: [1.0, 0.0, 0.0, 1.0], t: [0.0, 0.0] }; + + pub fn apply(&self, uv: [f32; 2]) -> [f32; 2] { + [ + self.m[0] * uv[0] + self.m[2] * uv[1] + self.t[0], + self.m[1] * uv[0] + self.m[3] * uv[1] + self.t[1], + ] + } + + /// The map applying `self` first, then `outer`. + pub fn then(&self, outer: &Self) -> Self { + let o = outer.apply(self.t); + Self { + m: [ + outer.m[0] * self.m[0] + outer.m[2] * self.m[1], + outer.m[1] * self.m[0] + outer.m[3] * self.m[1], + outer.m[0] * self.m[2] + outer.m[2] * self.m[3], + outer.m[1] * self.m[2] + outer.m[3] * self.m[3], + ], + t: o, + } + } +} + +/// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for +/// `Blinn`/`Phong` and the roughness for `CookTorrance`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SpecModel { + #[default] + Blinn, + Phong, + CookTorrance, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaterialFx { + pub uv: UvAffine, + /// 0 = clamp, 1 = wrap, 2 = mirror + pub uv_wrap: u32, + pub bump_scale: f32, + /// 0 = height map, 1 = normal map + pub bump_mode: u32, + /// The bound texture only perturbs normals; it does not color the surface. + pub bump_only: bool, + pub spec_model: SpecModel, + /// Draw the mesh edges as lines instead of filled triangles. + pub wireframe: bool, + pub cull_back: bool, + pub cull_front: bool, +} + +impl Default for MaterialFx { + fn default() -> Self { + Self { + uv: UvAffine::IDENTITY, + uv_wrap: 0, + bump_scale: 0.0, + bump_mode: 0, + bump_only: false, + spec_model: SpecModel::Blinn, + wireframe: false, + cull_back: false, + cull_front: false, + } + } } impl ShapeKind { /// Returns the underlying geometry shape without any `WithMaterialFx` wrapper. pub fn base_shape(&self) -> &ShapeKind { - match self { - ShapeKind::WithMaterialFx { inner, .. } => inner.base_shape(), - other => other, - } + self.split_fx().0 } - pub(super) fn unwrap_fx(&self) -> (&ShapeKind, [f32; 2], [f32; 2], f32, u32, f32, u32) { + pub fn split_fx(&self) -> (&ShapeKind, MaterialFx) { match self { - ShapeKind::WithMaterialFx { - inner, - uv_offset, - uv_scale, - uv_rot, - uv_wrap, - bump_scale, - bump_mode, - } => ( - inner.base_shape(), - *uv_offset, - *uv_scale, - *uv_rot, - *uv_wrap, - *bump_scale, - *bump_mode, - ), - other => (other, [0.0, 0.0], [1.0, 1.0], 0.0, 0, 0.0, 0), + ShapeKind::WithMaterialFx { inner, fx } => (inner.base_shape(), *fx), + other => (other, MaterialFx::default()), } } } @@ -102,7 +155,7 @@ pub struct Displace3DSpec { pub input_node: NodeId, pub scale: f32, pub bias: f32, - pub channel: i32, // 0=R, 1=G, 2=B, 3=A, 4=Luma (default) + pub channel: i32, // 0=Luma (default), 1=R, 2=G, 3=B, 4=A } #[derive(Clone, Debug)] @@ -132,19 +185,15 @@ pub struct MeshInstance { pub affected_by_lights: bool, pub flip_normals: bool, pub displace: Option, - pub uv_offset: [f32; 2], - pub uv_scale: [f32; 2], - pub uv_rot: f32, - pub uv_wrap: u32, - pub bump_scale: f32, - pub bump_mode: u32, } #[derive(Clone, Copy, Debug)] pub struct PointLight { pub pos: [f32; 3], pub color: [f32; 3], + /// 0 = none, 1 = linear (1/d), 2 = quadratic (1/d²) pub decay_type: f32, + /// Unused by the shader; `Renderer3D` still folds it into its cache key. pub decay_rate: f32, } @@ -198,7 +247,7 @@ impl Scene3DRenderer { pub fn new(device: &wgpu::Device) -> Self { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("scene3d-shader"), - source: wgpu::ShaderSource::Wgsl(SHADER_3D.into()), + source: wgpu::ShaderSource::Wgsl(SHADER_3D.replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()).into()), }); let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("scene3d-bgl"), @@ -245,19 +294,22 @@ impl Scene3DRenderer { wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 }, ], }; - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + let make_pipeline = |topology: wgpu::PrimitiveTopology, back_pass: bool| device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("scene3d-mesh"), layout: Some(&pl), vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_mesh"), compilation_options: Default::default(), - buffers: &[Some(vbuf_layout)], + buffers: &[Some(vbuf_layout.clone())], }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_mesh"), - compilation_options: Default::default(), + compilation_options: wgpu::PipelineCompilationOptions { + constants: &[("BACK_PASS", if back_pass { 1.0 } else { 0.0 })], + ..Default::default() + }, targets: &[Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba8Unorm, blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), @@ -265,7 +317,7 @@ impl Scene3DRenderer { })], }), primitive: wgpu::PrimitiveState { - topology: wgpu::PrimitiveTopology::TriangleList, + topology, cull_mode: None, ..Default::default() }, @@ -280,6 +332,8 @@ impl Scene3DRenderer { multiview_mask: None, cache: None, }); + let pipelines = [wgpu::PrimitiveTopology::TriangleList, wgpu::PrimitiveTopology::LineList] + .map(|topology| [make_pipeline(topology, true), make_pipeline(topology, false)]); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("scene3d-linear"), address_mode_u: wgpu::AddressMode::ClampToEdge, @@ -289,7 +343,7 @@ impl Scene3DRenderer { mipmap_filter: wgpu::MipmapFilterMode::Linear, ..Default::default() }); - Self { bgl, pipeline, sampler } + Self { bgl, pipelines, sampler } } #[allow(clippy::too_many_arguments)] @@ -338,6 +392,9 @@ impl Scene3DRenderer { order.sort_by(|a, b| a.1.total_cmp(&b.1)); struct GpuDraw { + wireframe: bool, + /// Skip the `[back-facing, front-facing]` pass. + cull: [bool; 2], bg: wgpu::BindGroup, vbuf: wgpu::Buffer, ibuf: wgpu::Buffer, @@ -351,15 +408,17 @@ impl Scene3DRenderer { .as_ref() .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) .unwrap_or(16.0 / 9.0); - let (base_shape, uv_offset, uv_scale, uv_rot, uv_wrap, bump_scale, bump_mode) = - m.shape.unwrap_fx(); - let (mut verts, indices) = build_shape_mesh(base_shape, aspect); + let (base_shape, fx) = m.shape.split_fx(); + let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect); if indices.is_empty() { continue; } if let Some(disp) = &m.displace { apply_heightmap_displace(&mut verts, &indices, disp); } + if fx.wireframe { + indices = triangle_edges(&indices); + } let vbytes = bytemuck::cast_slice(&verts); let ibytes = bytemuck::cast_slice(&indices); let vbuf = device.create_buffer(&wgpu::BufferDescriptor { @@ -387,18 +446,18 @@ impl Scene3DRenderer { } else { [0.0; 4] }; - let mut point_pos = [[0.0_f32; 4]; 4]; - let mut point_col = [[0.0_f32; 4]; 4]; - let n_pt = lights.points.len().min(4); - for (pi, pl) in lights.points.iter().take(4).enumerate() { + let mut point_pos = [[0.0_f32; 4]; MAX_LIGHTS]; + let mut point_col = [[0.0_f32; 4]; MAX_LIGHTS]; + let n_pt = lights.points.len().min(MAX_LIGHTS); + for (pi, pl) in lights.points.iter().take(MAX_LIGHTS).enumerate() { point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type]; - point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], pl.decay_rate]; + point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], 0.0]; } - let mut spot_pos = [[0.0_f32; 4]; 4]; - let mut spot_dir = [[0.0_f32; 4]; 4]; - let mut spot_col = [[0.0_f32; 4]; 4]; - let n_sp = lights.spots.len().min(4); - for (si, sl) in lights.spots.iter().take(4).enumerate() { + let mut spot_pos = [[0.0_f32; 4]; MAX_LIGHTS]; + let mut spot_dir = [[0.0_f32; 4]; MAX_LIGHTS]; + let mut spot_col = [[0.0_f32; 4]; MAX_LIGHTS]; + let n_sp = lights.spots.len().min(MAX_LIGHTS); + for (si, sl) in lights.spots.iter().take(MAX_LIGHTS).enumerate() { spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner]; spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer]; spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type]; @@ -430,8 +489,9 @@ impl Scene3DRenderer { dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0], cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0], - uv_xform: [uv_offset[0], uv_offset[1], uv_scale[0], uv_scale[1]], - mat_fx: [uv_rot, uv_wrap as f32, bump_scale, bump_mode as f32], + uv_xform: fx.uv.m, + uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, 0.0], + 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], point_pos, point_col, spot_pos, @@ -456,6 +516,8 @@ impl Scene3DRenderer { ], }); draw_items.push(GpuDraw { + wireframe: fx.wireframe, + cull: [fx.cull_back, fx.cull_front], bg, vbuf, ibuf, @@ -486,12 +548,109 @@ impl Scene3DRenderer { occlusion_query_set: None, multiview_mask: None, }); - pass.set_pipeline(&self.pipeline); for d in &draw_items { pass.set_bind_group(0, &d.bg, &[]); pass.set_vertex_buffer(0, d.vbuf.slice(..)); pass.set_index_buffer(d.ibuf.slice(..), wgpu::IndexFormat::Uint32); - pass.draw_indexed(0..d.idx_count, 0, 0..1); + for (pipeline, culled) in self.pipelines[d.wireframe as usize].iter().zip(d.cull) { + if !culled { + pass.set_pipeline(pipeline); + pass.draw_indexed(0..d.idx_count, 0, 0..1); + } + } } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::Engine; + use model::Comp; + + /// Renders `Renderer3D` node `R` of a 64x64 scene viewed by a camera at z=4.2 (35mm lens, 1" gate). + fn render(lighting: bool, scene: &str) -> Option> { + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ + 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, }}, }}, }}, + Tex = Texture2DOperator {{ Inputs = {{ Input = Input {{ SourceOp = "Bg", Source = "Output", }}, }}, }}, + Flat = MtlBlinn {{ Inputs = {{ ["Specular.Intensity"] = Input {{ Value = 0, }}, }}, }}, + Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 4.2, }}, ApertureW = Input {{ Value = 1.0, }}, ApertureH = Input {{ Value = 1.0, }}, }}, }}, + {scene} + R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, ["RendererSoftware.LightingEnabled"] = Input {{ Value = {}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }}, + }} }}"#, + lighting as u8 + ); + let comp = Comp::from_fusion_str(&src).expect("parse render comp"); + let mut eng = Engine::new_headless().ok()?; + let id = comp.find_node("R").expect("R"); + let (tex, _) = eng.evaluate(&comp, id, 0.0); + eng.readback_rgba(&tex).ok() + } + + fn center(px: &[u8]) -> [u8; 4] { + let i = (32 * 64 + 32) * 4; + [px[i], px[i + 1], px[i + 2], px[i + 3]] + } + + const PLANE: &str = r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2, }, MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", }, }, },"#; + + #[test] + fn point_light_decay_is_inverse_distance_and_inverse_square() { + for (decay, expected) in [(0, 255.0), (1, 127.5), (2, 63.75)] { + let scene = format!( + r#"{PLANE} L = LightPoint {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 2, }}, DecayType = Input {{ Value = {decay}, }}, }}, }}, + M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# + ); + let Some(px) = render(true, &scene) else { return }; + let c = center(&px); + assert!((c[0] as f32 - expected).abs() <= 3.0, "decay {decay}: {c:?}"); + } + } + + #[test] + fn bare_texture_renders_unlit_but_blinn_diffuse_is_lit() { + let scene = |mat: &str| { + format!( + r#"Shaded = MtlBlinn {{ Inputs = {{ ["Diffuse.Color.Material"] = Input {{ SourceOp = "Tex", Source = "MaterialOutput", }}, }}, }}, + P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 2, }}, MaterialInput = Input {{ SourceOp = "{mat}", Source = "MaterialOutput", }}, }}, }}, + M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# + ) + }; + let (Some(flat), Some(shaded)) = (render(true, &scene("Tex")), render(true, &scene("Shaded"))) else { return }; + assert_eq!(center(&flat), [255, 128, 64, 255]); + assert_eq!(center(&shaded)[..3], [0, 0, 0], "lighting on with no lights is black"); + } + + #[test] + fn wireframe_draws_edges_only() { + let scene = |wire: u8| { + format!( + r#"P = Shape3D {{ Inputs = {{ ["SurfacePlaneInputs.Width"] = Input {{ Value = 2, }}, ["SurfacePlaneInputs.SubdivisionWidth"] = Input {{ Value = 2, }}, ["SurfacePlaneInputs.Wireframe"] = Input {{ Value = {wire}, }}, }}, }}, + M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# + ) + }; + let (Some(solid), Some(wire)) = (render(false, &scene(0)), render(false, &scene(1))) else { return }; + let coverage = |px: &[u8]| px.chunks_exact(4).filter(|c| c[3] > 0).count(); + assert_eq!(center(&solid)[3], 255); + assert!(coverage(&wire) > 0 && coverage(&wire) < coverage(&solid) / 4, "{} vs {}", coverage(&wire), coverage(&solid)); + } + + #[test] + fn translucent_front_faces_show_the_inside_of_a_closed_mesh() { + // Half-opaque cube: front and back faces both blend, so coverage accumulates to 0.75. + let scene = r#"B = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, ["MtlStdInputs.Diffuse.Opacity"] = Input { Value = 0.5, }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "B", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#; + let Some(px) = render(false, scene) else { return }; + let alpha = center(&px)[3] as i32; + assert!((alpha - 191).abs() <= 3, "alpha {alpha}"); + } + + #[test] + fn uv_affine_then_applies_self_first() { + let shift = UvAffine { m: [1.0, 0.0, 0.0, 1.0], t: [0.5, 0.0] }; + let double = UvAffine { m: [2.0, 0.0, 0.0, 2.0], t: [0.0, 0.0] }; + assert_eq!(shift.then(&double).apply([0.0, 0.0]), [1.0, 0.0]); + assert_eq!(double.then(&shift).apply([0.0, 0.0]), [0.5, 0.0]); + } +} diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index 21d44d202dacead084ff8bfb204579b777a4070b..d71558c468ff74c44b96cff1c68b99821574010c 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -2,6 +2,9 @@ use bytemuck::{Pod, Zeroable}; +/// Point and spot lights each get this many shader slots. +pub(super) const MAX_LIGHTS: usize = 8; + #[repr(C)] #[derive(Clone, Copy, Debug, Pod, Zeroable)] pub struct Vertex3D { @@ -33,22 +36,25 @@ pub(super) struct MeshUniform { pub(super) cam_pos: [f32; 4], /// `[num_point_lights, num_spot_lights, 0, 0]` pub(super) light_counts: [f32; 4], - /// UV transform `[offset_x, offset_y, scale_x, scale_y]` + /// UV affine matrix, column-major `[m00, m10, m01, m11]` pub(super) uv_xform: [f32; 4], - /// Material effects `[uv_rot_rad, uv_wrap_mode, bump_scale, bump_mode]` + /// UV translation and wrap mode `[tx, ty, wrap, 0]` + pub(super) uv_off_wrap: [f32; 4], + /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance]` pub(super) mat_fx: [f32; 4], /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` - pub(super) point_pos: [[f32; 4]; 4], - /// Point light colors * intensity `(r, g, b, decay_rate)` - pub(super) point_col: [[f32; 4]; 4], + pub(super) point_pos: [[f32; 4]; MAX_LIGHTS], + /// Point light colors * intensity `(r, g, b, 0)` + pub(super) point_col: [[f32; 4]; MAX_LIGHTS], /// Spot light positions `(x, y, z, cos_inner)` - pub(super) spot_pos: [[f32; 4]; 4], + pub(super) spot_pos: [[f32; 4]; MAX_LIGHTS], /// Spot light forward directions `(dx, dy, dz, cos_outer)` - pub(super) spot_dir: [[f32; 4]; 4], + pub(super) spot_dir: [[f32; 4]; MAX_LIGHTS], /// Spot light colors * intensity `(r, g, b, decay_type)` - pub(super) spot_col: [[f32; 4]; 4], + pub(super) spot_col: [[f32; 4]; MAX_LIGHTS], } +/// WGSL source; `MAX_LIGHTS` is substituted with the Rust constant at pipeline creation. pub(super) const SHADER_3D: &str = r#" struct MeshUniform { mvp: mat4x4, @@ -63,14 +69,17 @@ struct MeshUniform { cam_pos: vec4, light_counts: vec4, uv_xform: vec4, + uv_off_wrap: vec4, mat_fx: vec4, - point_pos: array, 4>, - point_col: array, 4>, - spot_pos: array, 4>, - spot_dir: array, 4>, - spot_col: array, 4>, + point_pos: array, MAX_LIGHTS>, + point_col: array, MAX_LIGHTS>, + spot_pos: array, MAX_LIGHTS>, + spot_dir: array, MAX_LIGHTS>, + spot_col: array, MAX_LIGHTS>, }; +override BACK_PASS: bool = false; + @group(0) @binding(0) var u: MeshUniform; @group(0) @binding(1) var mat_tex: texture_2d; @group(0) @binding(2) var mat_samp: sampler; @@ -105,14 +114,13 @@ fn vs_mesh(v: VsIn) -> VsOut { return out; } -fn light_attenuation(dist: f32, decay_type: f32, decay_rate: f32) -> f32 { +fn light_attenuation(dist: f32, decay_type: f32) -> f32 { let dt = i32(decay_type + 0.5); - let rate = max(decay_rate, 0.001); + let d = max(dist, 1e-3); if (dt == 1) { - return 1.0 / max(1.0 + dist * rate, 1e-4); + return 1.0 / d; } else if (dt == 2) { - let d = dist * rate; - return 1.0 / max(1.0 + d * d, 1e-4); + return 1.0 / (d * d); } return 1.0; } @@ -134,19 +142,27 @@ fn eval_light_contrib( var out = albedo * light_rgb * ndotl; if (spec_int > 1e-4) { let h = normalize(l + v); - let spec = pow(max(dot(n, h), 0.0), shininess) * spec_int; - out = out + light_rgb * spec_rgb * spec; + let model = i32(u.mat_fx.w + 0.5); + var lobe: f32; + if (model == 1) { + lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess); + } else if (model == 2) { + // Beckmann distribution; shininess carries roughness. + let nh = max(dot(n, h), 1e-3); + let m2 = max(shininess * shininess, 1e-3); + lobe = 0.03 * exp(-(1.0 - nh * nh) / (nh * nh * m2)) / (3.14159265 * m2 * nh * nh * nh * nh); + } else { + lobe = pow(max(dot(n, h), 0.0), shininess); + } + out = out + light_rgb * spec_rgb * (lobe * spec_int); } return out; } -fn apply_uv_xform(raw_uv: vec2, uv_xform: vec4, rot_wrap: vec2) -> vec2 { - let p = raw_uv - vec2(0.5, 0.5); - let c = cos(rot_wrap.x); - let s = sin(rot_wrap.x); - let r = vec2(p.x * c - p.y * s, p.x * s + p.y * c); - var uv = r * uv_xform.zw + vec2(0.5, 0.5) + uv_xform.xy; - let wrap = i32(rot_wrap.y + 0.5); +fn apply_uv_xform(raw_uv: vec2) -> vec2 { + let m = u.uv_xform; + var uv = vec2(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; + let wrap = i32(u.uv_off_wrap.z + 0.5); if (wrap == 1) { uv = fract(uv); } else if (wrap == 2) { @@ -210,7 +226,11 @@ fn perturb_bump_normal( @fragment fn fs_mesh(in: VsOut) -> @location(0) vec4 { - let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.mat_fx.xy); + let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; + if (facing_away != BACK_PASS) { + discard; + } + let uv_xformed = apply_uv_xform(in.uv); let dpdx_w = dpdx(in.world_pos); let dpdy_w = dpdy(in.world_pos); let duvdx = dpdx(uv_xformed); @@ -229,7 +249,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { } } tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); - col = tex_col * u.diffuse_col; + col = select(tex_col, vec4(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; } if (col.a <= 0.002) { discard; @@ -239,7 +259,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { // Premultiplied -> unpremultiplied albedo for lighting let albedo = select(vec3(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5); var n = normalize(in.world_n); - if (u.flags.x > 0.5 && abs(u.mat_fx.z) > 1e-5) { + if (u.flags.x > 0.5 && abs(u.mat_fx.x) > 1e-5) { n = perturb_bump_normal( n, dpdx_w, @@ -248,13 +268,13 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { duvdy, uv_samp, tex_col, - u.mat_fx.z, - u.mat_fx.w, + u.mat_fx.x, + u.mat_fx.y, ); } let v = normalize(u.cam_pos.xyz - in.world_pos); let spec_rgb = u.specular_col.rgb; - let shininess = max(u.specular_col.w, 1.0); + let shininess = select(max(u.specular_col.w, 1.0), u.specular_col.w, u.mat_fx.w > 1.5); let spec_int = u.flags.z; var lit = albedo * u.ambient.rgb; @@ -264,16 +284,16 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { } let n_pt = i32(u.light_counts.x + 0.5); - for (var i: i32 = 0; i < 4; i = i + 1) { + for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) { if (i >= n_pt) { break; } let to_l = u.point_pos[i].xyz - in.world_pos; let dist = max(length(to_l), 1e-4); - let att = light_attenuation(dist, u.point_pos[i].w, u.point_col[i].w); + let att = light_attenuation(dist, u.point_pos[i].w); lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); } let n_sp = i32(u.light_counts.y + 0.5); - for (var i: i32 = 0; i < 4; i = i + 1) { + for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) { if (i >= n_sp) { break; } let to_l = u.spot_pos[i].xyz - in.world_pos; let dist = max(length(to_l), 1e-4); @@ -284,7 +304,7 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { let cos_outer = u.spot_dir[i].w; let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); if (cone > 0.0) { - let att = light_attenuation(dist, u.spot_col[i].w, 1.0) * cone; + let att = light_attenuation(dist, u.spot_col[i].w) * cone; lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); } }