From 4b05551050c90049563a0a4869e2ba7ee5a27041 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Wed, 2 Dec 2026 14:09:47 -0800 Subject: [PATCH] feat(scene3d): implement 15 Fusion 3D built-ins (LightDome, MtlPBRUber, Fog3D, UVMap, etc.) and calibrate SphereMap/MtlChanBool/MtlReflect Adds LightDome, MtlMerge3D, MtlPBRUber, MtlStereoMix3D, CubeMap, FalloffOperator, FastNoiseTexture3D, TexCatcher, TexGradient, Fog3D, Locator3D, Ribbon3D, Triangulate3D, Weld3D and UVMap. Per-mesh surface state moves into a Pod SurfaceFx block shared with surface_fx.wgsl; the mesh shader moves to mesh.wgsl. SphereMap drops StartAngle/EndAngle (no effect in Fusion) and fixes its equirect/angular lookup; MtlReflect and MtlChanBool drop fallback inputs and treat unwired inputs as Fusion does; Bender3D follows Fusion's axes, extends rigidly past its range and turns normals with the warp's rotation. Fuzz: SphereMap 99.955%, MtlChanBool 99.037%, MtlReflect 99.968%, Bender3D 99.838%. Assisted-by: claude-opus-5.5 --- crates/engine/src/scene3d/collect.rs | 434 +++++-------- crates/engine/src/scene3d/deform.rs | 323 +++------- crates/engine/src/scene3d/fx.rs | 126 ++++ crates/engine/src/scene3d/materials.rs | 225 +++++++ crates/engine/src/scene3d/mesh.rs | 51 +- crates/engine/src/scene3d/mesh.wgsl | 706 ++++++++++++++++++++++ crates/engine/src/scene3d/mod.rs | 60 +- crates/engine/src/scene3d/scene_ops.rs | 303 ++++++++++ crates/engine/src/scene3d/shader.rs | 705 +-------------------- crates/engine/src/scene3d/surface_fx.wgsl | 232 +++++++ crates/engine/src/scene3d/textures.rs | 168 +++++ 11 files changed, 2075 insertions(+), 1258 deletions(-) create mode 100644 crates/engine/src/scene3d/fx.rs create mode 100644 crates/engine/src/scene3d/materials.rs create mode 100644 crates/engine/src/scene3d/mesh.wgsl create mode 100644 crates/engine/src/scene3d/scene_ops.rs create mode 100644 crates/engine/src/scene3d/surface_fx.wgsl create mode 100644 crates/engine/src/scene3d/textures.rs diff --git a/crates/engine/src/scene3d/collect.rs b/crates/engine/src/scene3d/collect.rs index f9b02cf13dc86214804b83c57ebdcb2b419612c1..be2b5c9b8abdfb4df2b83212659fe6cbbdb66ced 100644 --- a/crates/engine/src/scene3d/collect.rs +++ b/crates/engine/src/scene3d/collect.rs @@ -11,6 +11,8 @@ use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, use super::math::{ mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, }; +use super::fx::layer_mode; +use super::{materials, scene_ops, textures}; use super::{ CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights, ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, Vertex3D, CUBE_FACES, @@ -133,7 +135,8 @@ fn collect_scene_inner( let world = mat4_mul(parent_xform, local); match node.kind.as_str() { - "Merge3D" | "Transform3D" => { + // Triangulate3D only matters to Fusion's own wireframe display; it passes the scene through. + "Merge3D" | "Transform3D" | "Triangulate3D" => { let mut input_names: Vec<&String> = node .inputs .keys() @@ -206,6 +209,50 @@ fn collect_scene_inner( collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); } } + "Weld3D" => { + let mut next_ovr = ovr.clone(); + if comp.eval_number(node, "WeldNormals", time, 0.0, expr) > 0.5 { + next_ovr.smooth_normals_deg = Some(180.0); + } + 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, &next_ovr, cameras, meshes, lights, visited, depth + 1); + } + } + "Fog3D" | "UVMap" => { + let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { + return; + }; + let mut child_meshes = Vec::new(); + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, &mut child_meshes, lights, visited, depth + 1); + if node.kind == "Fog3D" { + scene_ops::fog(comp, node, time, expr, &mut child_meshes); + } else if let Some(map) = scene_ops::UvMap::from_node(comp, node, time, expr) { + scene_ops::uv_map(&map, &mut child_meshes, |m| infer_image_plane_aspect(comp, m.material_node, time, expr, render_aspect)); + } + let remaining = MAX_SCENE_MESHES.saturating_sub(meshes.len()); + meshes.extend(child_meshes.into_iter().take(remaining)); + } + "Locator3D" => { + if let Some((shape, mat)) = scene_ops::locator(comp, node, time, expr) { + meshes.push(make_mesh_instance(world, shape, mat, None, ovr)); + } + // The locator's own transform does not reach its scene input. + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, parent_xform, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); + } + } + "Ribbon3D" => { + let mat_node = ovr.material_override.or_else(|| node.connected_node("MaterialInput").and_then(|s| comp.find_node(s))); + let mut mat = resolve_material(comp, mat_node, time, expr, visited); + if !mat.has_material_shader { + apply_mtl_std(&mut mat, comp, node, "", time, expr); + } + let (shape, mat) = scene_ops::ribbon(comp, node, time, expr, mat); + 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, visited, depth + 1); + } + } "Displace3D" => { let mut next_ovr = ovr.clone(); if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { @@ -520,9 +567,12 @@ fn collect_scene_inner( collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); } } - "LightAmbient" => { + "LightAmbient" | "LightDome" => { lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32; - if let Some(color) = light_color(comp, node, time, expr) { + // An untextured dome lights nothing; a textured one's irradiance is approximated as a + // uniform ambient, exact for a constant white texture. + let lit = node.kind == "LightAmbient" || node.connected_node("DomeTexture").is_some(); + if let Some(color) = light_color(comp, node, time, expr).filter(|_| lit) { for (acc, c) in lights.ambient.iter_mut().zip(color) { *acc += c; } @@ -621,6 +671,7 @@ fn collect_scene_inner( 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, 20.0, expr).round() as u32, + sub_height: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelHeight", time, 1.0, expr).round() as u32, top_cap: comp.eval_number(node, "SurfaceCylinderInputs.TopCap", time, 0.0, expr) > 0.5, bottom_cap: comp.eval_number(node, "SurfaceCylinderInputs.BottomCap", time, 0.0, expr) > 0.5, } @@ -781,20 +832,20 @@ fn collect_scene_inner( } #[derive(PartialEq)] -struct ResolvedMaterial { - tex_node: Option, - bump_node: Option, - diffuse_col: [f32; 4], - specular_col: [f32; 3], - specular_intensity: f32, - specular_exponent: f32, - fx: MaterialFx, +pub(super) struct ResolvedMaterial { + pub(super) tex_node: Option, + pub(super) bump_node: Option, + pub(super) diffuse_col: [f32; 4], + pub(super) specular_col: [f32; 3], + pub(super) specular_intensity: f32, + pub(super) specular_exponent: f32, + pub(super) fx: MaterialFx, /// A bare texture operator used as a surface's material renders flat, ignoring lights. - unlit: bool, - receives_shadows: bool, + pub(super) unlit: bool, + pub(super) receives_shadows: bool, /// True when resolved from a shader material node (`MtlBlinn` / `MtlPhong` / `MtlCookTorrance`), /// which owns diffuse/specular rather than inheriting the geometry node's `MtlStdInputs`. - has_material_shader: bool, + pub(super) has_material_shader: bool, } impl Default for ResolvedMaterial { @@ -858,6 +909,10 @@ fn make_mesh_instance( _ => shape, }; let unseen = ovr.unseen_by_cameras.unwrap_or(false); + let mut sfx = mat.fx.sfx; + if ovr.affected_by_lights == Some(false) { + sfx.layer[2] = 0.0; + } MeshInstance { world, shape: ShapeKind::WithMaterialFx { @@ -866,6 +921,7 @@ fn make_mesh_instance( wireframe: ovr.wireframe.unwrap_or(mat.fx.wireframe), cull_back: ovr.cull_back.unwrap_or(false) || unseen, cull_front: ovr.cull_front.unwrap_or(false) || unseen, + sfx, ..mat.fx }, }, @@ -1084,59 +1140,16 @@ fn resolve_material_inner( ..default_mat } } - "SphereMap" => { - let img_in = n - .connected_node("Image") - .or_else(|| n.connected_node("Input")) - .or_else(|| n.connected_node("MaterialInput")) - .and_then(|s| comp.find_node(s)); - let img_node = img_in.and_then(|id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1).tex_node); - let f = |k: &str, fb: &str, d: f64| { - comp.eval_number(n, k, time, comp.eval_number(n, fb, time, d, expr), expr) as f32 - }; - let rot_deg = [ - f("Rotate.X", "Transform3DOp.Rotate.X", 0.0), - f("Rotate.Y", "Transform3DOp.Rotate.Y", 0.0), - f("Rotate.Z", "Transform3DOp.Rotate.Z", 0.0), - ]; - let rot_order = n - .static_str("Rotate.RotOrder") - .or_else(|| n.static_str("Transform3DOp.Rotate.RotOrder")) - .unwrap_or("XYZ"); - // Rotating the environment sphere by R means sampling world directions via R^T. - let r = euler_matrix(rot_deg, rot_order); - let env_rot = [ - r[0], r[4], r[8], - r[1], r[5], r[9], - r[2], r[6], r[10], - ]; - let start_angle = comp.eval_number(n, "StartAngle", time, 0.0, expr) as f32; - let end_angle = comp.eval_number(n, "EndAngle", time, 360.0, expr) as f32; - let map_mode = comp.eval_number(n, "MapMode", time, 0.0, expr).round().clamp(0.0, 1.0) as u32; - let tint = [ - comp.eval_number(n, "Color.Red", time, 1.0, expr) as f32, - comp.eval_number(n, "Color.Green", time, 1.0, expr) as f32, - comp.eval_number(n, "Color.Blue", time, 1.0, expr) as f32, - 1.0, - ]; - ResolvedMaterial { - tex_node: img_node, - diffuse_col: tint, - fx: MaterialFx { - env_mode: 1, - env_map_mode: map_mode, - env_tex_slot: if img_node.is_some() { 1 } else { 0 }, - env_rot, - env_start_angle: start_angle, - env_end_angle: end_angle, - refl_tint: [tint[0], tint[1], tint[2]], - ..default_mat.fx - }, - unlit: true, - has_material_shader: true, - ..default_mat - } - } + "SphereMap" => textures::sphere_map(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), + "CubeMap" => textures::cube_map(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), + "TexGradient" => textures::tex_gradient(comp, n, time, expr), + "FastNoiseTexture3D" => textures::fast_noise(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), + "MtlMerge3D" => materials::merge3d(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), + "MtlStereoMix3D" => materials::stereo_mix(comp, n, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), + "MtlPBRUber" => materials::pbr_uber(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), + "FalloffOperator" => materials::falloff(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), + // Without projectors in the scene there is nothing to catch. + "TexCatcher" => materials::flat([0.0; 4]), "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" | "MtlWard" => { let diff_in = n .connected_node("Diffuse.Color.Material") @@ -1230,66 +1243,16 @@ fn resolve_material_inner( } } "MtlReflect" => { - let bg_in = n.connected_node("BackgroundMaterial").and_then(|s| comp.find_node(s)); - let has_bg = bg_in.is_some(); - let bg_mat = if has_bg { - resolve_material_inner(comp, bg_in, time, expr, visited, depth + 1) - } else { - ResolvedMaterial { - diffuse_col: [0.0, 0.0, 0.0, 0.0], - unlit: true, - ..default_mat - } + let input = |k: &str| n.connected_node(k).and_then(|s| comp.find_node(s)); + let has_bg = input("BackgroundMaterial").is_some(); + let bg_mat = match input("BackgroundMaterial") { + Some(id) => resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1), + None => ResolvedMaterial { diffuse_col: [0.0; 4], unlit: true, ..default_mat }, }; - let refl_in = n - .connected_node("Reflection.Color.Material") - .or_else(|| n.connected_node("ReflectionMaterial")) - .and_then(|s| comp.find_node(s)); - let refl_mat = refl_in.map(|rid| resolve_material_inner(comp, Some(rid), time, expr, visited, depth + 1)); - let bump_in = n.connected_node("Bumpmap.Material").and_then(|s| comp.find_node(s)); - let bump_mat = bump_in.map(|bid| resolve_material_inner(comp, Some(bid), time, expr, visited, depth + 1)); - - let f2 = |k: &str, fb: &str, d: f64| { - comp.eval_number(n, k, time, comp.eval_number(n, fb, time, d, expr), expr) as f32 - }; - let strength_var = comp.eval_number(n, "Reflection.StrengthVariability", time, 1.0, expr).round().clamp(0.0, 1.0) as u32; - let const_str = f2("Reflection.ConstantStrength", "Reflection.ConstantReflection", 1.0); - let glancing = f2("Reflection.GlancingStrength", "GlancingStrength", 0.8); - let face_on = f2("Reflection.FaceOnStrength", "FaceOnStrength", 0.0); - let falloff = f2("Reflection.Falloff", "Falloff", 2.0); - let ior = f2("Refraction.RefractiveIndex.RGB", "RefractionIndex", 1.333).max(0.01); - let refract_tint = [ - comp.eval_number(n, "Refraction.Tint.Red", time, 1.0, expr) as f32, - comp.eval_number(n, "Refraction.Tint.Green", time, 1.0, expr) as f32, - comp.eval_number(n, "Refraction.Tint.Blue", time, 1.0, expr) as f32, - ]; - let base_refl_tint = [ - f2("Reflection.Color.Red", "ReflectionColor.Red", 1.0), - f2("Reflection.Color.Green", "ReflectionColor.Green", 1.0), - f2("Reflection.Color.Blue", "ReflectionColor.Blue", 1.0), - ]; - let (env_node, env_rot, env_map_mode, env_start, env_end, refl_tint) = if let Some(rm) = &refl_mat { - let tint = [ - base_refl_tint[0] * rm.diffuse_col[0], - base_refl_tint[1] * rm.diffuse_col[1], - base_refl_tint[2] * rm.diffuse_col[2], - ]; - if rm.fx.env_mode == 1 { - (rm.tex_node, rm.fx.env_rot, rm.fx.env_map_mode, rm.fx.env_start_angle, rm.fx.env_end_angle, tint) - } else { - (rm.tex_node, MaterialFx::default().env_rot, 0, 0.0, 360.0, tint) - } - } else { - (None, MaterialFx::default().env_rot, 0, 0.0, 360.0, base_refl_tint) - }; - - let bg_has_diffuse_tex = bg_mat.tex_node.is_some() && !bg_mat.fx.bump_only; - let mut tex_node = if bg_has_diffuse_tex { bg_mat.tex_node } else { None }; + let mut tex_node = bg_mat.tex_node.filter(|_| !bg_mat.fx.bump_only); let mut bump_node = bg_mat.bump_node; - let mut fx = bg_mat.fx; - fx.bump_only = false; - - if let Some(bm) = bump_mat { + let mut fx = MaterialFx { bump_only: false, ..bg_mat.fx }; + if let Some(bm) = input("Bumpmap.Material").map(|id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)) { bump_node = bm.bump_node.or(bm.tex_node); 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; @@ -1298,152 +1261,60 @@ fn resolve_material_inner( fx.bump_clamp_z = bm.fx.bump_clamp_z; fx.bump_channel = bm.fx.bump_channel; } - - let env_tex_slot = if let Some(en) = env_node { + let mut mat = ResolvedMaterial { tex_node, bump_node, fx, has_material_shader: true, ..bg_mat }; + // Without a reflection material Fusion renders the background material alone. + let Some(rm) = input("Reflection.Color.Material").map(|id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)) else { + return mat; + }; + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + if let Some(env) = rm.tex_node { if tex_node.is_none() { - tex_node = Some(en); - 1 + tex_node = Some(env); + mat.fx.env_tex_slot = 1; } else { - bump_node = Some(en); - 2 + bump_node = Some(env); + mat.fx.env_tex_slot = 2; } + } + // A SphereMap/CubeMap reflects along directions; a plain image is laid on by mesh UV. + if rm.fx.env_mode == 1 { + mat.fx.env_rot = rm.fx.env_rot; + mat.fx.env_map_mode = rm.fx.env_map_mode; + mat.fx.sfx.env = rm.fx.sfx.env; } else { - 0 - }; - - fx.env_mode = 2; - fx.env_map_mode = env_map_mode; - fx.env_tex_slot = env_tex_slot; - fx.env_rot = env_rot; - fx.env_start_angle = env_start; - fx.env_end_angle = env_end; - fx.refl_strength_var = strength_var; - fx.refl_constant_strength = const_str; - fx.refl_glancing_strength = glancing; - fx.refl_face_on_strength = face_on; - fx.refl_falloff = falloff; - fx.refl_tint = refl_tint; - fx.refl_has_bg = has_bg; - fx.refract_ior = ior; - fx.refract_tint = refract_tint; - - ResolvedMaterial { - tex_node, - bump_node, - diffuse_col: bg_mat.diffuse_col, - specular_col: bg_mat.specular_col, - specular_intensity: bg_mat.specular_intensity, - specular_exponent: bg_mat.specular_exponent, - fx, - unlit: if has_bg { bg_mat.unlit } else { true }, - receives_shadows: bg_mat.receives_shadows, - has_material_shader: true, + mat.fx.env_map_mode = 5; } + mat.fx.env_mode = 2; + mat.fx.refl_strength_var = f("Reflection.StrengthVariability", 1.0).round().clamp(0.0, 1.0) as u32; + mat.fx.refl_constant_strength = f("Reflection.ConstantStrength", 1.0); + mat.fx.refl_glancing_strength = f("Reflection.GlancingStrength", 0.8); + mat.fx.refl_face_on_strength = f("Reflection.FaceOnStrength", 0.0); + mat.fx.refl_falloff = f("Reflection.Falloff", 2.0); + mat.fx.refl_tint = [rm.diffuse_col[0], rm.diffuse_col[1], rm.diffuse_col[2]]; + mat.fx.refl_has_bg = has_bg; + mat.fx.refract_ior = f("Refraction.RefractiveIndex.RGB", 1.333).max(0.01); + mat.fx.refract_tint = ["Red", "Green", "Blue"].map(|c| f(&format!("Refraction.Tint.{c}"), 1.0)); + ResolvedMaterial { tex_node, bump_node, ..mat } } "MtlChanBool" => { - let bg_in = n - .connected_node("BackgroundMaterial") - .or_else(|| n.connected_node("Background")) - .and_then(|s| comp.find_node(s)); - let fg_in = n - .connected_node("ForegroundMaterial") - .or_else(|| n.connected_node("Foreground")) - .and_then(|s| comp.find_node(s)); - let mut bg_mat = if bg_in.is_some() { - resolve_material_inner(comp, bg_in, time, expr, visited, depth + 1) - } else { - ResolvedMaterial { - diffuse_col: [0.0, 0.0, 0.0, 0.0], - unlit: true, - ..default_mat - } - }; - let fg_mat = fg_in.map(|fid| resolve_material_inner(comp, Some(fid), time, expr, visited, depth + 1)); - - let has_native_cb = ["OperandAR", "OperandAG", "OperandAB", "OperandAA", "OperationR", "OperationG", "OperationB", "OperationA", "OperandBR", "OperandBG", "OperandBB", "OperandBA"] - .iter() - .any(|k| n.inputs.contains_key(*k)); - let has_legacy_cb = ["Operation", "ToRed", "ToGreen", "ToBlue", "ToAlpha"] - .iter() - .any(|k| n.inputs.contains_key(*k)); - - let (cb_ops_a, cb_ops, cb_ops_b) = if has_native_cb || !has_legacy_cb { - let g = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr).round().clamp(0.0, 30.0) as u8; - let op = |k: &str| comp.eval_number(n, k, time, 0.0, expr).round().clamp(0.0, 10.0) as u8; - ( - [g("OperandAR", 4.0), g("OperandAG", 5.0), g("OperandAB", 6.0), g("OperandAA", 7.0)], - [op("OperationR"), op("OperationG"), op("OperationB"), op("OperationA")], - [g("OperandBR", 0.0), g("OperandBG", 1.0), g("OperandBB", 2.0), g("OperandBA", 3.0)], - ) - } else { - // Fallback mapping for 2D ChannelBoolean-style keys (Operation + ToRed/Green/Blue/Alpha). - let leg_op = comp.eval_number(n, "Operation", time, 0.0, expr).round() as i32; - let mapped_op: u8 = match leg_op { - 1 => 4, // Add -> A + B - 2 => 5, // Subtract -> A - B - 6 | 3 => 6, // Multiply / And -> A * B - 7 => 7, // Divide -> A / B - 8 => 9, // Maximum -> max(A, B) - 9 => 8, // Minimum -> min(A, B) - 10 => 3, // Negative -> 1 - B - _ => 1, // Copy -> B - }; - let map_ch = |k: &str, bg_idx: u8, def_ch: f64| -> (u8, u8) { - let v = comp.eval_number(n, k, time, def_ch, expr).round() as i32; - match v { - 0..=3 => (mapped_op, v as u8), - 4 => (0, bg_idx), // Do Nothing -> keep A (BG) - 5..=8 => (mapped_op, (v - 1) as u8), // BG RGBA -> 4..=7 - 15 => (mapped_op, 8), // Black - 16 => (mapped_op, 9), // White - _ => (mapped_op, bg_idx), - } - }; - let (or, br) = map_ch("ToRed", 4, 0.0); - let (og, bg_b) = map_ch("ToGreen", 5, 1.0); - let (ob, bb) = map_ch("ToBlue", 6, 2.0); - let (oa, ba) = map_ch("ToAlpha", 7, 3.0); - ([4, 5, 6, 7], [or, og, ob, oa], [br, bg_b, bb, ba]) - }; - - let coord_space = match n.static_str("CoordSpace") { + let mut resolve = |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1); + let black = || materials::flat([0.0, 0.0, 0.0, 1.0]); + let mut mat = materials::material_input(comp, n, "BackgroundMaterial", &mut resolve).unwrap_or_else(black); + let fg = materials::material_input(comp, n, "ForegroundMaterial", &mut resolve).unwrap_or_else(black); + let g = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr).round().clamp(0.0, 30.0) as u8; + let op = |k: &str| comp.eval_number(n, k, time, 0.0, expr).round().clamp(0.0, 10.0) as u8; + mat.fx.cb_enabled = true; + mat.fx.cb_ops_a = [g("OperandAR", 4.0), g("OperandAG", 5.0), g("OperandAB", 6.0), g("OperandAA", 7.0)]; + mat.fx.cb_ops = [op("OperationR"), op("OperationG"), op("OperationB"), op("OperationA")]; + mat.fx.cb_ops_b = [g("OperandBR", 0.0), g("OperandBG", 1.0), g("OperandBB", 2.0), g("OperandBA", 3.0)]; + mat.fx.cb_coord_space = match n.static_str("CoordSpace") { Some("Model") => 0, Some("World") => 1, _ => 2, }; - - let (fg_col, fg_tex_slot) = if let Some(fm) = fg_mat { - let col = [ - fm.diffuse_col[0], - fm.diffuse_col[1], - fm.diffuse_col[2], - fm.diffuse_col[3] * fm.fx.diffuse_color_alpha, - ]; - let slot = if let Some(ftex) = fm.tex_node.filter(|_| !fm.fx.bump_only) { - if bg_mat.bump_node.is_none() && bg_mat.fx.env_tex_slot != 2 { - bg_mat.bump_node = Some(ftex); - bg_mat.fx.bump_wrap = fm.fx.uv_wrap; - 2 - } else { - 0 - } - } else { - 0 - }; - (col, slot) - } else { - ([0.0, 0.0, 0.0, 0.0], 0) - }; - - bg_mat.fx.cb_enabled = true; - bg_mat.fx.cb_ops_a = cb_ops_a; - bg_mat.fx.cb_ops = cb_ops; - bg_mat.fx.cb_ops_b = cb_ops_b; - bg_mat.fx.cb_fg_col = fg_col; - bg_mat.fx.cb_coord_space = coord_space; - bg_mat.fx.cb_fg_tex_slot = fg_tex_slot; - bg_mat.has_material_shader = true; - bg_mat + materials::set_layer(&mut mat, &fg, layer_mode::CHAN_BOOL, 0.0); + mat.has_material_shader = true; + mat } _ => ResolvedMaterial { tex_node: Some(mid), @@ -1630,7 +1501,7 @@ fn target_aim_matrix(eye: [f32; 3], target: [f32; 3], neg_z_forward: bool) -> Op ]) } -fn euler_matrix(rot_deg: [f32; 3], order: &str) -> Mat4 { +pub(super) fn euler_matrix(rot_deg: [f32; 3], order: &str) -> Mat4 { let [rx, ry, rz] = rot_deg.map(f32::to_radians); let axes = [mat4_rot_x(rx), mat4_rot_y(ry), mat4_rot_z(rz)]; order @@ -1647,9 +1518,33 @@ fn trs_matrix(translate: [f32; 3], rot_deg: [f32; 3], order: &str, scale: [f32; mat4_mul(t, mat4_mul(rot, mat4_mul(s, mat4_translate(-pivot[0], -pivot[1], -pivot[2])))) } +#[cfg(test)] +pub(super) fn comp_src(tools: &str) -> String { + format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}") +} + +#[cfg(test)] +pub(super) fn collect_test_scene(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) +} + +/// Resolves node `X` of a comp holding `tools`. +#[cfg(test)] +pub(super) fn resolve_test_material(tools: &str) -> ResolvedMaterial { + let comp = Comp::from_fusion_str(&comp_src(tools)).expect("parse comp"); + let id = comp.find_node("X").expect("node X"); + resolve_material(&comp, Some(id), 0.0, &ExprEngine::new(), &mut Vec::new()) +} + #[cfg(test)] mod tests { use super::*; + use super::collect_test_scene as collect; #[test] fn test_collect_scene_archive_3d_nodes() { @@ -1903,19 +1798,6 @@ mod tests { 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 cameras_carry_names_for_renderer_selection() { let src = comp_src( @@ -2385,7 +2267,6 @@ mod tests { assert_eq!(meshes[0].material_node, Some(env_id)); assert_eq!(fx0.env_mode, 1); assert_eq!(fx0.env_tex_slot, 1); - assert!((fx0.env_start_angle - 30.0).abs() < 1e-4 && (fx0.env_end_angle - 330.0).abs() < 1e-4); // MtlWard let fx1 = meshes[1].shape.split_fx().1; @@ -2411,6 +2292,7 @@ mod tests { assert_eq!(fx3.cb_ops[0], 4); assert_eq!(fx3.cb_ops_b[0], 0); assert_eq!(fx3.cb_coord_space, 1); - assert!((fx3.cb_fg_col[0] - 0.2).abs() < 1e-5 && (fx3.cb_fg_col[2] - 0.6).abs() < 1e-5); + assert_eq!(fx3.sfx.layer, [layer_mode::CHAN_BOOL, 0.0, 1.0, 0.0], "a wired shader foreground is lit"); + assert!((fx3.sfx.layer_col[0] - 0.2).abs() < 1e-5 && (fx3.sfx.layer_col[2] - 0.6).abs() < 1e-5); } } diff --git a/crates/engine/src/scene3d/deform.rs b/crates/engine/src/scene3d/deform.rs index 1934ce7546ed5997148f7797086d4dac1dee1a0e..170a2c4236e1d0aaafe0a6c28f065b8083efe5d2 100644 --- a/crates/engine/src/scene3d/deform.rs +++ b/crates/engine/src/scene3d/deform.rs @@ -118,24 +118,17 @@ fn xform_normal(m: Mat4, n: [f32; 3]) -> [f32; 3] { vec3_norm(out).unwrap_or([0.0, 0.0, 1.0]) } -/// Right-handed orthonormal basis `(u, v, w)` where `w` is the bend axis rotated by `angle_deg`. +/// Right-handed basis `(u, v, w)`: `w` is the bend axis and `u` the direction the ends bend +/// toward (`X -> +Y`, `Y -> +Z`, `Z -> +X`), rotated by `angle_deg` toward `v = w x u`. fn bender_basis(axis: u32, angle_deg: f32) -> ([f32; 3], [f32; 3], [f32; 3]) { let (u0, v0, w) = match axis { 0 => ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]), 2 => ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), - _ => ([1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]), + _ => ([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), }; let (s, c) = angle_deg.to_radians().sin_cos(); - let u = [ - u0[0] * c + v0[0] * s, - u0[1] * c + v0[1] * s, - u0[2] * c + v0[2] * s, - ]; - let v = [ - -u0[0] * s + v0[0] * c, - -u0[1] * s + v0[1] * c, - -u0[2] * s + v0[2] * c, - ]; + let u = [0, 1, 2].map(|i| u0[i] * c + v0[i] * s); + let v = [0, 1, 2].map(|i| -u0[i] * s + v0[i] * c); (u, v, w) } @@ -150,10 +143,9 @@ fn axis_bounds_of(verts: &[Vertex3D], w: [f32; 3]) -> Option<[f32; 2]> { (mn.is_finite() && mx.is_finite()).then_some([mn, mx]) } -/// Applies `Bender3D` deformation to `verts` in-place and recomputes smooth vertex normals. +/// Applies `Bender3D` deformation to `verts` in-place, turning their normals with it. pub fn deform_mesh_vertices( verts: &mut [Vertex3D], - indices: &[u32], params: &Bender3DParams, shared_bounds: Option<[f32; 2]>, ) { @@ -185,159 +177,54 @@ pub fn deform_mesh_vertices( let r_min = min_w + r_min_frac * extent; let r_max = min_w + r_max_frac * extent; let amount = params.amount; - - for vert in verts.iter_mut() { - let pu = vec3_dot(vert.pos, u); - let pv = vec3_dot(vert.pos, v); - let pw = vec3_dot(vert.pos, w); + let k = amount * std::f32::consts::TAU / extent; + // Deformation in bender coordinates `(u, v, w)`; outside the range the clamped end's frame + // carries the rest of the mesh rigidly. + let warp = |[pu, pv, pw]: [f32; 3]| -> [f32; 3] { let wc = pw.clamp(r_min, r_max); let w_ext = pw - wc; let t = (wc - w0) / extent; - - let nu_old = vec3_dot(vert.normal, u); - let nv_old = vec3_dot(vert.normal, v); - let nw_old = vec3_dot(vert.normal, w); - - let (nu, nv, nw, rnu, rnv, rnw) = match params.mode { - BenderMode::Bend => { - // Amount = 1.0 bends the full extent by PI radians (180 degrees). - let k = amount * std::f32::consts::PI / extent; - let theta = k * (wc - w0); - let (st, ct) = theta.sin_cos(); - let (pos_u, pos_w) = if k.abs() > 1e-6 { - let r = 1.0 / k; - ( - r - (r - pu) * ct - w_ext * st, - w0 + (r - pu) * st + w_ext * ct, - ) - } else { - (pu, pw) - }; - // Rotate normal by the local bend angle so face orientation checks stay accurate. - let n_u = nu_old * ct - nw_old * st; - let n_w = nu_old * st + nw_old * ct; - (pos_u, pv, pos_w, n_u, nv_old, n_w) + match params.mode { + // Amount = 1.0 bends the full extent into a closed circle. + BenderMode::Bend if k.abs() > 1e-6 => { + let (st, ct) = (k * (wc - w0)).sin_cos(); + let r = 1.0 / k; + [r - (r - pu) * ct + w_ext * st, pv, w0 + (r - pu) * st + w_ext * ct] } + BenderMode::Bend => [pu, pv, pw], BenderMode::Taper => { let s = (1.0 + amount * 2.0 * t).max(0.0); - (pu * s, pv * s, pw, nu_old, nv_old, nw_old) + [pu * s, pv * s, pw] } BenderMode::Twist => { - let theta = amount * std::f32::consts::TAU * t; - let (st, ct) = theta.sin_cos(); - let pos_u = pu * ct - pv * st; - let pos_v = pu * st + pv * ct; - let n_u = nu_old * ct - nv_old * st; - let n_v = nu_old * st + nv_old * ct; - (pos_u, pos_v, pw, n_u, n_v, nw_old) + let (st, ct) = (amount * std::f32::consts::TAU * t).sin_cos(); + [pu * ct - pv * st, pu * st + pv * ct, pw] } - BenderMode::Shear => { - let pos_u = pu + amount * (wc - w0); - let n_w = nw_old - amount * nu_old; - (pos_u, pv, pw, nu_old, nv_old, n_w) - } - }; - - vert.pos = [ - u[0] * nu + v[0] * nv + w[0] * nw, - u[1] * nu + v[1] * nv + w[1] * nw, - u[2] * nu + v[2] * nv + w[2] * nw, - ]; - let approx_n = [ - u[0] * rnu + v[0] * rnv + w[0] * rnw, - u[1] * rnu + v[1] * rnv + w[1] * rnw, - u[2] * rnu + v[2] * rnv + w[2] * rnw, - ]; - vert.normal = vec3_norm(approx_n).unwrap_or(vert.normal); - } - - recompute_smooth_normals(verts, indices, 60.0); -} - -/// Recomputes smooth vertex normals across welded vertex positions, orienting each triangle -/// consistently with the approximate vertex normals and preserving creases sharper than `crease_deg`. -pub fn recompute_smooth_normals(verts: &mut [Vertex3D], indices: &[u32], crease_deg: f32) { - let tris: Vec<[u32; 3]> = indices - .chunks_exact(3) - .filter_map(|t| { - let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); - (a < verts.len() && b < verts.len() && c < verts.len()).then_some([t[0], t[1], t[2]]) - }) - .collect(); - if tris.is_empty() { - return; - } - - let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64); - let mut face_normals: Vec> = Vec::with_capacity(tris.len()); - let mut face_areas: Vec = Vec::with_capacity(tris.len()); - let mut at_pos: HashMap<[i64; 3], Vec> = HashMap::new(); - - for (ti, t) in tris.iter().enumerate() { - let p = t.map(|i| verts[i as usize].pos); - let raw = vec3_cross(vec3_sub(p[1], p[0]), vec3_sub(p[2], p[0])); - let area = vec3_dot(raw, raw).sqrt(); - if area > 1e-10 { - let mut fn_u = [raw[0] / area, raw[1] / area, raw[2] / area]; - // Match each builder's outward winding using the Jacobian-transformed vertex normals. - let outward = t.iter().fold(0.0_f32, |acc, &i| acc + vec3_dot(verts[i as usize].normal, fn_u)); - if outward < 0.0 { - fn_u = [-fn_u[0], -fn_u[1], -fn_u[2]]; - } - face_normals.push(Some(fn_u)); - face_areas.push(area); - for &i in t { - at_pos.entry(key(verts[i as usize].pos)).or_default().push(ti); - } - } else { - face_normals.push(None); - face_areas.push(0.0); - } - } - - let cos_limit = crease_deg.to_radians().cos() - 1e-4; - let mut new_normals: Vec> = vec![None; verts.len()]; - for (ti, t) in tris.iter().enumerate() { - let Some(own_n) = face_normals[ti] else { - continue; - }; - for &vi in t { - let v_idx = vi as usize; - let k = key(verts[v_idx].pos); - let mut sum = [0.0_f32; 3]; - if let Some(group) = at_pos.get(&k) { - for &fi in group { - if let Some(fn_u) = face_normals[fi] { - if vec3_dot(fn_u, own_n) >= cos_limit { - let w = face_areas[fi]; - sum[0] += fn_u[0] * w; - sum[1] += fn_u[1] * w; - sum[2] += fn_u[2] * w; - } - } - } - } - let smoothed = vec3_norm(sum).unwrap_or(own_n); - if let Some(prev) = new_normals[v_idx] { - new_normals[v_idx] = vec3_norm([ - prev[0] + smoothed[0], - prev[1] + smoothed[1], - prev[2] + smoothed[2], - ]) - .or(Some(smoothed)); - } else { - new_normals[v_idx] = Some(smoothed); - } - } - } - for (v, n_opt) in verts.iter_mut().zip(new_normals) { - if let Some(n) = n_opt { - v.normal = n; + BenderMode::Shear => [pu + amount * (wc - w0), pv, pw], } + }; + let to_world = |[a, b, c]: [f32; 3]| [0, 1, 2].map(|i| u[i] * a + v[i] * b + w[i] * c); + let eps = extent * 1e-4; + for vert in verts.iter_mut() { + let p = [vec3_dot(vert.pos, u), vec3_dot(vert.pos, v), vec3_dot(vert.pos, w)]; + let n = [vec3_dot(vert.normal, u), vec3_dot(vert.normal, v), vec3_dot(vert.normal, w)]; + // Fusion turns normals with the warp's local rotation and ignores its stretch: the + // cofactor of the Jacobian (central differences) with unit columns. + let [ja, jb, jc] = [0, 1, 2].map(|axis| { + let (mut lo, mut hi) = (p, p); + lo[axis] -= eps; + hi[axis] += eps; + vec3_norm(vec3_sub(warp(hi), warp(lo))).unwrap_or([0.0; 3]) + }); + let cof = [vec3_cross(jb, jc), vec3_cross(jc, ja), vec3_cross(ja, jb)]; + let n_def = [0, 1, 2].map(|i| cof[0][i] * n[0] + cof[1][i] * n[1] + cof[2][i] * n[2]); + vert.pos = to_world(warp(p)); + vert.normal = vec3_norm(to_world(n_def)).unwrap_or(vert.normal); } } -/// Applies `Bender3D` to a slice of collected child meshes (either individually or as a group). +/// Applies `Bender3D` in the bender's own space to collected child meshes, each within its own +/// bounds or, with `group`, within their shared bounds. pub fn apply_bender_to_meshes( meshes: &mut [MeshInstance], bender_world: Mat4, @@ -347,57 +234,38 @@ pub fn apply_bender_to_meshes( if meshes.is_empty() || !params.amount.is_finite() || params.amount.abs() < 1e-6 { return; } - - if params.group { - let inv_bender = mat4_inverse(bender_world); - let angle_deg = if params.angle_deg.is_finite() { params.angle_deg } else { 0.0 }; - let (_, _, w_axis) = bender_basis(params.axis, angle_deg); - let mut baked: Vec<(Vec, Vec)> = Vec::with_capacity(meshes.len()); - let mut g_min = f32::INFINITY; - let mut g_max = f32::NEG_INFINITY; - - for m in meshes.iter() { + let inv_bender = mat4_inverse(bender_world); + let angle_deg = if params.angle_deg.is_finite() { params.angle_deg } else { 0.0 }; + let (_, _, w_axis) = bender_basis(params.axis, angle_deg); + let baked: Vec<(Vec, Vec)> = meshes + .iter() + .map(|m| { let rel = mat4_mul(inv_bender, m.world); - let aspect = image_plane_aspect(m); - let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), aspect); + let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), image_plane_aspect(m)); for vert in &mut verts { vert.pos = xform_point(rel, vert.pos); vert.normal = xform_normal(rel, vert.normal); - let p = vec3_dot(vert.pos, w_axis); - g_min = g_min.min(p); - g_max = g_max.max(p); } - baked.push((verts, idx)); - } - let shared = (g_min.is_finite() && g_max.is_finite()).then_some([g_min, g_max]); - for (m, (mut verts, idx)) in meshes.iter_mut().zip(baked) { - if idx.is_empty() { - continue; - } - deform_mesh_vertices(&mut verts, &idx, params, shared); - let soup = triangle_soup((verts, idx)); - let (_, fx) = m.shape.split_fx(); - m.shape = ShapeKind::WithMaterialFx { - inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))), - fx, - }; - m.world = bender_world; - } - } else { - for m in meshes.iter_mut() { - let aspect = image_plane_aspect(m); - let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), aspect); - if idx.is_empty() { - continue; - } - deform_mesh_vertices(&mut verts, &idx, params, None); - let soup = triangle_soup((verts, idx)); - let (_, fx) = m.shape.split_fx(); - m.shape = ShapeKind::WithMaterialFx { - inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))), - fx, - }; + (verts, idx) + }) + .collect(); + let shared = params + .group + .then(|| { + baked.iter().filter_map(|(v, _)| axis_bounds_of(v, w_axis)).reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])]) + }) + .flatten(); + for (m, (mut verts, idx)) in meshes.iter_mut().zip(baked) { + if idx.is_empty() { + continue; } + deform_mesh_vertices(&mut verts, params, shared); + let (_, fx) = m.shape.split_fx(); + m.shape = ShapeKind::WithMaterialFx { + inner: Box::new(ShapeKind::CustomMesh(Arc::new(triangle_soup((verts, idx))))), + fx, + }; + m.world = bender_world; } } @@ -673,28 +541,28 @@ mod tests { } #[test] - fn bender_bend_curves_plane_and_updates_normals() { + fn bender_bend_follows_fusion_axes_and_turns_normals() { let shape = ShapeKind::Plane { width: 1.0, height: 2.0, sub_w: 4, sub_h: 8 }; - let (mut verts, idx) = build_shape_mesh(&shape, 1.0); - let params = Bender3DParams { - mode: BenderMode::Bend, - amount: 1.0, - axis: 1, // Y axis - angle_deg: 0.0, - center: 0.5, - range_min: 0.0, - range_max: 1.0, - group: false, + let bend = |angle_deg: f32| { + let (mut verts, _) = build_shape_mesh(&shape, 1.0); + let params = Bender3DParams { mode: BenderMode::Bend, amount: 0.5, axis: 1, angle_deg, center: 0.5, range_min: 0.0, range_max: 1.0, group: false }; + deform_mesh_vertices(&mut verts, ¶ms, None); + verts }; - deform_mesh_vertices(&mut verts, &idx, ¶ms, None); - // Plane was originally flat at z=0 with normal +Z; bending around Y along X curls X into a circle - // and tilts top/bottom vertices in X while keeping finite unit normals. - let top_x = verts.iter().filter(|v| v.uv[1] < 0.01).map(|v| v.pos[0]).fold(0.0_f32, |a, b| a + b) / 5.0; - assert!(top_x > 0.2, "top edge should bend toward +X, got {top_x}"); - assert!(verts.iter().all(|v| { - let l = vec3_dot(v.normal, v.normal).sqrt(); - l.is_finite() && (l - 1.0).abs() < 1e-3 - })); + let mean = |verts: &[Vertex3D], top: bool, axis: usize| { + let edge: Vec = verts.iter().filter(|v| (v.uv[1] < 0.01) == top && (v.uv[1] > 0.99) != top).map(|v| v.pos[axis]).collect(); + edge.iter().sum::() / edge.len() as f32 + }; + // Amount 0.5 bends the height into a half circle of radius 2 / pi opening toward +Z. + let verts = bend(0.0); + let r = 2.0 / std::f32::consts::PI; + for (top, y) in [(true, r), (false, -r)] { + assert!((mean(&verts, top, 2) - r).abs() < 1e-3 && (mean(&verts, top, 1) - y).abs() < 1e-3); + } + let top_n = verts.iter().find(|v| v.uv[1] < 0.01).unwrap().normal; + assert!(top_n[1] < -0.99, "the top end's +Z normal turns toward the bend centre: {top_n:?}"); + // Angle 90 turns the bend toward +X. + assert!(mean(&bend(90.0), true, 0) > 0.6); } #[test] @@ -702,8 +570,8 @@ mod tests { let shape = ShapeKind::Plane { width: 2.0, height: 2.0, sub_w: 4, sub_h: 4 }; // Taper: top (+Y) expands, bottom (-Y) shrinks. - let (mut v_taper, idx) = build_shape_mesh(&shape, 1.0); - deform_mesh_vertices(&mut v_taper, &idx, &Bender3DParams { + let (mut v_taper, _) = build_shape_mesh(&shape, 1.0); + deform_mesh_vertices(&mut v_taper, &Bender3DParams { mode: BenderMode::Taper, amount: 0.5, axis: 1, @@ -715,8 +583,8 @@ mod tests { assert!((max_x_top - 1.5).abs() < 1e-4 && (max_x_bot - 0.5).abs() < 1e-4, "top={max_x_top} bot={max_x_bot}"); // Twist: rotates corners out of z=0 plane. - let (mut v_twist, idx) = build_shape_mesh(&shape, 1.0); - deform_mesh_vertices(&mut v_twist, &idx, &Bender3DParams { + let (mut v_twist, _) = build_shape_mesh(&shape, 1.0); + deform_mesh_vertices(&mut v_twist, &Bender3DParams { mode: BenderMode::Twist, amount: 0.5, axis: 1, @@ -727,8 +595,8 @@ mod tests { assert!(max_z > 0.5, "twist should rotate vertices out of XY plane, max_z={max_z}"); // Shear with RangeMin=0.5 leaves bottom half unsheared (all at constant offset for wc=0) and shears top half. - let (mut v_shear, idx) = build_shape_mesh(&shape, 1.0); - deform_mesh_vertices(&mut v_shear, &idx, &Bender3DParams { + let (mut v_shear, _) = build_shape_mesh(&shape, 1.0); + deform_mesh_vertices(&mut v_shear, &Bender3DParams { mode: BenderMode::Shear, amount: 1.0, axis: 1, @@ -737,8 +605,9 @@ mod tests { range_max: 1.0, ..Default::default() }, None); - let top_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] < 0.01).unwrap().pos[0]; - let bot_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] > 0.99).unwrap().pos[0]; + // Bending/shearing along the Y axis moves vertices toward +Z. + let top_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] < 0.01).unwrap().pos[2]; + let bot_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] > 0.99).unwrap().pos[2]; assert!((top_shift - 1.0).abs() < 1e-4, "top center should shear by +1.0, got {top_shift}"); assert!(bot_shift.abs() < 1e-4, "bottom below RangeMin should stay at 0, got {bot_shift}"); } diff --git a/crates/engine/src/scene3d/fx.rs b/crates/engine/src/scene3d/fx.rs new file mode 100644 index 0000000000000000000000000000000000000000..459047f44e535524ae504406e00d303438204bdf --- /dev/null +++ b/crates/engine/src/scene3d/fx.rs @@ -0,0 +1,126 @@ +//! Surface shading beyond the classic material: procedural textures, a secondary material layer, +//! `MtlPBRUber`, fog and environment coordinate spaces. `SurfaceFx` is copied verbatim into the +//! mesh uniform, so its layout mirrors `struct SurfaceFx` in `surface_fx.wgsl`. + +use bytemuck::{Pod, Zeroable}; +use model::Gradient; + +/// Entries in the gradient lookup table shared by `TexGradient` and `FalloffOperator`. +pub(super) const LUT_SIZE: usize = 16; + +/// Procedural colour source replacing the bound texture (`proc_a.x`). +pub(super) mod proc_kind { + pub const GRADIENT: f32 = 1.0; + pub const NOISE: f32 = 2.0; + pub const FALLOFF_GRADIENT: f32 = 3.0; +} + +/// How the secondary material in `layer` combines with the base surface (`layer.x`). +pub(super) mod layer_mode { + /// `MtlChanBool` foreground operands. + pub const CHAN_BOOL: f32 = 1.0; + /// `MtlMerge3D`: foreground over background scaled by `layer.y` (Blend). + pub const MERGE: f32 = 2.0; + /// `FalloffOperator`: base is face-on, layer is glancing, mixed by `1 - (N.V)^layer.y`. + pub const FALLOFF: f32 = 3.0; +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)] +pub struct SurfaceFx { + /// `[kind, ..]`: gradient `[1, type, scale, offset]`, noise `[2, detail, scale, seethe]`, + /// falloff gradient `[3, falloff, 0, 0]`. + pub proc_a: [f32; 4], + /// Gradient `[repeat, 0, 0, 0]`; noise `[contrast, brightness, inverted, discontinuous]`. + pub proc_b: [f32; 4], + /// `[mode, amount, lit, tex_slot (2 = bump_tex)]`. + pub layer: [f32; 4], + /// Layer diffuse colour (straight RGB, alpha). + pub layer_col: [f32; 4], + /// Layer specular colour and exponent. + pub layer_spec: [f32; 4], + /// `[specular_intensity, spec_model, 0, 0]`. + pub layer_mtl: [f32; 4], + /// `MtlPBRUber` `[metalness, roughness, ior, specular]`. + pub pbr: [f32; 4], + /// `MtlPBRUber` specular colour and `Base.Base` weight. + pub pbr_spec: [f32; 4], + /// `MtlPBRUber` `[coat, coat_roughness, coat_ior, sheen]`. + pub pbr_layers: [f32; 4], + /// `MtlPBRUber` sheen colour and roughness. + pub sheen: [f32; 4], + /// Emitted colour added after lighting. + pub emission: [f32; 4], + /// `Fog3D` `[type (1 linear, 2 exp, 3 exp2), near, far, density]`. + pub fog: [f32; 4], + /// Fog colour and `Radial`. + pub fog_col: [f32; 4], + /// `[coord_space (0 world, 1 model, 2 camera), 0, 0, 0]` for environment lookups. + pub env: [f32; 4], + /// Premultiplied gradient samples at `i / (LUT_SIZE - 1)`. + pub lut: [[f32; 4]; LUT_SIZE], +} + +/// Premultiplied lookup table of `gradient`, or of `fallback` stops when the input is absent. +pub(super) fn gradient_lut(gradient: Option, fallback: [[f32; 4]; 2]) -> [[f32; 4]; LUT_SIZE] { + std::array::from_fn(|i| { + let t = i as f64 / (LUT_SIZE - 1) as f64; + let c = match &gradient { + Some(g) => g.sample(t), + None => std::array::from_fn(|k| fallback[0][k] + (fallback[1][k] - fallback[0][k]) * t as f32), + }; + [c[0] * c[3], c[1] * c[3], c[2] * c[3], c[3]] + }) +} + +/// Fusion's simplex lattice, shared with the 2D `FastNoise` generator. +pub(super) fn simplex_wgsl() -> &'static str { + const SRC: &str = include_str!("../shaders/keyers_gen.wgsl"); + let start = SRC.find("const PERM: array").expect("keyers_gen.wgsl defines PERM"); + let end = SRC[start..].find("@compute").expect("keyers_gen.wgsl has an entry point after the lattice"); + &SRC[start..start + end] +} + +pub(super) const SURFACE_FX_WGSL: &str = include_str!("surface_fx.wgsl"); + +#[cfg(test)] +mod tests { + use super::*; + use model::GradientStop; + + #[test] + fn surface_fx_matches_wgsl_layout() { + let wgsl_vec4s = SURFACE_FX_WGSL + .split("struct SurfaceFx {") + .nth(1) + .and_then(|s| s.split("};").next()) + .expect("SurfaceFx struct") + .lines() + .filter(|l| l.trim_end().ends_with(": vec4,")) + .count(); + assert_eq!(wgsl_vec4s, 14, "scalar vec4 fields"); + assert_eq!(std::mem::size_of::(), (14 + LUT_SIZE) * 16); + assert!(SURFACE_FX_WGSL.contains(&format!("lut: array, {LUT_SIZE}>"))); + } + + #[test] + fn simplex_slice_holds_the_lattice_only() { + let s = simplex_wgsl(); + assert!(s.contains("fn simplex3d(") && s.contains("const SIMPLEX_GAIN")); + assert!(!s.contains("@compute") && !s.contains("var")); + } + + #[test] + fn gradient_lut_premultiplies_and_falls_back() { + let lut = gradient_lut(None, [[1.0; 4], [0.0, 0.0, 0.0, 1.0]]); + assert_eq!(lut[0], [1.0; 4]); + assert_eq!(lut[LUT_SIZE - 1], [0.0, 0.0, 0.0, 1.0]); + let g = Gradient { + stops: vec![ + GradientStop { pos: 0.0, rgba: [1.0, 0.0, 0.0, 0.5] }, + GradientStop { pos: 1.0, rgba: [0.0, 1.0, 0.0, 0.5] }, + ], + }; + assert_eq!(gradient_lut(Some(g), [[0.0; 4]; 2])[0], [0.5, 0.0, 0.0, 0.5]); + } +} diff --git a/crates/engine/src/scene3d/materials.rs b/crates/engine/src/scene3d/materials.rs new file mode 100644 index 0000000000000000000000000000000000000000..55284f59f01e0a2c29e050d5ae7eeeebcbfc47f3 --- /dev/null +++ b/crates/engine/src/scene3d/materials.rs @@ -0,0 +1,225 @@ +//! Material operators layered on `ResolvedMaterial`: `MtlMerge3D`, `MtlPBRUber`, +//! `MtlStereoMix3D`, `FalloffOperator`, `TexCatcher`, and the secondary-layer plumbing shared with +//! `MtlChanBool`. + +use super::collect::ResolvedMaterial; +use super::fx::{gradient_lut, layer_mode, proc_kind, SurfaceFx}; +use super::{MaterialFx, SpecModel}; +use model::{Comp, ExprEngine, Node, NodeId}; + +pub(super) type Resolve<'a> = dyn FnMut(NodeId) -> ResolvedMaterial + 'a; + +/// A material operator's own input: a bare image there renders flat, as Fusion shows it. +pub(super) fn material_input(comp: &Comp, n: &Node, input: &str, resolve: &mut Resolve) -> Option { + let id = n.connected_node(input).and_then(|s| comp.find_node(s))?; + let mut m = resolve(id); + m.unlit |= !m.has_material_shader; + Some(m) +} + +/// Flat colour standing in for an unwired material input. +pub(super) fn flat(rgba: [f32; 4]) -> ResolvedMaterial { + ResolvedMaterial { diffuse_col: rgba, unlit: true, has_material_shader: true, ..ResolvedMaterial::default() } +} + +/// Stores `layer` as the secondary material of `base`; its texture takes the bump slot when free. +pub(super) fn set_layer(base: &mut ResolvedMaterial, layer: &ResolvedMaterial, mode: f32, amount: f32) { + let tex_slot = match layer.tex_node.filter(|_| !layer.fx.bump_only) { + Some(tex) if base.bump_node.is_none() && base.fx.env_tex_slot != 2 => { + base.bump_node = Some(tex); + base.fx.bump_wrap = layer.fx.uv_wrap; + 2.0 + } + _ => 0.0, + }; + let [r, g, b, a] = layer.diffuse_col; + let [sr, sg, sb] = layer.specular_col; + let sfx = &mut base.fx.sfx; + sfx.layer = [mode, amount, if layer.unlit { 0.0 } else { 1.0 }, tex_slot]; + sfx.layer_col = [r, g, b, a * layer.fx.diffuse_color_alpha]; + sfx.layer_spec = [sr, sg, sb, layer.specular_exponent]; + sfx.layer_mtl = [layer.specular_intensity, layer.fx.spec_model as u32 as f32, 0.0, 0.0]; +} + +/// `MtlMerge3D`: the foreground over the background, scaled by `Blend`. Mono renders ignore +/// `MergeType`. +pub(super) fn merge3d(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { + let mut mat = material_input(comp, n, "BackgroundMaterial", resolve).unwrap_or_else(|| flat([0.0; 4])); + let fg = material_input(comp, n, "ForegroundMaterial", resolve).unwrap_or_else(|| flat([0.0; 4])); + set_layer(&mut mat, &fg, layer_mode::MERGE, comp.eval_number(n, "Blend", time, 1.0, expr) as f32); + mat.has_material_shader = true; + mat +} + +/// `MtlStereoMix3D`: mono renders show the left eye whatever `Swap` says. +pub(super) fn stereo_mix(comp: &Comp, n: &Node, resolve: &mut Resolve) -> ResolvedMaterial { + material_input(comp, n, "LeftMaterial", resolve).unwrap_or_else(|| flat([0.0; 4])) +} + +pub(super) fn pbr_uber(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + let rgb = |p: &str, d: f64| ["Red", "Green", "Blue"].map(|c| f(&format!("{p}.{c}"), d)); + let base = rgb("Base.Color", 1.0); + let opacity = rgb("Opacity.Opacity", 1.0); + let spec = rgb("Specular.Color", 1.0); + let sheen = rgb("Sheen.Color", 1.0); + let emission = rgb("Emission.Color", 1.0).map(|c| c * f("Emission.Emission", 0.0)); + let tex = n.connected_node("Base.Color.ColorMtl").and_then(|s| comp.find_node(s)).map(&mut *resolve).unwrap_or_default(); + ResolvedMaterial { + tex_node: tex.tex_node, + diffuse_col: [base[0], base[1], base[2], opacity.iter().sum::() / 3.0], + fx: MaterialFx { + spec_model: SpecModel::PbrUber, + sfx: SurfaceFx { + pbr: [f("Metalness.Metalness", 0.0), f("Specular.Roughness", 0.5), f("Specular.IOR", 1.5), f("Specular.Specular", 1.0)], + pbr_spec: [spec[0], spec[1], spec[2], f("Base.Base", 1.0)], + pbr_layers: [f("Coat.Coat", 0.0), f("Coat.Roughness", 0.0), f("Coat.IOR", 1.5), f("Sheen.Sheen", 0.0)], + sheen: [sheen[0], sheen[1], sheen[2], f("Sheen.Roughness", 0.3)], + emission: [emission[0], emission[1], emission[2], 0.0], + ..SurfaceFx::default() + }, + ..tex.fx + }, + unlit: f("ReceivesLighting", 1.0) < 0.5, + receives_shadows: f("ReceivesShadows", 1.0) > 0.5, + has_material_shader: true, + ..ResolvedMaterial::default() + } +} + +/// `FalloffOperator`: `t = 1 - (N.V)^Falloff` blends face-on toward glancing, either through the +/// gradient or between the two tones (each a colour or a material, scaled by its opacity). +pub(super) fn falloff(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + let power = f("Falloff", 2.0); + if n.static_str("ColorVariation") == Some("Gradient") { + let mut mat = flat([1.0; 4]); + mat.fx.sfx.proc_a = [proc_kind::FALLOFF_GRADIENT, power, 0.0, 0.0]; + mat.fx.sfx.lut = gradient_lut(comp.eval_gradient(n, "Gradient", time), [[1.0; 4], [0.0, 0.0, 0.0, 1.0]]); + return mat; + } + let mut tone = |p: &str, opacity: f64| { + let mut m = material_input(comp, n, &format!("{p}Material"), resolve) + .unwrap_or_else(|| flat(["Red", "Green", "Blue", "Alpha"].map(|c| f(&format!("{p}.{c}"), 1.0)))); + m.diffuse_col[3] *= f(&format!("{p}.Opacity"), opacity); + m + }; + let mut mat = tone("FaceOn", 0.2); + let glancing = tone("Glancing", 1.0); + set_layer(&mut mat, &glancing, layer_mode::FALLOFF, power); + mat.has_material_shader = true; + mat +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scene3d::collect::resolve_test_material as resolve_in; + + #[test] + fn merge3d_layers_foreground_over_background() { + let mat = resolve_in( + "BG = MtlBlinn { Inputs = { [\"Diffuse.Color.Red\"] = Input { Value = 0.5, }, }, }, + FG = MtlPhong { Inputs = { [\"Specular.Exponent\"] = Input { Value = 12, }, }, }, + X = MtlMerge3D { Inputs = { Blend = Input { Value = 0.25, }, + BackgroundMaterial = Input { SourceOp = \"BG\", Source = \"MaterialOutput\", }, + ForegroundMaterial = Input { SourceOp = \"FG\", Source = \"MaterialOutput\", }, }, },", + ); + assert_eq!(mat.diffuse_col[0], 0.5); + assert!(!mat.unlit); + let sfx = mat.fx.sfx; + assert_eq!(sfx.layer, [layer_mode::MERGE, 0.25, 1.0, 0.0]); + assert_eq!(sfx.layer_spec[3], 12.0); + assert_eq!(sfx.layer_mtl[1], SpecModel::Phong as u32 as f32); + } + + #[test] + fn merge3d_unwired_is_transparent_and_bare_images_are_flat() { + let empty = resolve_in("X = MtlMerge3D { },"); + assert_eq!(empty.diffuse_col, [0.0; 4]); + assert_eq!(empty.fx.sfx.layer_col, [0.0; 4]); + let img = resolve_in( + "Img = Background { }, + X = MtlMerge3D { Inputs = { ForegroundMaterial = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", + ); + assert_eq!(img.bump_node.map(|_| ()), Some(()), "foreground image takes the bump slot"); + assert_eq!(img.fx.sfx.layer[2..], [0.0, 2.0]); + } + + #[test] + fn stereo_mix_always_uses_left() { + let mat = resolve_in( + "L = MtlBlinn { Inputs = { [\"Diffuse.Color.Green\"] = Input { Value = 0.3, }, }, }, + R = MtlBlinn { }, + X = MtlStereoMix3D { Inputs = { Swap = Input { Value = 1, }, + LeftMaterial = Input { SourceOp = \"L\", Source = \"MaterialOutput\", }, + RightMaterial = Input { SourceOp = \"R\", Source = \"MaterialOutput\", }, }, },", + ); + assert_eq!(mat.diffuse_col[1], 0.3); + } + + #[test] + fn pbr_uber_reads_metal_roughness_and_emission() { + let mat = resolve_in( + "X = MtlPBRUber { Inputs = { + [\"Metalness.Metalness\"] = Input { Value = 1, }, + [\"Specular.Roughness\"] = Input { Value = 0.2, }, + [\"Emission.Emission\"] = Input { Value = 0.5, }, + [\"Emission.Color.Red\"] = Input { Value = 0, }, + [\"Opacity.Opacity.Green\"] = Input { Value = 0.4, }, }, },", + ); + assert_eq!(mat.fx.spec_model, SpecModel::PbrUber); + assert_eq!(mat.fx.sfx.pbr, [1.0, 0.2, 1.5, 1.0]); + assert_eq!(mat.fx.sfx.emission, [0.0, 0.5, 0.5, 0.0]); + assert!((mat.diffuse_col[3] - 0.8).abs() < 1e-6); + } + + #[test] + fn falloff_two_tone_and_gradient() { + let two = resolve_in("X = FalloffOperator { Inputs = { [\"Glancing.Red\"] = Input { Value = 0, }, Falloff = Input { Value = 3, }, }, },"); + assert_eq!(two.diffuse_col, [1.0, 1.0, 1.0, 0.2]); + assert!(two.unlit); + assert_eq!(two.fx.sfx.layer, [layer_mode::FALLOFF, 3.0, 0.0, 0.0]); + assert_eq!(two.fx.sfx.layer_col, [0.0, 1.0, 1.0, 1.0]); + let grad = resolve_in("X = FalloffOperator { Inputs = { ColorVariation = Input { Value = FuID { \"Gradient\" }, }, }, },"); + assert_eq!(grad.fx.sfx.proc_a, [proc_kind::FALLOFF_GRADIENT, 2.0, 0.0, 0.0]); + assert_eq!(grad.fx.sfx.lut[0], [1.0; 4]); + assert_eq!(grad.fx.sfx.layer, [0.0; 4]); + } + + #[test] + fn reflect_without_reflection_is_its_background_and_images_lay_on_by_uv() { + let bg = "BG = MtlBlinn { Inputs = { [\"Diffuse.Color.Red\"] = Input { Value = 0.3, }, }, }, Img = Background { },"; + let plain = resolve_in(&format!("{bg} X = MtlReflect {{ Inputs = {{ BackgroundMaterial = Input {{ SourceOp = \"BG\", Source = \"MaterialOutput\", }}, }}, }},")); + assert_eq!((plain.fx.env_mode, plain.diffuse_col[0]), (0, 0.3)); + let img = resolve_in(&format!( + "{bg} X = MtlReflect {{ Inputs = {{ BackgroundMaterial = Input {{ SourceOp = \"BG\", Source = \"MaterialOutput\", }}, + [\"Reflection.Color.Material\"] = Input {{ SourceOp = \"Img\", Source = \"Output\", }}, }}, }}," + )); + assert_eq!((img.fx.env_mode, img.fx.env_map_mode, img.fx.env_tex_slot), (2, 5, 1)); + } + + #[test] + fn chan_bool_unwired_inputs_are_black_and_bare_images_unlit() { + let empty = resolve_in("X = MtlChanBool { },"); + assert_eq!(empty.diffuse_col, [0.0, 0.0, 0.0, 1.0]); + assert_eq!(empty.fx.sfx.layer_col, [0.0, 0.0, 0.0, 1.0]); + assert!(empty.fx.cb_enabled); + let img = resolve_in("Img = Background { }, X = MtlChanBool { Inputs = { BackgroundMaterial = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },"); + assert!(img.unlit && img.tex_node.is_some()); + } + + #[test] + fn pbr_uber_reads_coat_and_sheen() { + let mat = resolve_in("X = MtlPBRUber { Inputs = { [\"Coat.Coat\"] = Input { Value = 1, }, [\"Sheen.Sheen\"] = Input { Value = 0.5, }, [\"Sheen.Color.Blue\"] = Input { Value = 0, }, }, },"); + assert_eq!(mat.fx.sfx.pbr_layers, [1.0, 0.0, 1.5, 0.5]); + assert_eq!(mat.fx.sfx.sheen, [1.0, 1.0, 0.0, 0.3]); + } + + #[test] + fn tex_catcher_without_projectors_is_transparent() { + let mat = resolve_in("X = TexCatcher { },"); + assert_eq!(mat.diffuse_col[3], 0.0); + assert!(mat.has_material_shader); + } +} diff --git a/crates/engine/src/scene3d/mesh.rs b/crates/engine/src/scene3d/mesh.rs index fada7a3e7310beee110b801c359dff7e3cf4485f..27682477d677c16caed3a1c53790804a960f2711 100644 --- a/crates/engine/src/scene3d/mesh.rs +++ b/crates/engine/src/scene3d/mesh.rs @@ -19,9 +19,10 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base, [*top_cap, *bottom_cap]), + } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, [*sub_base, *sub_height], [*top_cap, *bottom_cap]), ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces), ShapeKind::CustomMesh(verts) => { let v = verts.as_ref().clone(); @@ -150,39 +151,33 @@ fn build_cylinder( height: f32, start_sweep_deg: f32, end_sweep_deg: f32, - sub_base: u32, + [sub_base, sub_height]: [u32; 2], caps: [bool; 2], ) -> (Vec, Vec) { let seg_u = sub_base.clamp(16, 96); + let seg_v = sub_height.clamp(1, 256); let half_h = height * 0.5; let a0 = start_sweep_deg.to_radians(); let a1 = end_sweep_deg.to_radians(); - let mut verts = Vec::with_capacity(((seg_u + 1) * 2) as usize); - let mut idx = Vec::with_capacity((seg_u * 6) as usize); + let rows = seg_v + 1; + let mut verts = Vec::with_capacity(((seg_u + 1) * rows) as usize); + let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize); for iu in 0..=seg_u { let u = iu as f32 / seg_u as f32; // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc let theta = a0 + (a1 - a0) * u; - let (st, ct) = theta.sin_cos(); - let nx = ct; - let nz = st; - verts.push(Vertex3D { - pos: [nx * radius, half_h, nz * radius], - normal: [nx, 0.0, nz], - uv: [1.0 - u, 0.0], - }); - verts.push(Vertex3D { - pos: [nx * radius, -half_h, nz * radius], - normal: [nx, 0.0, nz], - uv: [1.0 - u, 1.0], - }); + let (nz, nx) = theta.sin_cos(); + for iv in 0..rows { + let v = iv as f32 / seg_v as f32; + verts.push(Vertex3D { pos: [nx * radius, half_h - height * v, nz * radius], normal: [nx, 0.0, nz], uv: [1.0 - u, v] }); + } } for iu in 0..seg_u { - let a = iu * 2; - let b = a + 1; - let c = a + 3; - let d = a + 2; - idx.extend_from_slice(&[a, b, d, b, c, d]); + for iv in 0..seg_v { + let a = iu * rows + iv; + let (b, d) = (a + 1, a + rows); + idx.extend_from_slice(&[a, b, d, b, d + 1, d]); + } } for (cap, (y, ny)) in caps.into_iter().zip([(half_h, 1.0), (-half_h, -1.0)]) { if !cap { @@ -514,6 +509,18 @@ mod tests { assert_eq!(capped.len(), open.len() + 1 + 9); } + #[test] + fn cylinder_height_subdivision_adds_rings() { + let rings = |sub_height| { + let (v, _) = build_cylinder(1.0, 2.0, 0.0, 360.0, [8, sub_height], [false, false]); + let mut ys: Vec = v.iter().map(|p| (p.pos[1] * 1000.0).round() as i32).collect(); + ys.sort_unstable(); + ys.dedup(); + ys.len() + }; + assert_eq!((rings(1), rings(4)), (2, 5)); + } + #[test] fn torus_tube_stays_within_radius_plus_section() { let (verts, _) = build_torus(1.0, 0.5, [0.0, 360.0], 16, 8); diff --git a/crates/engine/src/scene3d/mesh.wgsl b/crates/engine/src/scene3d/mesh.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..0639a5d0cdf5a3dc6b98f76800a984c583b32c3c --- /dev/null +++ b/crates/engine/src/scene3d/mesh.wgsl @@ -0,0 +1,706 @@ +struct MeshUniform { + mvp: mat4x4, + model: mat4x4, + view: mat4x4, + dod: vec4, + flags: vec4, + diffuse_col: vec4, + specular_col: vec4, + ambient: vec4, + dir_to_light: array, MAX_DIR_LIGHTS>, + dir_color: array, MAX_DIR_LIGHTS>, + cam_pos: vec4, + light_counts: vec4, + uv_xform: vec4, + uv_off_wrap: vec4, + mat_fx: vec4, + bump_uv_xform: vec4, + bump_off_wrap: vec4, + bump_dod: vec4, + bump_params: vec4, + mtl_params: vec4, + env_rot_0: vec4, + env_rot_1: vec4, + env_rot_2: vec4, + refl_strength: vec4, + refl_params: vec4, + refl_tint: vec4, + refract_tint: vec4, + cb_ops_a: vec4, + cb_ops: vec4, + cb_ops_b: vec4, + cb_flags: vec4, + 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>, + sfx: SurfaceFx, +}; + +struct ShadowUniform { + face_vp: array, 6 * MAX_SHADOW_LIGHTS>, + point: 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; +@group(0) @binding(3) var shadow: ShadowUniform; +@group(0) @binding(4) var shadow_maps: texture_2d_array; +@group(0) @binding(5) var bump_tex: texture_2d; + +struct VsIn { + @location(0) pos: vec3, + @location(1) normal: vec3, + @location(2) uv: vec2, +}; + +struct VsOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, + @location(1) world_pos: vec3, + @location(2) world_n: vec3, + @location(3) local_pos: vec3, + @location(4) local_n: vec3, +}; + +// Cofactor matrix of the upper-left 3x3 of `m` (inverse-transpose up to scale), so normals stay +// perpendicular under non-uniform scale. Dividing by |det| instead of det keeps mirrored +// transforms pointing outward. +fn normal_matrix(m: mat4x4) -> mat3x3 { + let c0 = m[0].xyz; + let c1 = m[1].xyz; + let c2 = m[2].xyz; + let sign = select(-1.0, 1.0, dot(c0, cross(c1, c2)) >= 0.0); + return mat3x3(cross(c1, c2), cross(c2, c0), cross(c0, c1)) * sign; +} + +@vertex +fn vs_mesh(v: VsIn) -> VsOut { + var out: VsOut; + let wp = u.model * vec4(v.pos, 1.0); + out.clip = u.mvp * vec4(v.pos, 1.0); + out.uv = v.uv; + out.world_pos = wp.xyz; + let wn = normal_matrix(u.model) * v.normal; + let nlen = length(wn); + var n_norm = select(vec3(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); + var ln = v.normal; + if (u.flags.w > 0.5) { + n_norm = -n_norm; + ln = -ln; + } + out.world_n = n_norm; + out.local_pos = v.pos; + out.local_n = ln; + return out; +} + +fn light_attenuation(dist: f32, decay_type: f32) -> f32 { + let dt = i32(decay_type + 0.5); + let d = max(dist, 1e-3); + if (dt == 1) { + return 1.0 / d; + } else if (dt == 2) { + return 1.0 / (d * d); + } + return 1.0; +} + +/// Fraction of PCF taps where the cube map of point light `i` records a closer occluder. +fn point_shadow_occlusion(i: i32, world_pos: vec3, n: vec3, light_pos: vec3) -> f32 { + let params = shadow.point[i]; + if (params.x < -0.5) { + return 0.0; + } + let slot = i32(params.x + 0.5); + let dist = length(world_pos - light_pos); + // World size of one texel at this distance for a 90 degree face. + let texel = 2.0 * dist / f32(SHADOW_MAP_SIZE); + // The face is picked from the offset point so the lookup never straddles a cube seam. + let biased = world_pos + n * (texel * 1.5); + let d = biased - light_pos; + let a = abs(d); + var face = 4; + if (a.x >= a.y && a.x >= a.z) { + face = select(1, 0, d.x > 0.0); + } else if (a.y >= a.z) { + face = select(3, 2, d.y > 0.0); + } else { + face = select(5, 4, d.z > 0.0); + } + let clip = shadow.face_vp[slot * 6 + face] * vec4(biased, 1.0); + if (clip.w <= 1e-5) { + return 0.0; + } + let ndc = clip.xy / clip.w; + let base = vec2(floor(vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * f32(SHADOW_MAP_SIZE))); + let last = SHADOW_MAP_SIZE - 1; + var occluded = 0.0; + for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { + for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { + let t = clamp(base + vec2(dx, dy), vec2(0), vec2(last)); + let stored = textureLoad(shadow_maps, t, slot * 6 + face, 0).r; + occluded = occluded + select(0.0, 1.0, dist - texel * 3.0 > stored); + } + } + return occluded / 9.0; +} + +struct TangentFrame { + t: vec3, + b: vec3, +}; + +fn compute_tangent_frame( + base_n: vec3, + dpdx_w: vec3, + dpdy_w: vec3, + duvdx: vec2, + duvdy: vec2, +) -> TangentFrame { + let det = duvdx.x * duvdy.y - duvdx.y * duvdy.x; + var t_vec: vec3; + var b_vec: vec3; + if (abs(det) > 1e-6) { + let inv_det = 1.0 / det; + t_vec = (dpdx_w * duvdy.y - dpdy_w * duvdx.y) * inv_det; + b_vec = (dpdy_w * duvdx.x - dpdx_w * duvdy.x) * inv_det; + t_vec = t_vec - base_n * dot(t_vec, base_n); + let t_len = length(t_vec); + if (t_len > 1e-5) { + t_vec = t_vec / t_len; + let b_sign = select(-1.0, 1.0, dot(cross(base_n, t_vec), b_vec) >= 0.0); + b_vec = cross(base_n, t_vec) * b_sign; + return TangentFrame(t_vec, b_vec); + } + } + let up = select(vec3(0.0, 1.0, 0.0), vec3(1.0, 0.0, 0.0), abs(base_n.y) > 0.9); + t_vec = normalize(cross(up, base_n)); + b_vec = cross(base_n, t_vec); + return TangentFrame(t_vec, b_vec); +} + +fn eval_light_contrib( + n: vec3, + t_vec: vec3, + b_vec: vec3, + v: vec3, + l: vec3, + light_rgb: vec3, + albedo: vec3, + spec_rgb: vec3, + spec_int: f32, + shininess: f32, + diffuse_vis: f32, + spec_vis: f32, + model: i32, +) -> vec3 { + let ndotl = max(dot(n, l), 0.0); + if (ndotl <= 0.0) { + return vec3(0.0); + } + if (model == 5) { + return pbr_uber_light(n, v, l, light_rgb, albedo, diffuse_vis, spec_vis); + } + if (model == 3) { + return albedo * light_rgb * (ndotl * diffuse_vis / 3.14159265); + } + var out = albedo * light_rgb * (ndotl * diffuse_vis); + if (spec_int > 1e-4) { + let h = normalize(l + v); + var lobe: f32; + if (model == 1) { + lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess); + } else if (model == 2) { + // Cook-Torrance: Beckmann D, Torrance-Sparrow G, exact unpolarized Fresnel F. + // `eval_light_contrib` omits the outer N·L factor on `lobe`, so `(F*D*G)/(4*N·L*N·V) * N·L` + // simplifies to `(F*D*G)/(4*N·V)`. + let nh = max(dot(n, h), 1e-3); + let nv = max(dot(n, v), 1e-3); + let vh = max(dot(v, h), 1e-3); + let m2 = max(shininess * shininess, 1e-3); + let nh2 = nh * nh; + let d_term = exp(-(1.0 - nh2) / (nh2 * m2)) / (3.14159265 * m2 * nh2 * nh2); + let g_term = min(1.0, min(2.0 * nh * nv / vh, 2.0 * nh * ndotl / vh)); + var fresnel = 1.0; + if (u.mtl_params.z > 0.5) { + let eta = max(u.mtl_params.y, 1.0); + let c = vh; + let g = sqrt(max(eta * eta + c * c - 1.0, 0.0)); + let gmc = g - c; + let gpc = max(g + c, 1e-5); + let r_s = gmc / gpc; + let r_p = (c * gpc - 1.0) / max(c * gmc + 1.0, 1e-5); + fresnel = 0.5 * r_s * r_s * (1.0 + r_p * r_p); + } + lobe = (fresnel * d_term * g_term) / (4.0 * nv); + } else if (model == 4) { + // Anisotropic Ward (1992) BRDF * (N·L) using tangent frame (T, B) and SpreadU/SpreadV. + let nh = max(dot(n, h), 1e-3); + let nv = max(dot(n, v), 1e-3); + let su = max(shininess, 1e-3); + let sv = max(u.mtl_params.w, 1e-3); + let ht = dot(h, t_vec) / su; + let hb = dot(h, b_vec) / sv; + let expo = -(ht * ht + hb * hb) / (nh * nh); + let denom = max(4.0 * 3.14159265 * su * sv * sqrt(nv), 1e-4); + lobe = (sqrt(ndotl) / denom) * exp(max(expo, -80.0)); + } else { + lobe = pow(max(dot(n, h), 0.0), shininess); + } + out = out + light_rgb * spec_rgb * (lobe * spec_int * spec_vis); + } + return out; +} + +fn sample_bump_height(uv_in: vec2, wrap_f: f32, ch: i32) -> f32 { + let uv = wrap_uv_only(uv_in, wrap_f); + let c = textureSampleLevel(bump_tex, mat_samp, uv, 0.0); + if (ch == 1) { + return (c.r + c.g + c.b) / 3.0; + } else if (ch == 2) { + return max(c.r, max(c.g, c.b)); + } else if (ch == 3) { + return min(c.r, min(c.g, c.b)); + } else if (ch == 4) { + return c.r; + } else if (ch == 5) { + return c.g; + } else if (ch == 6) { + return c.b; + } else if (ch == 7) { + return c.a; + } + return dot(c.rgb, vec3(0.299, 0.587, 0.114)); +} + +fn perturb_bump_normal( + base_n: vec3, + dpdx_w: vec3, + dpdy_w: vec3, + duvdx: vec2, + duvdy: vec2, + uv_in: vec2, + bump_scale: f32, + bump_mode: f32, + bump_wrap: f32, + clamp_z: f32, + bump_ch: i32, +) -> vec3 { + var uv = uv_in; + if (u.bump_dod.z > 0.5 && u.bump_dod.w > 0.5) { + let bdims = vec2(textureDimensions(bump_tex)); + let canvas_px = vec2(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w); + uv = (canvas_px - u.bump_dod.xy) / bdims; + } + let frame = compute_tangent_frame(base_n, dpdx_w, dpdy_w, duvdx, duvdy); + let t_vec = frame.t; + let b_vec = frame.b; + + if (bump_mode > 0.5) { + let b_col = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv, bump_wrap), 0.0); + let b_rgb = select(vec3(0.5, 0.5, 1.0), b_col.rgb / max(b_col.a, 1e-5), b_col.a > 1e-5); + let tn = b_rgb * 2.0 - vec3(1.0); + let perturbed = t_vec * tn.x + b_vec * tn.y + base_n * tn.z; + let plen = length(perturbed); + return select(base_n, perturbed / plen, plen > 1e-5); + } + + let inv_dim = vec2(1.0) / max(vec2(textureDimensions(bump_tex)), vec2(1.0)); + let h_l = sample_bump_height(uv - vec2(inv_dim.x, 0.0), bump_wrap, bump_ch); + let h_r = sample_bump_height(uv + vec2(inv_dim.x, 0.0), bump_wrap, bump_ch); + let h_d = sample_bump_height(uv - vec2(0.0, inv_dim.y), bump_wrap, bump_ch); + let h_u = sample_bump_height(uv + vec2(0.0, inv_dim.y), bump_wrap, bump_ch); + let dhdu = (h_r - h_l) * 0.5 * bump_scale; + let dhdv = (h_u - h_d) * 0.5 * bump_scale; + return normalize(base_n - t_vec * dhdu + b_vec * dhdv); +} + +fn unpremultiply(c: vec4) -> vec3 { + return select(vec3(0.0), c.rgb / max(c.a, 1e-5), c.a > 1e-5); +} + +// Ambient plus every light's contribution for one material. +fn shade( + pos: vec3, + n: vec3, + v: vec3, + tf: TangentFrame, + albedo: vec3, + spec_rgb: vec3, + spec_int: f32, + exponent: f32, + model: i32, +) -> vec3 { + let shininess = select(max(exponent, 1.0), exponent, model > 1); + var lit = albedo * u.ambient.rgb; + let n_dir = i32(u.light_counts.z + 0.5); + for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) { + if (i >= n_dir) { break; } + let l = normalize(u.dir_to_light[i].xyz); + lit = lit + eval_light_contrib(n, tf.t, tf.b, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0, model); + } + + let n_pt = i32(u.light_counts.x + 0.5); + for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) { + if (i >= n_pt) { break; } + let to_l = u.point_pos[i].xyz - pos; + let dist = max(length(to_l), 1e-4); + let att = light_attenuation(dist, u.point_pos[i].w); + var occ = 0.0; + if (u.light_counts.w > 0.5) { + occ = point_shadow_occlusion(i, pos, n, u.point_pos[i].xyz); + } + lit = lit + eval_light_contrib( + n, tf.t, tf.b, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, + 1.0 - shadow.point[i].y * occ, 1.0 - occ, model, + ); + } + + let n_sp = i32(u.light_counts.y + 0.5); + for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) { + if (i >= n_sp) { break; } + let to_l = u.spot_pos[i].xyz - pos; + let dist = max(length(to_l), 1e-4); + let l_dir = to_l / dist; + let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz)); + let cos_inner = u.spot_pos[i].w; + 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) * cone; + lit = lit + eval_light_contrib(n, tf.t, tf.b, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0, model); + } + } + return lit; +} + +// Secondary material of `MtlChanBool`, `MtlMerge3D` and `FalloffOperator`: straight RGB, alpha. +fn layer_color(pos: vec3, n: vec3, v: vec3, tf: TangentFrame, uv: vec2) -> vec4 { + var c = u.sfx.layer_col; + if (u.sfx.layer.w > 1.5) { + let t = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv, u.bump_off_wrap.z), 0.0); + c = vec4(unpremultiply(t) * c.rgb, t.a * c.a); + } + if (u.sfx.layer.z > 0.5) { + let model = i32(u.sfx.layer_mtl.y + 0.5); + c = vec4(shade(pos, n, v, tf, c.rgb, u.sfx.layer_spec.rgb, u.sfx.layer_mtl.x, u.sfx.layer_spec.w, model), c.a); + } + return c; +} + +// Environment colour along `world_dir` (`env_map_mode`: 0 equirect, 1 angular, 2-4 cube map, +// 5 the image at `mesh_uv`), tinted, from the texture in `env_tex_slot`. +fn sample_sphere_map(world_dir: vec3, mesh_uv: vec2) -> vec4 { + let slot = i32(u.env_rot_2.w + 0.5); + if (slot == 0) { + return vec4(u.refl_tint.rgb, 1.0); + } + let rot = mat3x3(u.env_rot_0.xyz, u.env_rot_1.xyz, u.env_rot_2.xyz); + let d = normalize(rot * env_space(world_dir)); + let map_mode = i32(u.env_rot_1.w + 0.5); + let dod = select(u.dod, u.bump_dod, slot == 2); + let has_dod = dod.z > 0.5 && dod.w > 0.5; + let tex_dims = vec2(select(textureDimensions(mat_tex), textureDimensions(bump_tex), slot == 2)); + var uv: vec2; + if (map_mode == 5) { + uv = mesh_uv; + } else if (map_mode >= 2) { + uv = cube_uv(d, map_mode, select(tex_dims, dod.zw, has_dod)); + } else { + // Fusion's longitude runs against atan2(x, z); Angular maps V linearly by height. + let u_c = 1.0 - fract(atan2(d.x, d.z) / 6.2831853 + 0.75); + let v_c = select(acos(clamp(d.y, -1.0, 1.0)) / 3.14159265, 0.5 - 0.5 * d.y, map_mode == 1); + uv = vec2(u_c, v_c); + } + if (has_dod) { + uv = clamp((uv * dod.zw - dod.xy) / tex_dims, vec2(0.0), vec2(1.0)); + } + let raw = select(textureSampleLevel(mat_tex, mat_samp, uv, 0.0), textureSampleLevel(bump_tex, mat_samp, uv, 0.0), slot == 2); + return vec4(unpremultiply(raw) * u.refl_tint.rgb, raw.a); +} + +// Fusion evaluates the HLS operands (11-16) as 0 and EnvCoords as the eye-space normal's XY. +fn cb_operand( + idx: i32, + bg: vec4, + fg: vec4, + pos: vec3, + uv: vec2, + env_c: vec2, + n: vec3, +) -> f32 { + switch idx { + case 0: { return fg.r; } + case 1: { return fg.g; } + case 2: { return fg.b; } + case 3: { return fg.a; } + case 4: { return bg.r; } + case 5: { return bg.g; } + case 6: { return bg.b; } + case 7: { return bg.a; } + case 9: { return 1.0; } + case 10: { return 0.5; } + case 17: { return dot(fg.rgb, vec3(0.299, 0.587, 0.114)); } + case 18: { return dot(bg.rgb, vec3(0.299, 0.587, 0.114)); } + case 19: { return pos.x; } + case 20: { return pos.y; } + case 21: { return pos.z; } + case 22: { return uv.x; } + case 23: { return 1.0 - uv.y; } + case 25: { return env_c.x; } + case 26: { return env_c.y; } + case 28: { return n.x; } + case 29: { return n.y; } + case 30: { return n.z; } + default: { return 0.0; } + } +} + +fn cb_combine(op: i32, a: f32, b: f32) -> f32 { + switch op { + case 0: { return a; } + case 1: { return b; } + case 2: { return 1.0 - a; } + case 3: { return 1.0 - b; } + case 4: { return a + b; } + case 5: { return a - b; } + case 6: { return a * b; } + case 7: { return select(a / b, 0.0, abs(b) <= 1e-5); } + case 8: { return min(a, b); } + case 9: { return max(a, b); } + case 10: { return 0.5 * (a + b); } + default: { return a; } + } +} + +@fragment +fn fs_mesh(in: VsOut) -> @location(0) vec4 { + let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); + let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap); + let dpdx_w = dpdx(in.world_pos); + let dpdy_w = dpdy(in.world_pos); + let duvdx = dpdx(uv_bump_xformed); + let duvdy = dpdy(uv_bump_xformed); + let duvdx_main = dpdx(uv_xformed); + let duvdy_main = dpdy(uv_xformed); + let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; + if (facing_away != BACK_PASS) { + discard; + } + + let env_mode = i32(u.env_rot_0.w + 0.5); + let cb_on = u.cb_flags.x > 0.5; + let layer_mode = i32(u.sfx.layer.x + 0.5); + let proc_on = u.sfx.proc_a.x > 0.5; + let v_dir = normalize(u.cam_pos.xyz - in.world_pos); + var n_surf = normalize(in.world_n); + if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { + n_surf = perturb_bump_normal( + n_surf, + dpdx_w, + dpdy_w, + duvdx, + duvdy, + uv_bump_xformed, + u.mat_fx.x, + u.mat_fx.y, + u.bump_off_wrap.z, + u.bump_params.x, + i32(u.bump_params.y + 0.5), + ); + } + let tframe = compute_tangent_frame(n_surf, dpdx_w, dpdy_w, duvdx_main, duvdy_main); + + var base_straight = vec3(0.0); + var rgb_alpha = u.diffuse_col.a; + var out_alpha = rgb_alpha * u.mtl_params.x; + + if (env_mode == 1) { + // Standalone SphereMap / CubeMap shader: lookup along the view ray. + let env_c = sample_sphere_map(-v_dir, in.uv); + base_straight = env_c.rgb * u.diffuse_col.rgb; + rgb_alpha = env_c.a * u.diffuse_col.a; + out_alpha = rgb_alpha * u.mtl_params.x; + } else { + var col = u.diffuse_col; + var tex_col = vec4(1.0); + var tex_straight = vec3(1.0); + if (u.flags.x > 0.5) { + var uv_samp = uv_xformed; + if (u.dod.z > 0.5 && u.dod.w > 0.5) { + let tdims = vec2(textureDimensions(mat_tex)); + let canvas_px = vec2(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w); + uv_samp = (canvas_px - u.dod.xy) / tdims; + if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) { + discard; + } + } + tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); + } + if (proc_on) { + tex_col = surface_proc(tex_col, vec2(in.uv.x, 1.0 - in.uv.y), n_surf, v_dir); + } + if (u.flags.x > 0.5 || proc_on) { + if (u.mat_fx.z <= 0.5) { + tex_straight = unpremultiply(tex_col); + } + col = select(tex_col, vec4(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; + } + // `rgb_alpha` is `tex_col.a * Diffuse.Opacity`; `Diffuse.Color.Alpha` (`u.mtl_params.x`) + // modulates output alpha without attenuating diffuse/specular RGB. + rgb_alpha = col.a; + out_alpha = rgb_alpha * u.mtl_params.x; + if (env_mode == 0 && !cb_on && layer_mode == 0 && out_alpha <= 0.002) { + discard; + } + + let albedo = tex_straight * u.diffuse_col.rgb; + if (env_mode == 2 && u.refl_tint.w < 0.5) { + base_straight = vec3(0.0); + rgb_alpha = 0.0; + out_alpha = 0.0; + } else if (u.flags.y > 0.5) { + base_straight = shade(in.world_pos, n_surf, v_dir, tframe, albedo, u.specular_col.rgb, u.flags.z, u.specular_col.w, i32(u.mat_fx.w + 0.5)) + + u.sfx.emission.rgb; + } else { + base_straight = albedo * u.uv_off_wrap.w; + } + + if (env_mode == 2) { + let r_dir = reflect(-v_dir, n_surf); + let refl_c = sample_sphere_map(r_dir, in.uv); + var refl_str = clamp(u.refl_strength.y, 0.0, 1.0); + if (u.refl_strength.x > 0.5) { + let cos_nv = clamp(dot(n_surf, v_dir), 0.0, 1.0); + let f_ang = pow(1.0 - cos_nv, max(u.refl_params.z, 1e-4)); + refl_str = clamp(mix(u.refl_params.y, u.refl_params.x, f_ang), 0.0, 1.0); + } + var under_rgb = base_straight; + var under_a = rgb_alpha; + if (rgb_alpha < 0.999 && u.refl_params.w > 0.01 && u.env_rot_2.w > 0.5 && u.refl_tint.w > 0.5) { + let eta = 1.0 / max(u.refl_params.w, 0.01); + var refr_dir = refract(-v_dir, n_surf, eta); + if (dot(refr_dir, refr_dir) < 1e-5) { + refr_dir = r_dir; + } + let refr_c = sample_sphere_map(refr_dir, in.uv); + under_rgb = mix(refr_c.rgb * u.refract_tint.rgb, base_straight, rgb_alpha); + under_a = clamp(max(rgb_alpha, refr_c.a * (1.0 - rgb_alpha)), 0.0, 1.0); + } + let under_premul = under_rgb * under_a; + let refl_a = refl_str * refl_c.a; + let out_premul = under_premul * (1.0 - refl_str) + refl_c.rgb * refl_a; + let final_a = clamp(under_a * (1.0 - refl_str) + refl_a, 0.0, 1.0); + base_straight = select(vec3(0.0), out_premul / max(final_a, 1e-5), final_a > 1e-5); + rgb_alpha = final_a; + out_alpha = clamp(out_alpha * (1.0 - refl_str) + refl_a, 0.0, 1.0); + } + } + + if (layer_mode >= 2) { + let fg = layer_color(in.world_pos, n_surf, v_dir, tframe, uv_xformed); + let bg_p = vec4(base_straight * rgb_alpha, out_alpha); + let fg_p = vec4(fg.rgb * fg.a, fg.a); + var o: vec4; + if (layer_mode == 2) { + o = fg_p * u.sfx.layer.y + bg_p * (1.0 - fg.a * u.sfx.layer.y); + } else { + o = mix(bg_p, fg_p, falloff_t(n_surf, v_dir, u.sfx.layer.y)); + } + base_straight = unpremultiply(o); + rgb_alpha = o.a; + out_alpha = o.a; + } + base_straight = apply_fog(base_straight, in.world_pos); + + if (cb_on) { + let bg_c = vec4(base_straight, out_alpha); + let fg_c = layer_color(in.world_pos, n_surf, v_dir, tframe, uv_xformed); + let cspace = i32(u.cb_flags.y + 0.5); + var c_pos = in.world_pos; + var c_n = n_surf; + if (cspace == 0) { + c_pos = in.local_pos; + let ln_len = length(in.local_n); + c_n = select(vec3(0.0, 0.0, 1.0), in.local_n / ln_len, ln_len > 1e-5); + } else if (cspace == 2) { + c_pos = (u.view * vec4(in.world_pos, 1.0)).xyz; + let en = (u.view * vec4(n_surf, 0.0)).xyz; + let elen = length(en); + c_n = select(vec3(0.0, 0.0, 1.0), en / elen, elen > 1e-5); + } + let env_c = normalize((u.view * vec4(n_surf, 0.0)).xyz).xy; + let r_out = cb_combine(i32(u.cb_ops.x + 0.5), cb_operand(i32(u.cb_ops_a.x + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.x + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); + let g_out = cb_combine(i32(u.cb_ops.y + 0.5), cb_operand(i32(u.cb_ops_a.y + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.y + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); + let b_out = cb_combine(i32(u.cb_ops.z + 0.5), cb_operand(i32(u.cb_ops_a.z + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.z + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); + let a_out = cb_combine(i32(u.cb_ops.w + 0.5), cb_operand(i32(u.cb_ops_a.w + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.w + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); + let clamped_a = clamp(a_out, 0.0, 1.0); + if (clamped_a <= 0.002) { + discard; + } + // Fusion does not premultiply the channel results by the computed alpha. + return vec4(clamp(vec3(r_out, g_out, b_out), vec3(0.0), vec3(1.0)), clamped_a); + } + + if (out_alpha <= 0.002) { + discard; + } + return vec4(clamp(base_straight * rgb_alpha, vec3(0.0), vec3(1.0)), out_alpha); +} + +@fragment +fn fs_normal(in: VsOut) -> @location(0) vec4 { + let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); + let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap); + let dpdx_w = dpdx(in.world_pos); + let dpdy_w = dpdy(in.world_pos); + let duvdx = dpdx(uv_bump_xformed); + let duvdy = dpdy(uv_bump_xformed); + let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; + if (facing_away != BACK_PASS) { + discard; + } + + var col = u.diffuse_col; + if (u.flags.x > 0.5) { + var uv_samp = uv_xformed; + if (u.dod.z > 0.5 && u.dod.w > 0.5) { + let tdims = vec2(textureDimensions(mat_tex)); + let canvas_px = vec2(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w); + uv_samp = (canvas_px - u.dod.xy) / tdims; + if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) { + discard; + } + } + let tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); + col = select(tex_col, vec4(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; + } + let out_alpha = col.a * u.mtl_params.x; + if (i32(u.env_rot_0.w + 0.5) == 0 && u.cb_flags.x < 0.5 && u.sfx.layer.x < 0.5 && out_alpha <= 0.002) { + discard; + } + + let nlen = length(in.world_n); + var n = select(vec3(0.0, 0.0, 1.0), in.world_n / nlen, nlen > 1e-5); + if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { + n = perturb_bump_normal( + n, + dpdx_w, + dpdy_w, + duvdx, + duvdy, + uv_bump_xformed, + u.mat_fx.x, + u.mat_fx.y, + u.bump_off_wrap.z, + u.bump_params.x, + i32(u.bump_params.y + 0.5), + ); + } + return vec4(n, 0.0); +} diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index 29a07c1ef4f0d99906b1631cb51941bc22e32706..a6963aa3351c64ab5f484f6950fb4bf77bcd4c21 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -9,9 +9,13 @@ mod collect; mod deform; mod fbx; +mod fx; +mod materials; mod math; mod mesh; +mod scene_ops; mod shader; +mod textures; pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d, mat4_inverse}; pub use math::{ @@ -28,6 +32,7 @@ fn lock_or_recover(m: &Mutex) -> MutexGuard<'_, T> { } use crate::cache::{AuxChannelTex, AuxChannels, CachedTexture, EMPTY_Z_SENTINEL}; +use fx::{SurfaceFx, SURFACE_FX_WGSL}; use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; use model::NodeId; use shader::{ @@ -228,7 +233,7 @@ pub struct CameraInstance { pub enum ShapeKind { ImagePlane, 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, top_cap: bool, bottom_cap: bool }, + Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32, sub_height: u32, top_cap: bool, bottom_cap: bool }, Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order. Cube { width: f32, sub: u32, faces: u8 }, @@ -295,6 +300,8 @@ pub enum SpecModel { Pbr, /// Anisotropic Ward BRDF (`MtlWard`). Ward, + /// `MtlPBRUber` metal/roughness BRDF; parameters live in `SurfaceFx::pbr`. + PbrUber, } #[derive(Clone, Copy, Debug, PartialEq)] @@ -330,16 +337,13 @@ pub struct MaterialFx { pub ward_spread_v: f32, /// Environment shading mode: `0 = none`, `1 = standalone SphereMap`, `2 = MtlReflect`. pub env_mode: u32, - /// `SphereMap.MapMode`: `0 = equirectangular`, `1 = angular`. + /// `0 = equirectangular`, `1 = angular`, `2 = vertical cross`, `3 = horizontal cross`, + /// `4 = single cube face`, `5 = image at the mesh UV`. pub env_map_mode: u32, /// Texture slot carrying the environment image: `0 = solid/none`, `1 = mat_tex`, `2 = bump_tex`. pub env_tex_slot: u32, /// Column-major 3x3 inverse rotation matrix for `SphereMap` direction lookup. pub env_rot: [f32; 9], - /// `SphereMap.StartAngle` in degrees. - pub env_start_angle: f32, - /// `SphereMap.EndAngle` in degrees. - pub env_end_angle: f32, /// `MtlReflect.Reflection.StrengthVariability`: `0 = Constant`, `1 = By Angle`. pub refl_strength_var: u32, pub refl_constant_strength: f32, @@ -355,11 +359,9 @@ pub struct MaterialFx { pub cb_ops_a: [u8; 4], pub cb_ops: [u8; 4], pub cb_ops_b: [u8; 4], - pub cb_fg_col: [f32; 4], /// `0 = Model`, `1 = World`, `2 = Eye`. pub cb_coord_space: u8, - /// `0 = constant fg_col`, `2 = sample bump_tex for FG`. - pub cb_fg_tex_slot: u8, + pub sfx: SurfaceFx, } impl Default for MaterialFx { @@ -387,8 +389,6 @@ impl Default for MaterialFx { env_map_mode: 0, env_tex_slot: 0, env_rot: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], - env_start_angle: 0.0, - env_end_angle: 360.0, refl_strength_var: 1, refl_constant_strength: 1.0, refl_glancing_strength: 0.8, @@ -402,9 +402,8 @@ impl Default for MaterialFx { cb_ops_a: [4, 5, 6, 7], cb_ops: [0, 0, 0, 0], cb_ops_b: [0, 1, 2, 3], - cb_fg_col: [0.0, 0.0, 0.0, 0.0], cb_coord_space: 2, - cb_fg_tex_slot: 0, + sfx: SurfaceFx::default(), } } } @@ -436,8 +435,6 @@ impl MaterialFx { for v in self.env_rot { v.to_bits().hash(h); } - self.env_start_angle.to_bits().hash(h); - self.env_end_angle.to_bits().hash(h); self.refl_strength_var.hash(h); self.refl_constant_strength.to_bits().hash(h); self.refl_glancing_strength.to_bits().hash(h); @@ -455,11 +452,8 @@ impl MaterialFx { self.cb_ops_a.hash(h); self.cb_ops.hash(h); self.cb_ops_b.hash(h); - for v in self.cb_fg_col { - v.to_bits().hash(h); - } self.cb_coord_space.hash(h); - self.cb_fg_tex_slot.hash(h); + bytemuck::bytes_of(&self.sfx).hash(h); } } @@ -486,8 +480,9 @@ impl ShapeKind { sub_base.hash(h); sub_height.hash(h); } - ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base, top_cap, bottom_cap } => { + ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base, sub_height, top_cap, bottom_cap } => { 2u8.hash(h); + sub_height.hash(h); (*top_cap, *bottom_cap).hash(h); radius.to_bits().hash(h); height.to_bits().hash(h); @@ -724,7 +719,7 @@ impl Scene3DRenderer { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("scene3d-shader"), source: wgpu::ShaderSource::Wgsl( - format!("{UV_XFORM_WGSL}{SHADER_3D}") + format!("{UV_XFORM_WGSL}{SHADER_3D}{SURFACE_FX_WGSL}{}", fx::simplex_wgsl()) .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string()) .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string()) .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()) @@ -1529,8 +1524,11 @@ impl Scene3DRenderer { dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0]; } let use_diffuse_tex = m.tex.is_some() && fx.env_tex_slot != 1; - let has_bump_tex = bump_src.is_some() && fx.env_tex_slot != 2 && fx.cb_fg_tex_slot != 2; - let env_span = ((fx.env_end_angle - fx.env_start_angle) / 360.0).abs().max(1e-4); + let has_bump_tex = bump_src.is_some() && fx.env_tex_slot != 2 && fx.sfx.layer[3] != 2.0; + let mut sfx = fx.sfx; + if !lighting_enabled { + sfx.layer[2] = 0.0; + } let uni = MeshUniform { mvp, model: m.world, @@ -1570,12 +1568,7 @@ impl Scene3DRenderer { env_rot_0: [fx.env_rot[0], fx.env_rot[1], fx.env_rot[2], fx.env_mode as f32], env_rot_1: [fx.env_rot[3], fx.env_rot[4], fx.env_rot[5], fx.env_map_mode as f32], env_rot_2: [fx.env_rot[6], fx.env_rot[7], fx.env_rot[8], fx.env_tex_slot as f32], - env_angles: [ - fx.env_start_angle / 360.0, - 1.0 / env_span, - fx.refl_strength_var as f32, - fx.refl_constant_strength, - ], + refl_strength: [fx.refl_strength_var as f32, fx.refl_constant_strength, 0.0, 0.0], refl_params: [ fx.refl_glancing_strength, fx.refl_face_on_strength, @@ -1592,18 +1585,13 @@ impl Scene3DRenderer { cb_ops_a: fx.cb_ops_a.map(f32::from), cb_ops: fx.cb_ops.map(f32::from), cb_ops_b: fx.cb_ops_b.map(f32::from), - cb_fg_col: fx.cb_fg_col, - cb_flags: [ - if fx.cb_enabled { 1.0 } else { 0.0 }, - f32::from(fx.cb_coord_space), - f32::from(fx.cb_fg_tex_slot), - 0.0, - ], + cb_flags: [if fx.cb_enabled { 1.0 } else { 0.0 }, f32::from(fx.cb_coord_space), 0.0, 0.0], point_pos, point_col, spot_pos, spot_dir, spot_col, + sfx, }; let uni_offset = prepared.len() * mesh_uni_stride; mesh_uniform_bytes[uni_offset..uni_offset + mesh_uni_size].copy_from_slice(bytemuck::bytes_of(&uni)); diff --git a/crates/engine/src/scene3d/scene_ops.rs b/crates/engine/src/scene3d/scene_ops.rs new file mode 100644 index 0000000000000000000000000000000000000000..a3720c9c0c35a14f1b517460b98ec7e81a615b12 --- /dev/null +++ b/crates/engine/src/scene3d/scene_ops.rs @@ -0,0 +1,303 @@ +//! Scene operators that edit or add geometry: `Fog3D`, `Locator3D`, `Ribbon3D` and `UVMap`. + +use std::f32::consts::{PI, TAU}; +use std::sync::Arc; + +use super::collect::{euler_matrix, ResolvedMaterial}; +use super::materials::flat; +use super::mesh::{build_shape_mesh, triangle_soup}; +use super::{MeshInstance, ShapeKind, Vertex3D}; +use model::{Comp, ExprEngine, Node}; + +pub(super) fn fog(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, meshes: &mut [MeshInstance]) { + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + if f("Enable", 1.0) < 0.5 { + return; + } + let kind = match n.static_str("FogType") { + Some("Exp") => 2.0, + Some("Exp2") => 3.0, + _ => 1.0, + }; + let fog = [kind, f("NearFogDist", 1.0), f("FarFogDistance", 100.0), f("FogDensity", 0.05)]; + let fog_col = [f("FogRed", 0.7), f("FogGreen", 0.7), f("FogBlue", 0.8), f("Radial", 0.0)]; + for m in meshes { + if let ShapeKind::WithMaterialFx { fx, .. } = &mut m.shape { + fx.sfx.fog = fog; + fx.sfx.fog_col = fog_col; + } + } +} + +/// Segments as degenerate `(a, b, b)` triangles, which the wireframe pass draws as the line `a-b`. +fn lines(segments: impl IntoIterator, normal: [f32; 3], mut mat: ResolvedMaterial) -> (ShapeKind, ResolvedMaterial) { + let v = |pos| Vertex3D { pos, normal, uv: [0.0; 2] }; + mat.fx.wireframe = true; + (ShapeKind::CustomMesh(Arc::new(segments.into_iter().flat_map(|[a, b]| [v(a), v(b), v(b)]).collect())), mat) +} + +/// `Locator3D` with `MakeRenderable`: an unlit axis cross `Size` across. +pub(super) fn locator(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> Option<(ShapeKind, ResolvedMaterial)> { + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + if f("MakeRenderable", 0.0) < 0.5 || f("UnseenByCamera", 0.0) > 0.5 { + return None; + } + let half = f("Size", 0.25) * 0.5; + let axes = [0, 1, 2].map(|a| { + let mut p = [0.0; 3]; + p[a] = half; + [p.map(|c| -c), p] + }); + Some(lines(axes, [0.0, 0.0, 1.0], flat([f("ColorRed", 1.0), f("ColorGreen", 1.0), f("ColorBlue", 1.0), 1.0]))) +} + +/// `Ribbon3D`: `NumberOfLines` parallel lines from `Start` to `End`, spread `RibbonWidth` across +/// the axis's up side and turned about it by `RibbonRotation`. +pub(super) fn ribbon(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, mat: ResolvedMaterial) -> (ShapeKind, ResolvedMaterial) { + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + let point = |k: &str, d: [f64; 3]| [0, 1, 2].map(|i| f(&format!("{k}.{}", ["X", "Y", "Z"][i]), d[i])); + let (start, end) = (point("Start", [-1.0, 0.0, 0.0]), point("End", [1.0, 0.0, 0.0])); + let dot = |a: [f32; 3], b: [f32; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let unit = |a: [f32; 3]| { + let l = dot(a, a).sqrt(); + if l > 1e-9 { a.map(|c| c / l) } else { [1.0, 0.0, 0.0] } + }; + let axis = unit([0, 1, 2].map(|i| end[i] - start[i])); + let up = if axis[1].abs() > 0.99 { [0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0] }; + let side0 = unit([0, 1, 2].map(|i| up[i] - axis[i] * dot(up, axis))); + let normal0 = [axis[1] * side0[2] - axis[2] * side0[1], axis[2] * side0[0] - axis[0] * side0[2], axis[0] * side0[1] - axis[1] * side0[0]]; + let (s, c) = f("RibbonRotation", 0.0).to_radians().sin_cos(); + let side = [0, 1, 2].map(|i| side0[i] * c + normal0[i] * s); + let normal = [0, 1, 2].map(|i| normal0[i] * c - side0[i] * s); + let count = f("NumberOfLines", 10.0).round().max(1.0) as usize; + let width = f("RibbonWidth", 0.2); + let segments = (0..count).map(|i| { + let t = if count == 1 { 0.0 } else { (i as f32 / (count - 1) as f32 - 0.5) * width }; + [start, end].map(|p| [0, 1, 2].map(|k| p[k] + side[k] * t)) + }); + lines(segments, normal, mat) +} + +#[derive(Clone, Copy, PartialEq)] +enum UvMode { + Planar, + Cylindrical, + Spherical, + Cube, + Xyz, +} + +/// `UVMap` projection: world points enter the map's frame (`R^T (p - Center)`), whose +/// `Orientation` axis is "up" and whose other two axes span the image. +pub(super) struct UvMap { + mode: UvMode, + rot: [f32; 16], + center: [f32; 3], + size: [f32; 3], + orientation: usize, + tile: [f32; 2], + flip: [bool; 2], +} + +/// `(s, t, up)` world-axis indices and signs per `Orientation` (`X`, `Y`, `Z`). +const FRAMES: [[(usize, f32); 3]; 3] = [[(2, -1.0), (1, 1.0), (0, 1.0)], [(0, 1.0), (2, -1.0), (1, 1.0)], [(0, 1.0), (1, 1.0), (2, 1.0)]]; + +impl UvMap { + /// `None` for `Camera` projection, which leaves UVs untouched. + pub(super) fn from_node(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> Option { + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + let xyz = |k: &str, d: f64| ["X", "Y", "Z"].map(|a| f(&format!("{k}.{a}"), d)); + let mode = match n.static_str("MapMode") { + Some("Cylindrical") => UvMode::Cylindrical, + Some("Spherical") => UvMode::Spherical, + Some("CubeMap") => UvMode::Cube, + Some("XYZtoUVW") => UvMode::Xyz, + Some("Camera") => return None, + _ => UvMode::Planar, + }; + Some(Self { + mode, + rot: euler_matrix(xyz("Rotate", 0.0), n.static_str("Rotate.RotOrder").unwrap_or("XYZ")), + center: xyz("Center", 0.0), + size: xyz("Size", 2.0).map(|s| if s.abs() < 1e-6 { 1e-6 } else { s }), + orientation: f("Orientation", 1.0).round().clamp(0.0, 2.0) as usize, + tile: [f("Tile.U", 1.0), f("Tile.V", 1.0)], + flip: [f("Flip.U", 0.0) > 0.5, f("Flip.V", 0.0) > 0.5], + }) + } + + fn to_local(&self, p: [f32; 3]) -> [f32; 3] { + let (r, c) = (&self.rot, self.center); + [0, 1, 2].map(|i| r[i * 4] * (p[0] - c[0]) + r[i * 4 + 1] * (p[1] - c[1]) + r[i * 4 + 2] * (p[2] - c[2])) + } + + /// Mesh UV (V down) of world point `p`; in cube mode the face is the dominant axis of the + /// world point `face_at`. + fn uv(&self, p: [f32; 3], face_at: [f32; 3]) -> [f32; 2] { + let local = self.to_local(p); + let (orientation, face_sign) = if self.mode == UvMode::Cube { + let f = self.to_local(face_at); + let a = (0..3).max_by(|&a, &b| f[a].abs().total_cmp(&f[b].abs())).unwrap_or(2); + (a, if f[a] < 0.0 { -1.0 } else { 1.0 }) + } else { + (self.orientation, 1.0) + }; + let [s, t, up] = FRAMES[orientation].map(|(i, sign)| (local[i] * sign, self.size[i])); + let (u, v) = match self.mode { + UvMode::Xyz => return [s.0, 1.0 - t.0], + UvMode::Planar | UvMode::Cube => (face_sign * s.0 / s.1, t.0 / t.1), + UvMode::Cylindrical | UvMode::Spherical => { + let u = s.0.atan2(-t.0) / TAU; + let len = (s.0 * s.0 + t.0 * t.0 + up.0 * up.0).sqrt(); + let v = if self.mode == UvMode::Cylindrical { up.0 / up.1 } else { (up.0 / len.max(1e-9)).clamp(-1.0, 1.0).asin() / PI }; + (u, v) + } + }; + let [u, v] = [(u, 0), (v, 1)].map(|(c, k)| { + let c = c * self.tile[k] + 0.5; + if self.flip[k] { 1.0 - c } else { c } + }); + [u, 1.0 - v] + } +} + +/// Re-projects UVs; in cube mode each triangle takes the face of its centroid. +pub(super) fn uv_map(map: &UvMap, meshes: &mut [MeshInstance], aspect: impl Fn(&MeshInstance) -> f32) { + for m in meshes.iter_mut().filter(|m| m.text3d.is_none()) { + let mut soup = triangle_soup(build_shape_mesh(m.shape.base_shape(), aspect(m))); + let w = m.world; + let to_world = |v: [f32; 3]| [0, 1, 2].map(|i| w[i] * v[0] + w[4 + i] * v[1] + w[8 + i] * v[2] + w[12 + i]); + for tri in soup.chunks_exact_mut(3) { + let p = [0, 1, 2].map(|k| to_world(tri[k].pos)); + let centroid = [0, 1, 2].map(|i| (p[0][i] + p[1][i] + p[2][i]) / 3.0); + for (v, q) in tri.iter_mut().zip(p) { + v.uv = map.uv(q, centroid); + } + } + let (_, fx) = m.shape.split_fx(); + m.shape = ShapeKind::WithMaterialFx { inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))), fx }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scene3d::collect::{collect_test_scene, comp_src}; + + fn scene(tools: &str) -> (Vec, crate::scene3d::SceneLights) { + let (_, meshes, lights) = collect_test_scene(&comp_src(tools), "R"); + (meshes, lights) + } + + #[test] + fn fog_tags_every_child_mesh() { + let (meshes, _) = scene( + "S = Shape3D { }, C = Shape3D { }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = \"S\", Source = \"Output\", }, SceneInput2 = Input { SourceOp = \"C\", Source = \"Output\", }, }, }, + R = Fog3D { Inputs = { SceneInput = Input { SourceOp = \"M\", Source = \"Output\", }, FogType = Input { Value = FuID { \"Exp2\" }, }, + FogDensity = Input { Value = 0.3, }, Radial = Input { Value = 1, }, }, },", + ); + assert_eq!(meshes.len(), 2); + for m in &meshes { + let fx = m.shape.split_fx().1; + assert_eq!(fx.sfx.fog, [3.0, 1.0, 100.0, 0.3]); + assert_eq!(fx.sfx.fog_col, [0.7, 0.7, 0.8, 1.0]); + } + } + + #[test] + fn locator_draws_a_cross_and_leaves_its_input_untransformed() { + let (meshes, _) = scene( + "S = Shape3D { }, + R = Locator3D { Inputs = { SceneInput = Input { SourceOp = \"S\", Source = \"Output\", }, MakeRenderable = Input { Value = 1, }, + [\"Transform3DOp.Translate.X\"] = Input { Value = 3, }, ColorGreen = Input { Value = 0, }, }, },", + ); + assert_eq!(meshes.len(), 2); + assert_eq!(meshes[0].world[12], 3.0); + assert_eq!(meshes[0].diffuse_col, [1.0, 0.0, 1.0, 1.0]); + assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::CustomMesh(v) if v.len() == 9)); + assert!(meshes[0].shape.split_fx().1.wireframe); + assert_eq!(meshes[1].world[12], 0.0); + let (hidden, _) = scene("R = Locator3D { },"); + assert!(hidden.is_empty()); + } + + #[test] + fn ribbon_spreads_lines_across_its_width() { + let (meshes, _) = scene("R = Ribbon3D { Inputs = { NumberOfLines = Input { Value = 3, }, RibbonWidth = Input { Value = 1, }, }, },"); + let ShapeKind::CustomMesh(v) = meshes[0].shape.base_shape() else { panic!("ribbon mesh") }; + let ys: Vec = v.chunks(3).map(|t| t[0].pos[1]).collect(); + assert_eq!(ys, [-0.5, 0.0, 0.5]); + assert_eq!((v[0].pos[0], v[1].pos[0]), (-1.0, 1.0)); + assert!(meshes[0].shape.split_fx().1.wireframe); + } + + #[test] + fn triangulate_passes_through_and_weld_smooths_normals() { + let cube = "S = Shape3D { Inputs = { Shape = Input { Value = FuID { \"SurfaceCubeInputs\" }, }, }, },"; + let (tri, _) = scene(&format!("{cube} R = Triangulate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = \"S\", Source = \"Output\", }}, }}, }},")); + assert!(matches!(tri[0].shape.base_shape(), ShapeKind::Cube { .. })); + let (welded, _) = scene(&format!( + "{cube} R = Weld3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = \"S\", Source = \"Output\", }}, WeldNormals = Input {{ Value = 1, }}, }}, }}," + )); + let ShapeKind::CustomMesh(v) = welded[0].shape.base_shape() else { panic!("welded mesh") }; + let corner = v.iter().find(|p| p.pos.iter().all(|c| c.abs() > 0.49)).expect("corner vertex"); + assert!(corner.normal.iter().all(|c| c.abs() > 0.5), "corner normals average the three faces: {:?}", corner.normal); + } + + #[test] + fn light_dome_is_ambient_only_when_textured() { + let (_, bare) = scene("R = LightDome { Inputs = { Intensity = Input { Value = 0.5, }, }, },"); + assert_eq!((bare.count, bare.ambient), (1, [0.0; 3])); + let (_, lit) = scene( + "Img = Background { }, + R = LightDome { Inputs = { Intensity = Input { Value = 0.5, }, DomeTexture = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", + ); + assert_eq!(lit.ambient, [0.5; 3]); + } + + #[test] + fn uv_map_rebuilds_child_meshes() { + let (meshes, _) = scene( + "S = Shape3D { }, + R = UVMap { Inputs = { SceneInput = Input { SourceOp = \"S\", Source = \"Output\", }, }, },", + ); + let ShapeKind::CustomMesh(v) = meshes[0].shape.base_shape() else { panic!("uv mapped mesh") }; + assert!(v.iter().all(|p| (0.0..=1.0).contains(&p.uv[0]) && (0.0..=1.0).contains(&p.uv[1]))); + } + + fn map(mode: UvMode, orientation: usize) -> UvMap { + UvMap { mode, rot: crate::scene3d::mat4_identity(), center: [0.0; 3], size: [2.0; 3], orientation, tile: [1.0; 2], flip: [false; 2] } + } + + #[test] + fn planar_orientations_follow_fusion_frames() { + let p = [0.5, 0.25, -0.5]; + assert_eq!(map(UvMode::Planar, 2).uv(p, [0.0; 3]), [0.75, 1.0 - 0.625]); + assert_eq!(map(UvMode::Planar, 1).uv(p, [0.0; 3]), [0.75, 1.0 - 0.75]); + assert_eq!(map(UvMode::Planar, 0).uv(p, [0.0; 3]), [0.75, 1.0 - 0.625]); + let mut tiled = map(UvMode::Planar, 2); + tiled.tile = [2.0, 1.0]; + tiled.flip = [false, true]; + assert_eq!(tiled.uv(p, [0.0; 3]), [1.0, 0.625]); + } + + #[test] + fn cylindrical_spherical_and_xyz() { + let front = [0.0, 0.0, 1.0]; + let cyl = map(UvMode::Cylindrical, 1).uv(front, front); + assert!((cyl[0] - 0.5).abs() < 1e-6 && (cyl[1] - 0.5).abs() < 1e-6, "{cyl:?}"); + let top = map(UvMode::Spherical, 1).uv([0.0, 1.0, 0.0], [0.0, 1.0, 0.0]); + assert!((top[1] - 0.0).abs() < 1e-6, "pole maps to v = 1 (V down 0): {top:?}"); + assert_eq!(map(UvMode::Xyz, 2).uv([0.3, 0.4, 0.5], [0.0; 3]), [0.3, 0.6]); + } + + #[test] + fn cube_mode_projects_each_face_along_its_dominant_axis() { + let m = map(UvMode::Cube, 1); + let side = m.uv([1.0, 0.5, 0.0], [1.0, 0.4, 0.0]); + let back = m.uv([-1.0, 0.5, 0.0], [-1.0, 0.4, 0.0]); + assert_eq!(side[1], back[1]); + assert_eq!(side[1], 1.0 - 0.75); + } +} diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index 7d680246edbe4a68ecc4dbd0914b43354980564a..8a99d1dbe86a0771c4b8e69a3a1b19542b9ef098 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -2,6 +2,8 @@ use bytemuck::{Pod, Zeroable}; +use super::fx::SurfaceFx; + /// Point and spot lights each get this many shader slots. pub(super) const MAX_LIGHTS: usize = 8; /// Directional lights get this many shader slots. @@ -62,12 +64,12 @@ pub(super) struct MeshUniform { pub(super) mtl_params: [f32; 4], /// Environment inverse rotation col 0 + `env_mode` (`0=none, 1=SphereMap, 2=MtlReflect`) pub(super) env_rot_0: [f32; 4], - /// Environment inverse rotation col 1 + `env_map_mode` (`0=equirect, 1=angular`) + /// Environment inverse rotation col 1 + `env_map_mode` (see `sample_sphere_map`) pub(super) env_rot_1: [f32; 4], /// Environment inverse rotation col 2 + `env_tex_slot` (`0=solid, 1=mat_tex, 2=bump_tex`) pub(super) env_rot_2: [f32; 4], - /// `[start_angle_norm, inv_angle_span, strength_variability, constant_strength]` - pub(super) env_angles: [f32; 4], + /// `[strength_variability, constant_strength, 0, 0]` + pub(super) refl_strength: [f32; 4], /// `[glancing_strength, face_on_strength, falloff, refract_ior]` pub(super) refl_params: [f32; 4], /// `[refl_tint_r, refl_tint_g, refl_tint_b, has_bg_material]` @@ -80,9 +82,7 @@ pub(super) struct MeshUniform { pub(super) cb_ops: [f32; 4], /// `MtlChanBool` operand B indices `[r, g, b, a]` pub(super) cb_ops_b: [f32; 4], - /// `MtlChanBool` foreground material constant RGBA - pub(super) cb_fg_col: [f32; 4], - /// `[cb_enabled, cb_coord_space (0=Model,1=World,2=Eye), cb_fg_tex_slot (0=none,2=bump_tex), 0]` + /// `[cb_enabled, cb_coord_space (0=Model,1=World,2=Eye), 0, 0]` pub(super) cb_flags: [f32; 4], /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` pub(super) point_pos: [[f32; 4]; MAX_LIGHTS], @@ -94,6 +94,7 @@ pub(super) struct MeshUniform { pub(super) spot_dir: [[f32; 4]; MAX_LIGHTS], /// Spot light colors * intensity `(r, g, b, decay_type)` pub(super) spot_col: [[f32; 4]; MAX_LIGHTS], + pub(super) sfx: SurfaceFx, } #[repr(C)] @@ -199,694 +200,4 @@ fn fs_shadow(in: VsOut) -> @location(0) f32 { /// WGSL source; `MAX_LIGHTS`, `MAX_DIR_LIGHTS`, `MAX_SHADOW_LIGHTS` and `SHADOW_MAP_SIZE` are /// substituted with the Rust constants at pipeline creation. -pub(super) const SHADER_3D: &str = r#" -struct MeshUniform { - mvp: mat4x4, - model: mat4x4, - view: mat4x4, - dod: vec4, - flags: vec4, - diffuse_col: vec4, - specular_col: vec4, - ambient: vec4, - dir_to_light: array, MAX_DIR_LIGHTS>, - dir_color: array, MAX_DIR_LIGHTS>, - cam_pos: vec4, - light_counts: vec4, - uv_xform: vec4, - uv_off_wrap: vec4, - mat_fx: vec4, - bump_uv_xform: vec4, - bump_off_wrap: vec4, - bump_dod: vec4, - bump_params: vec4, - mtl_params: vec4, - env_rot_0: vec4, - env_rot_1: vec4, - env_rot_2: vec4, - env_angles: vec4, - refl_params: vec4, - refl_tint: vec4, - refract_tint: vec4, - cb_ops_a: vec4, - cb_ops: vec4, - cb_ops_b: vec4, - cb_fg_col: vec4, - cb_flags: vec4, - 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>, -}; - -struct ShadowUniform { - face_vp: array, 6 * MAX_SHADOW_LIGHTS>, - point: 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; -@group(0) @binding(3) var shadow: ShadowUniform; -@group(0) @binding(4) var shadow_maps: texture_2d_array; -@group(0) @binding(5) var bump_tex: texture_2d; - -struct VsIn { - @location(0) pos: vec3, - @location(1) normal: vec3, - @location(2) uv: vec2, -}; - -struct VsOut { - @builtin(position) clip: vec4, - @location(0) uv: vec2, - @location(1) world_pos: vec3, - @location(2) world_n: vec3, - @location(3) local_pos: vec3, - @location(4) local_n: vec3, -}; - -// Cofactor matrix of the upper-left 3x3 of `m` (inverse-transpose up to scale), so normals stay -// perpendicular under non-uniform scale. Dividing by |det| instead of det keeps mirrored -// transforms pointing outward. -fn normal_matrix(m: mat4x4) -> mat3x3 { - let c0 = m[0].xyz; - let c1 = m[1].xyz; - let c2 = m[2].xyz; - let sign = select(-1.0, 1.0, dot(c0, cross(c1, c2)) >= 0.0); - return mat3x3(cross(c1, c2), cross(c2, c0), cross(c0, c1)) * sign; -} - -@vertex -fn vs_mesh(v: VsIn) -> VsOut { - var out: VsOut; - let wp = u.model * vec4(v.pos, 1.0); - out.clip = u.mvp * vec4(v.pos, 1.0); - out.uv = v.uv; - out.world_pos = wp.xyz; - let wn = normal_matrix(u.model) * v.normal; - let nlen = length(wn); - var n_norm = select(vec3(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); - var ln = v.normal; - if (u.flags.w > 0.5) { - n_norm = -n_norm; - ln = -ln; - } - out.world_n = n_norm; - out.local_pos = v.pos; - out.local_n = ln; - return out; -} - -fn light_attenuation(dist: f32, decay_type: f32) -> f32 { - let dt = i32(decay_type + 0.5); - let d = max(dist, 1e-3); - if (dt == 1) { - return 1.0 / d; - } else if (dt == 2) { - return 1.0 / (d * d); - } - return 1.0; -} - -/// Fraction of PCF taps where the cube map of point light `i` records a closer occluder. -fn point_shadow_occlusion(i: i32, world_pos: vec3, n: vec3, light_pos: vec3) -> f32 { - let params = shadow.point[i]; - if (params.x < -0.5) { - return 0.0; - } - let slot = i32(params.x + 0.5); - let dist = length(world_pos - light_pos); - // World size of one texel at this distance for a 90 degree face. - let texel = 2.0 * dist / f32(SHADOW_MAP_SIZE); - // The face is picked from the offset point so the lookup never straddles a cube seam. - let biased = world_pos + n * (texel * 1.5); - let d = biased - light_pos; - let a = abs(d); - var face = 4; - if (a.x >= a.y && a.x >= a.z) { - face = select(1, 0, d.x > 0.0); - } else if (a.y >= a.z) { - face = select(3, 2, d.y > 0.0); - } else { - face = select(5, 4, d.z > 0.0); - } - let clip = shadow.face_vp[slot * 6 + face] * vec4(biased, 1.0); - if (clip.w <= 1e-5) { - return 0.0; - } - let ndc = clip.xy / clip.w; - let base = vec2(floor(vec2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * f32(SHADOW_MAP_SIZE))); - let last = SHADOW_MAP_SIZE - 1; - var occluded = 0.0; - for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { - for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { - let t = clamp(base + vec2(dx, dy), vec2(0), vec2(last)); - let stored = textureLoad(shadow_maps, t, slot * 6 + face, 0).r; - occluded = occluded + select(0.0, 1.0, dist - texel * 3.0 > stored); - } - } - return occluded / 9.0; -} - -struct TangentFrame { - t: vec3, - b: vec3, -}; - -fn compute_tangent_frame( - base_n: vec3, - dpdx_w: vec3, - dpdy_w: vec3, - duvdx: vec2, - duvdy: vec2, -) -> TangentFrame { - let det = duvdx.x * duvdy.y - duvdx.y * duvdy.x; - var t_vec: vec3; - var b_vec: vec3; - if (abs(det) > 1e-6) { - let inv_det = 1.0 / det; - t_vec = (dpdx_w * duvdy.y - dpdy_w * duvdx.y) * inv_det; - b_vec = (dpdy_w * duvdx.x - dpdx_w * duvdy.x) * inv_det; - t_vec = t_vec - base_n * dot(t_vec, base_n); - let t_len = length(t_vec); - if (t_len > 1e-5) { - t_vec = t_vec / t_len; - let b_sign = select(-1.0, 1.0, dot(cross(base_n, t_vec), b_vec) >= 0.0); - b_vec = cross(base_n, t_vec) * b_sign; - return TangentFrame(t_vec, b_vec); - } - } - let up = select(vec3(0.0, 1.0, 0.0), vec3(1.0, 0.0, 0.0), abs(base_n.y) > 0.9); - t_vec = normalize(cross(up, base_n)); - b_vec = cross(base_n, t_vec); - return TangentFrame(t_vec, b_vec); -} - -fn eval_light_contrib( - n: vec3, - t_vec: vec3, - b_vec: vec3, - v: vec3, - l: vec3, - light_rgb: vec3, - albedo: vec3, - spec_rgb: vec3, - spec_int: f32, - shininess: f32, - diffuse_vis: f32, - spec_vis: f32, -) -> vec3 { - let ndotl = max(dot(n, l), 0.0); - if (ndotl <= 0.0) { - return vec3(0.0); - } - let model = i32(u.mat_fx.w + 0.5); - if (model == 3) { - return albedo * light_rgb * (ndotl * diffuse_vis / 3.14159265); - } - var out = albedo * light_rgb * (ndotl * diffuse_vis); - if (spec_int > 1e-4) { - let h = normalize(l + v); - var lobe: f32; - if (model == 1) { - lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess); - } else if (model == 2) { - // Cook-Torrance: Beckmann D, Torrance-Sparrow G, exact unpolarized Fresnel F. - // `eval_light_contrib` omits the outer N·L factor on `lobe`, so `(F*D*G)/(4*N·L*N·V) * N·L` - // simplifies to `(F*D*G)/(4*N·V)`. - let nh = max(dot(n, h), 1e-3); - let nv = max(dot(n, v), 1e-3); - let vh = max(dot(v, h), 1e-3); - let m2 = max(shininess * shininess, 1e-3); - let nh2 = nh * nh; - let d_term = exp(-(1.0 - nh2) / (nh2 * m2)) / (3.14159265 * m2 * nh2 * nh2); - let g_term = min(1.0, min(2.0 * nh * nv / vh, 2.0 * nh * ndotl / vh)); - var fresnel = 1.0; - if (u.mtl_params.z > 0.5) { - let eta = max(u.mtl_params.y, 1.0); - let c = vh; - let g = sqrt(max(eta * eta + c * c - 1.0, 0.0)); - let gmc = g - c; - let gpc = max(g + c, 1e-5); - let r_s = gmc / gpc; - let r_p = (c * gpc - 1.0) / max(c * gmc + 1.0, 1e-5); - fresnel = 0.5 * r_s * r_s * (1.0 + r_p * r_p); - } - lobe = (fresnel * d_term * g_term) / (4.0 * nv); - } else if (model == 4) { - // Anisotropic Ward (1992) BRDF * (N·L) using tangent frame (T, B) and SpreadU/SpreadV. - let nh = max(dot(n, h), 1e-3); - let nv = max(dot(n, v), 1e-3); - let su = max(shininess, 1e-3); - let sv = max(u.mtl_params.w, 1e-3); - let ht = dot(h, t_vec) / su; - let hb = dot(h, b_vec) / sv; - let expo = -(ht * ht + hb * hb) / (nh * nh); - let denom = max(4.0 * 3.14159265 * su * sv * sqrt(nv), 1e-4); - lobe = (sqrt(ndotl) / denom) * exp(max(expo, -80.0)); - } else { - lobe = pow(max(dot(n, h), 0.0), shininess); - } - out = out + light_rgb * spec_rgb * (lobe * spec_int * spec_vis); - } - return out; -} - -fn sample_bump_height(uv_in: vec2, wrap_f: f32, ch: i32) -> f32 { - let uv = wrap_uv_only(uv_in, wrap_f); - let c = textureSampleLevel(bump_tex, mat_samp, uv, 0.0); - if (ch == 1) { - return (c.r + c.g + c.b) / 3.0; - } else if (ch == 2) { - return max(c.r, max(c.g, c.b)); - } else if (ch == 3) { - return min(c.r, min(c.g, c.b)); - } else if (ch == 4) { - return c.r; - } else if (ch == 5) { - return c.g; - } else if (ch == 6) { - return c.b; - } else if (ch == 7) { - return c.a; - } - return dot(c.rgb, vec3(0.299, 0.587, 0.114)); -} - -fn perturb_bump_normal( - base_n: vec3, - dpdx_w: vec3, - dpdy_w: vec3, - duvdx: vec2, - duvdy: vec2, - uv_in: vec2, - bump_scale: f32, - bump_mode: f32, - bump_wrap: f32, - clamp_z: f32, - bump_ch: i32, -) -> vec3 { - var uv = uv_in; - if (u.bump_dod.z > 0.5 && u.bump_dod.w > 0.5) { - let bdims = vec2(textureDimensions(bump_tex)); - let canvas_px = vec2(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w); - uv = (canvas_px - u.bump_dod.xy) / bdims; - } - let frame = compute_tangent_frame(base_n, dpdx_w, dpdy_w, duvdx, duvdy); - let t_vec = frame.t; - let b_vec = frame.b; - - if (bump_mode > 0.5) { - let b_col = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv, bump_wrap), 0.0); - let b_rgb = select(vec3(0.5, 0.5, 1.0), b_col.rgb / max(b_col.a, 1e-5), b_col.a > 1e-5); - let tn = b_rgb * 2.0 - vec3(1.0); - let perturbed = t_vec * tn.x + b_vec * tn.y + base_n * tn.z; - let plen = length(perturbed); - return select(base_n, perturbed / plen, plen > 1e-5); - } - - let inv_dim = vec2(1.0) / max(vec2(textureDimensions(bump_tex)), vec2(1.0)); - let h_l = sample_bump_height(uv - vec2(inv_dim.x, 0.0), bump_wrap, bump_ch); - let h_r = sample_bump_height(uv + vec2(inv_dim.x, 0.0), bump_wrap, bump_ch); - let h_d = sample_bump_height(uv - vec2(0.0, inv_dim.y), bump_wrap, bump_ch); - let h_u = sample_bump_height(uv + vec2(0.0, inv_dim.y), bump_wrap, bump_ch); - let dhdu = (h_r - h_l) * 0.5 * bump_scale; - let dhdv = (h_u - h_d) * 0.5 * bump_scale; - return normalize(base_n - t_vec * dhdu + b_vec * dhdv); -} - -fn sample_sphere_map(world_dir: vec3) -> vec4 { - let slot = i32(u.env_rot_2.w + 0.5); - if (slot == 0) { - return vec4(u.refl_tint.rgb, 1.0); - } - let rot = mat3x3(u.env_rot_0.xyz, u.env_rot_1.xyz, u.env_rot_2.xyz); - let d = normalize(rot * world_dir); - let map_mode = i32(u.env_rot_1.w + 0.5); - var uv: vec2; - if (map_mode == 1) { - let r_xy = length(d.xy); - let r = select(0.0, acos(clamp(-d.z, -1.0, 1.0)) / (3.14159265 * r_xy), r_xy > 1e-5); - uv = clamp(vec2(0.5 + d.x * r * 0.5, 0.5 - d.y * r * 0.5), vec2(0.0), vec2(1.0)); - } else { - let theta = atan2(d.x, d.z); - var u_c = fract(theta / 6.2831853 + 0.75); - u_c = fract((u_c - u.env_angles.x) * u.env_angles.y); - let v_c = acos(clamp(d.y, -1.0, 1.0)) / 3.14159265; - uv = vec2(u_c, v_c); - } - var raw: vec4; - if (slot == 2) { - if (u.bump_dod.z > 0.5 && u.bump_dod.w > 0.5) { - let dims = vec2(textureDimensions(bump_tex)); - uv = clamp((vec2(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w) - u.bump_dod.xy) / dims, vec2(0.0), vec2(1.0)); - } - raw = textureSampleLevel(bump_tex, mat_samp, uv, 0.0); - } else { - if (u.dod.z > 0.5 && u.dod.w > 0.5) { - let dims = vec2(textureDimensions(mat_tex)); - uv = clamp((vec2(uv.x * u.dod.z, uv.y * u.dod.w) - u.dod.xy) / dims, vec2(0.0), vec2(1.0)); - } - raw = textureSampleLevel(mat_tex, mat_samp, uv, 0.0); - } - let straight = select(vec3(0.0), raw.rgb / max(raw.a, 1e-5), raw.a > 1e-5); - return vec4(straight * u.refl_tint.rgb, raw.a); -} - -fn cb_hls(c: vec3) -> vec3 { - let mx = max(c.r, max(c.g, c.b)); - let mn = min(c.r, min(c.g, c.b)); - let l = 0.5 * (mx + mn); - let d = mx - mn; - if (d <= 1e-6) { - return vec3(0.0, l, 0.0); - } - let s = d / max(1.0 - abs(2.0 * l - 1.0), 1e-6); - var h = 0.0; - if (mx == c.r) { - h = (c.g - c.b) / d + select(0.0, 6.0, c.g < c.b); - } else if (mx == c.g) { - h = (c.b - c.r) / d + 2.0; - } else { - h = (c.r - c.g) / d + 4.0; - } - return vec3(h / 6.0, l, clamp(s, 0.0, 1.0)); -} - -fn cb_operand( - idx: i32, - bg: vec4, - fg: vec4, - pos: vec3, - uv: vec2, - env_c: vec3, - n: vec3, -) -> f32 { - switch idx { - case 0: { return fg.r; } - case 1: { return fg.g; } - case 2: { return fg.b; } - case 3: { return fg.a; } - case 4: { return bg.r; } - case 5: { return bg.g; } - case 6: { return bg.b; } - case 7: { return bg.a; } - case 8: { return 0.0; } - case 9: { return 1.0; } - case 10: { return 0.5; } - case 11: { return cb_hls(fg.rgb).x; } - case 12: { return cb_hls(fg.rgb).y; } - case 13: { return cb_hls(fg.rgb).z; } - case 14: { return cb_hls(bg.rgb).x; } - case 15: { return cb_hls(bg.rgb).y; } - case 16: { return cb_hls(bg.rgb).z; } - case 17: { return dot(fg.rgb, vec3(0.299, 0.587, 0.114)); } - case 18: { return dot(bg.rgb, vec3(0.299, 0.587, 0.114)); } - case 19: { return pos.x; } - case 20: { return pos.y; } - case 21: { return pos.z; } - case 22: { return uv.x; } - case 23: { return 1.0 - uv.y; } - case 24: { return 0.0; } - case 25: { return env_c.x; } - case 26: { return env_c.y; } - case 27: { return env_c.z; } - case 28: { return n.x; } - case 29: { return n.y; } - case 30: { return n.z; } - default: { return bg.r; } - } -} - -fn cb_combine(op: i32, a: f32, b: f32) -> f32 { - switch op { - case 0: { return a; } - case 1: { return b; } - case 2: { return 1.0 - a; } - case 3: { return 1.0 - b; } - case 4: { return a + b; } - case 5: { return a - b; } - case 6: { return a * b; } - case 7: { return select(a / b, 0.0, abs(b) <= 1e-5); } - case 8: { return min(a, b); } - case 9: { return max(a, b); } - case 10: { return 0.5 * (a + b); } - default: { return a; } - } -} - -@fragment -fn fs_mesh(in: VsOut) -> @location(0) vec4 { - let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); - let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap); - let dpdx_w = dpdx(in.world_pos); - let dpdy_w = dpdy(in.world_pos); - let duvdx = dpdx(uv_bump_xformed); - let duvdy = dpdy(uv_bump_xformed); - let duvdx_main = dpdx(uv_xformed); - let duvdy_main = dpdy(uv_xformed); - let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; - if (facing_away != BACK_PASS) { - discard; - } - - let env_mode = i32(u.env_rot_0.w + 0.5); - let cb_on = u.cb_flags.x > 0.5; - let v_dir = normalize(u.cam_pos.xyz - in.world_pos); - var n_surf = normalize(in.world_n); - if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { - n_surf = perturb_bump_normal( - n_surf, - dpdx_w, - dpdy_w, - duvdx, - duvdy, - uv_bump_xformed, - u.mat_fx.x, - u.mat_fx.y, - u.bump_off_wrap.z, - u.bump_params.x, - i32(u.bump_params.y + 0.5), - ); - } - - var base_straight = vec3(0.0); - var rgb_alpha = u.diffuse_col.a; - var out_alpha = rgb_alpha * u.mtl_params.x; - - if (env_mode == 1) { - // Standalone SphereMap shader: equirectangular/angular lookup along view ray. - let env_c = sample_sphere_map(-v_dir); - base_straight = env_c.rgb * u.diffuse_col.rgb; - rgb_alpha = env_c.a * u.diffuse_col.a; - out_alpha = rgb_alpha * u.mtl_params.x; - } else { - var col = u.diffuse_col; - var tex_col = vec4(1.0); - var uv_samp = uv_xformed; - var tex_straight = vec3(1.0); - if (u.flags.x > 0.5) { - if (u.dod.z > 0.5 && u.dod.w > 0.5) { - let tdims = vec2(textureDimensions(mat_tex)); - let canvas_px = vec2(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w); - uv_samp = (canvas_px - u.dod.xy) / tdims; - if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) { - discard; - } - } - tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); - if (u.mat_fx.z <= 0.5) { - tex_straight = select(vec3(0.0), tex_col.rgb / max(tex_col.a, 1e-5), tex_col.a > 1e-5); - } - col = select(tex_col, vec4(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; - } - // `rgb_alpha` is `tex_col.a * Diffuse.Opacity`; `Diffuse.Color.Alpha` (`u.mtl_params.x`) - // modulates output alpha without attenuating diffuse/specular RGB. - rgb_alpha = col.a; - out_alpha = rgb_alpha * u.mtl_params.x; - if (env_mode == 0 && !cb_on && out_alpha <= 0.002) { - discard; - } - - let albedo = tex_straight * u.diffuse_col.rgb; - if (env_mode == 2 && u.refl_tint.w < 0.5) { - base_straight = vec3(0.0); - rgb_alpha = 0.0; - out_alpha = 0.0; - } else if (u.flags.y > 0.5) { - let tframe = compute_tangent_frame(n_surf, dpdx_w, dpdy_w, duvdx_main, duvdy_main); - let spec_rgb = u.specular_col.rgb; - 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; - let n_dir = i32(u.light_counts.z + 0.5); - for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) { - if (i >= n_dir) { break; } - let l = normalize(u.dir_to_light[i].xyz); - lit = lit + eval_light_contrib(n_surf, tframe.t, tframe.b, v_dir, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0); - } - - let n_pt = i32(u.light_counts.x + 0.5); - 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); - var occ = 0.0; - if (u.light_counts.w > 0.5) { - occ = point_shadow_occlusion(i, in.world_pos, n_surf, u.point_pos[i].xyz); - } - lit = lit + eval_light_contrib( - n_surf, tframe.t, tframe.b, v_dir, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, - 1.0 - shadow.point[i].y * occ, 1.0 - occ, - ); - } - - let n_sp = i32(u.light_counts.y + 0.5); - 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); - let l_dir = to_l / dist; - let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz)); - let cos_inner = u.spot_pos[i].w; - 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) * cone; - lit = lit + eval_light_contrib(n_surf, tframe.t, tframe.b, v_dir, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0); - } - } - base_straight = lit; - } else { - base_straight = albedo * u.uv_off_wrap.w; - } - - if (env_mode == 2) { - let r_dir = reflect(-v_dir, n_surf); - let refl_c = sample_sphere_map(r_dir); - let strength_var = i32(u.env_angles.z + 0.5); - var refl_str = clamp(u.env_angles.w, 0.0, 1.0); - if (strength_var != 0) { - let cos_nv = clamp(dot(n_surf, v_dir), 0.0, 1.0); - let f_ang = pow(1.0 - cos_nv, max(u.refl_params.z, 1e-4)); - refl_str = clamp(mix(u.refl_params.y, u.refl_params.x, f_ang), 0.0, 1.0); - } - var under_rgb = base_straight; - var under_a = rgb_alpha; - if (rgb_alpha < 0.999 && u.refl_params.w > 0.01 && u.env_rot_2.w > 0.5 && u.refl_tint.w > 0.5) { - let eta = 1.0 / max(u.refl_params.w, 0.01); - var refr_dir = refract(-v_dir, n_surf, eta); - if (dot(refr_dir, refr_dir) < 1e-5) { - refr_dir = r_dir; - } - let refr_c = sample_sphere_map(refr_dir); - under_rgb = mix(refr_c.rgb * u.refract_tint.rgb, base_straight, rgb_alpha); - under_a = clamp(max(rgb_alpha, refr_c.a * (1.0 - rgb_alpha)), 0.0, 1.0); - } - let under_premul = under_rgb * under_a; - let refl_a = refl_str * refl_c.a; - let out_premul = under_premul * (1.0 - refl_str) + refl_c.rgb * refl_a; - let final_a = clamp(under_a * (1.0 - refl_str) + refl_a, 0.0, 1.0); - base_straight = select(vec3(0.0), out_premul / max(final_a, 1e-5), final_a > 1e-5); - rgb_alpha = final_a; - out_alpha = clamp(out_alpha * (1.0 - refl_str) + refl_a, 0.0, 1.0); - } - } - - if (cb_on) { - let bg_c = vec4(base_straight, out_alpha); - var fg_c = u.cb_fg_col; - if (u.cb_flags.z > 1.5) { - let fg_raw = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv_xformed, u.bump_off_wrap.z), 0.0); - let fg_s = select(vec3(0.0), fg_raw.rgb / max(fg_raw.a, 1e-5), fg_raw.a > 1e-5); - fg_c = vec4(fg_s * u.cb_fg_col.rgb, fg_raw.a * u.cb_fg_col.a); - } - let cspace = i32(u.cb_flags.y + 0.5); - var c_pos = in.world_pos; - var c_n = n_surf; - if (cspace == 0) { - c_pos = in.local_pos; - let ln_len = length(in.local_n); - c_n = select(vec3(0.0, 0.0, 1.0), in.local_n / ln_len, ln_len > 1e-5); - } else if (cspace == 2) { - c_pos = (u.view * vec4(in.world_pos, 1.0)).xyz; - let en = (u.view * vec4(n_surf, 0.0)).xyz; - let elen = length(en); - c_n = select(vec3(0.0, 0.0, 1.0), en / elen, elen > 1e-5); - } - let env_c = reflect(-v_dir, n_surf); - let r_out = cb_combine(i32(u.cb_ops.x + 0.5), cb_operand(i32(u.cb_ops_a.x + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.x + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); - let g_out = cb_combine(i32(u.cb_ops.y + 0.5), cb_operand(i32(u.cb_ops_a.y + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.y + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); - let b_out = cb_combine(i32(u.cb_ops.z + 0.5), cb_operand(i32(u.cb_ops_a.z + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.z + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); - let a_out = cb_combine(i32(u.cb_ops.w + 0.5), cb_operand(i32(u.cb_ops_a.w + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.w + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); - let clamped_a = clamp(a_out, 0.0, 1.0); - if (clamped_a <= 0.002) { - discard; - } - return vec4(clamp(vec3(r_out, g_out, b_out) * clamped_a, vec3(0.0), vec3(1.0)), clamped_a); - } - - if (out_alpha <= 0.002) { - discard; - } - return vec4(clamp(base_straight * rgb_alpha, vec3(0.0), vec3(1.0)), out_alpha); -} - -@fragment -fn fs_normal(in: VsOut) -> @location(0) vec4 { - let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); - let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap); - let dpdx_w = dpdx(in.world_pos); - let dpdy_w = dpdy(in.world_pos); - let duvdx = dpdx(uv_bump_xformed); - let duvdy = dpdy(uv_bump_xformed); - let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; - if (facing_away != BACK_PASS) { - discard; - } - - var col = u.diffuse_col; - if (u.flags.x > 0.5) { - var uv_samp = uv_xformed; - if (u.dod.z > 0.5 && u.dod.w > 0.5) { - let tdims = vec2(textureDimensions(mat_tex)); - let canvas_px = vec2(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w); - uv_samp = (canvas_px - u.dod.xy) / tdims; - if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) { - discard; - } - } - let tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); - col = select(tex_col, vec4(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; - } - let out_alpha = col.a * u.mtl_params.x; - if (i32(u.env_rot_0.w + 0.5) == 0 && u.cb_flags.x < 0.5 && out_alpha <= 0.002) { - discard; - } - - let nlen = length(in.world_n); - var n = select(vec3(0.0, 0.0, 1.0), in.world_n / nlen, nlen > 1e-5); - if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { - n = perturb_bump_normal( - n, - dpdx_w, - dpdy_w, - duvdx, - duvdy, - uv_bump_xformed, - u.mat_fx.x, - u.mat_fx.y, - u.bump_off_wrap.z, - u.bump_params.x, - i32(u.bump_params.y + 0.5), - ); - } - return vec4(n, 0.0); -} -"#; +pub(super) const SHADER_3D: &str = include_str!("mesh.wgsl"); diff --git a/crates/engine/src/scene3d/surface_fx.wgsl b/crates/engine/src/scene3d/surface_fx.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..3a52ae9091d3ea021fe0f2e12dd9bae2c912428a --- /dev/null +++ b/crates/engine/src/scene3d/surface_fx.wgsl @@ -0,0 +1,232 @@ +struct SurfaceFx { + proc_a: vec4, + proc_b: vec4, + layer: vec4, + layer_col: vec4, + layer_spec: vec4, + layer_mtl: vec4, + pbr: vec4, + pbr_spec: vec4, + pbr_layers: vec4, + sheen: vec4, + emission: vec4, + fog: vec4, + fog_col: vec4, + env: vec4, + lut: array, 16>, +}; + +fn sfx_lut(t: f32) -> vec4 { + let x = clamp(t, 0.0, 1.0) * 15.0; + let i = min(u32(x), 14u); + return mix(u.sfx.lut[i], u.sfx.lut[i + 1u], x - f32(i)); +} + +// `TexGradient` position along the gradient. Types measure from the UVW origin; Linear, Reflect +// and Cross depend on W alone, which every primitive leaves at 0. +fn gradient_t(uv_up: vec2) -> f32 { + let kind = i32(u.sfx.proc_a.y + 0.5); + var t = 0.5; + if (kind == 1 || kind == 3) { + t = 0.0; + } else if (kind == 2) { + t = max(abs(uv_up.x), abs(uv_up.y)); + } else if (kind == 4) { + t = length(uv_up); + } + t = (t - u.sfx.proc_a.w - 0.5) / u.sfx.proc_a.z + 0.5; + let repeat = i32(u.sfx.proc_b.x + 0.5); + if (repeat == 1) { + t = fract(t); + } else if (repeat == 2) { + t = 1.0 - abs(fract(t * 0.5) * 2.0 - 1.0); + } + return t; +} + +// `FastNoiseTexture3D`: Seethe is the lattice Z for every octave and octave weights 0.5^i are +// normalised to sum to 2 (4 for Discontinuous). Contrast scales about 0 after Inverted. +fn noise_value(uv_up: vec2) -> f32 { + let detail = clamp(u.sfx.proc_a.y, 0.0, 10.0); + let disc = u.sfx.proc_b.w > 0.5; + let p = uv_up * (2.0 * u.sfx.proc_a.z); + let full = i32(floor(detail)); + let frac_w = detail - f32(full); + var sum = 0.0; + var norm = 0.0; + var amp = 1.0; + var scale = 1.0; + for (var i = 0; i <= full; i = i + 1) { + let w = select(amp, amp * frac_w, i == full); + if (w > 0.0) { + let n = simplex3d(vec3(p * scale, u.sfx.proc_a.w)); + sum = sum + w * select(n, abs(n), disc); + norm = norm + w; + } + amp = amp * 0.5; + scale = scale * 2.0; + } + let avg = select(0.0, sum / norm, norm > 0.0); + var val = select(0.5 + 2.0 * avg, 4.0 * avg, disc); + if (u.sfx.proc_b.z > 0.5) { + val = 1.0 - val; + } + return clamp(val * u.sfx.proc_b.x + u.sfx.proc_b.y, 0.0, 1.0); +} + +// Premultiplied colour of the procedural source `proc_a.x`; `tex` is the bound texture or white. +fn surface_proc(tex: vec4, uv_up: vec2, n: vec3, v: vec3) -> vec4 { + let kind = i32(u.sfx.proc_a.x + 0.5); + if (kind == 1) { + return sfx_lut(gradient_t(uv_up)); + } + if (kind == 2) { + return tex * noise_value(uv_up); + } + return sfx_lut(falloff_t(n, v, u.sfx.proc_a.y)); +} + +fn falloff_t(n: vec3, v: vec3, power: f32) -> f32 { + // Back faces see their inner side face-on, as Fusion shades them. + return 1.0 - pow(min(abs(dot(n, v)), 1.0), power); +} + +fn smith_g1(x: f32, a2: f32) -> f32 { + return 2.0 * x / max(x + sqrt(a2 + (1.0 - a2) * x * x), 1e-5); +} + +// GGX distribution times Smith shadowing over 4 N.V (alpha = roughness^2). +fn ggx_spec(nh: f32, nl: f32, nv: f32, rough: f32) -> f32 { + let a = max(rough * rough, 1e-3); + let a2 = a * a; + let dd = nh * nh * (a2 - 1.0) + 1.0; + return a2 / (3.14159265 * dd * dd) * smith_g1(nl, a2) * smith_g1(nv, a2) / (4.0 * nv); +} + +fn schlick(ior: f32, vh: f32) -> f32 { + let r0 = (ior - 1.0) / (ior + 1.0); + return r0 * r0 + (1.0 - r0 * r0) * pow(1.0 - vh, 5.0); +} + +// GGX/Smith directional albedo E(N.V, roughness): rows are roughness i/7, columns N.V j/7. +const GGX_ALBEDO: array = array( + 0.9990, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 0.8846, 0.9884, 0.9974, 0.9991, 0.9995, 0.9998, 0.9994, 0.9995, + 0.9178, 0.9005, 0.9486, 0.9736, 0.9833, 0.9878, 0.9907, 0.9924, + 0.9113, 0.8517, 0.8629, 0.8934, 0.9187, 0.9364, 0.9482, 0.9564, + 0.8688, 0.8191, 0.7954, 0.7947, 0.8061, 0.8227, 0.8396, 0.8548, + 0.8011, 0.7525, 0.7125, 0.6876, 0.6745, 0.6704, 0.6722, 0.6778, + 0.7090, 0.6530, 0.6019, 0.5623, 0.5317, 0.5080, 0.4897, 0.4758, + 0.6010, 0.5370, 0.4774, 0.4296, 0.3905, 0.3580, 0.3304, 0.3069, +); + +fn ggx_albedo(nv: f32, rough: f32) -> f32 { + let x = clamp(nv, 0.0, 1.0) * 7.0; + let y = clamp(rough, 0.0, 1.0) * 7.0; + let i = min(u32(x), 6u); + let j = min(u32(y), 6u); + let row0 = mix(GGX_ALBEDO[j * 8u + i], GGX_ALBEDO[j * 8u + i + 1u], x - f32(i)); + let row1 = mix(GGX_ALBEDO[j * 8u + i + 8u], GGX_ALBEDO[j * 8u + i + 9u], x - f32(i)); + return mix(row0, row1, y - f32(j)); +} + +// `MtlPBRUber`: GGX specular with Schlick Fresnel whose F0 blends from the IOR reflectance toward +// the base colour by metalness, scaled by 1 + F0 (1/E - 1) for the energy single scattering +// loses; a Charlie sheen lobe; and a GGX coat whose Fresnel dims everything beneath it. +fn pbr_uber_light( + n: vec3, + v: vec3, + l: vec3, + light_rgb: vec3, + albedo: vec3, + diffuse_vis: f32, + spec_vis: f32, +) -> vec3 { + let nl = max(dot(n, l), 0.0); + let nv = max(dot(n, v), 1e-3); + let h = normalize(l + v); + let nh = max(dot(n, h), 0.0); + let vh = max(dot(v, h), 0.0); + let metal = clamp(u.sfx.pbr.x, 0.0, 1.0); + let r0 = (u.sfx.pbr.z - 1.0) / (u.sfx.pbr.z + 1.0); + let f0 = mix(vec3(r0 * r0), albedo, metal); + let fres = f0 + (vec3(1.0) - f0) * pow(1.0 - vh, 5.0); + let diffuse = (1.0 - metal) * (vec3(1.0) - u.sfx.pbr.w * fres) * albedo * (u.sfx.pbr_spec.w * nl / 3.14159265); + let multi = vec3(1.0) + f0 * (1.0 / ggx_albedo(nv, u.sfx.pbr.y) - 1.0); + var spec = u.sfx.pbr_spec.rgb * fres * multi * (u.sfx.pbr.w * ggx_spec(nh, nl, nv, u.sfx.pbr.y)); + let inv_sheen = 1.0 / max(u.sfx.sheen.w * u.sfx.sheen.w, 1e-3); + let sin_h = sqrt(max(1.0 - nh * nh, 0.0)); + let charlie = (2.0 + inv_sheen) * pow(sin_h, inv_sheen) / 6.2831853; + spec = spec + u.sfx.sheen.rgb * (u.sfx.pbr_layers.w * charlie * nl / (4.0 * (nl + nv - nl * nv))); + let coat_f = u.sfx.pbr_layers.x * schlick(u.sfx.pbr_layers.z, vh); + let coat = coat_f * ggx_spec(nh, nl, nv, u.sfx.pbr_layers.y); + return light_rgb * ((diffuse * diffuse_vis + spec * spec_vis) * (1.0 - coat_f) + coat * spec_vis); +} + +// `Fog3D` over the lit colour: eye depth, or eye distance when Radial. +fn apply_fog(c: vec3, world_pos: vec3) -> vec3 { + let kind = i32(u.sfx.fog.x + 0.5); + if (kind == 0) { + return c; + } + let eye = (u.view * vec4(world_pos, 1.0)).xyz; + let d = select(-eye.z, length(eye), u.sfx.fog_col.w > 0.5); + var f = exp(-u.sfx.fog.w * d); + if (kind == 1) { + f = (u.sfx.fog.z - d) / max(u.sfx.fog.z - u.sfx.fog.y, 1e-5); + } else if (kind == 3) { + f = exp(-(u.sfx.fog.w * d) * (u.sfx.fog.w * d)); + } + f = clamp(f, 0.0, 1.0); + return c * f + u.sfx.fog_col.rgb * (1.0 - f); +} + +// World direction in the environment's coordinate system (`env.x`: 1 model, 2 camera). +fn env_space(d: vec3) -> vec3 { + let space = i32(u.sfx.env.x + 0.5); + if (space == 1) { + // The adjugate is the inverse up to a positive scale, which the caller normalises away. + return transpose(normal_matrix(u.model)) * d; + } + if (space == 2) { + return (u.view * vec4(d, 0.0)).xyz; + } + return d; +} + +// `CubeMap` texture coordinates (V down) of direction `d`: `mode` 2 = vertical cross, 3 = +// horizontal cross, 4 = one face image. Crosses sit at the image's bottom-left corner. +fn cube_uv(d: vec3, mode: i32, dims: vec2) -> vec2 { + let a = abs(d); + let horizontal = mode == 3; + let mid = select(2.0, 1.0, horizontal); + var st: vec2; + var tile: vec2; + if (a.x >= a.y && a.x >= a.z) { + let s = vec2(d.z, d.y) / a.x * 0.5 + 0.5; + st = select(vec2(1.0 - s.x, s.y), s, d.x > 0.0); + tile = vec2(select(2.0, 0.0, d.x > 0.0), mid); + } else if (a.y >= a.z) { + let s = vec2(d.x, d.z) / a.y * 0.5 + 0.5; + st = select(vec2(1.0 - s.x, s.y), vec2(1.0) - s, d.y > 0.0); + tile = vec2(1.0, mid + select(-1.0, 1.0, d.y > 0.0)); + } else { + let s = vec2(d.x, d.y) / a.z * 0.5 + 0.5; + if (d.z > 0.0) { + st = vec2(1.0 - s.x, s.y); + tile = vec2(1.0, mid); + } else if (horizontal || mode == 4) { + st = s; + tile = vec2(3.0, 1.0); + } else { + st = vec2(1.0) - s; + tile = vec2(1.0, 0.0); + } + } + if (mode == 4) { + return vec2(st.x, 1.0 - st.y); + } + let face = select(min(dims.x / 3.0, dims.y / 4.0), min(dims.x / 4.0, dims.y / 3.0), horizontal); + let uv_up = (tile + st) * face / dims; + return vec2(uv_up.x, 1.0 - uv_up.y); +} diff --git a/crates/engine/src/scene3d/textures.rs b/crates/engine/src/scene3d/textures.rs new file mode 100644 index 0000000000000000000000000000000000000000..670aac13084fdeb605c57ee4dbb1b99fbcbb6d91 --- /dev/null +++ b/crates/engine/src/scene3d/textures.rs @@ -0,0 +1,168 @@ +//! Procedural and environment 3D textures: `TexGradient`, `FastNoiseTexture3D`, `SphereMap` and +//! `CubeMap`. + +use super::collect::{euler_matrix, ResolvedMaterial}; +use super::fx::{gradient_lut, proc_kind, SurfaceFx}; +use super::materials::{flat, Resolve}; +use super::MaterialFx; +use model::{Comp, ExprEngine, Node}; + +pub(super) fn tex_gradient(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> ResolvedMaterial { + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + let kind = match n.static_str("GradientType") { + Some("Reflect") => 1.0, + Some("Square") => 2.0, + Some("Cross") => 3.0, + Some("Radial") => 4.0, + _ => 0.0, + }; + let repeat = match n.static_str("Repeat") { + Some("Repeat") => 1.0, + Some("Ping-Pong") => 2.0, + _ => 0.0, + }; + let scale = f("Scale", 1.0); + let mut mat = flat([1.0; 4]); + mat.fx.sfx.proc_a = [proc_kind::GRADIENT, kind, if scale.abs() < 1e-6 { 1e-6 } else { scale }, f("Offset", 0.0)]; + mat.fx.sfx.proc_b = [repeat, 0.0, 0.0, 0.0]; + mat.fx.sfx.lut = gradient_lut(comp.eval_gradient(n, "Gradient", time), [[0.0, 0.0, 0.0, 1.0], [1.0; 4]]); + mat +} + +/// `FastNoiseTexture3D` over mesh UVW; `ThreeD` output differs only along W, which primitives +/// leave at 0. A `SourceMaterial` texture is scaled by the noise. +pub(super) fn fast_noise(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; + let source = n.connected_node("SourceMaterial").and_then(|s| comp.find_node(s)).map(&mut *resolve); + let mut mat = flat([1.0; 4]); + if let Some(src) = source { + mat.tex_node = src.tex_node; + mat.fx.uv = src.fx.uv; + mat.fx.uv_wrap = src.fx.uv_wrap; + } + let seethe = f("Seethe", 1.0) + f("SeetheRate", 0.0) * time as f32 * 0.1; + mat.fx.sfx.proc_a = [proc_kind::NOISE, f("Detail", 2.0), f("XScale", 1.0), seethe]; + mat.fx.sfx.proc_b = [f("Contrast", 1.0), f("Brightness", 0.0), f("Invert", 0.0), f("Discontinuous", 0.0)]; + mat +} + +/// Column-major `R^T` of the node's `Rotate.*`: rotating the environment by `R` samples world +/// directions through its inverse. +fn env_rotation(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> [f32; 9] { + let rot_deg = ["X", "Y", "Z"].map(|a| comp.eval_number(n, &format!("Rotate.{a}"), time, 0.0, expr) as f32); + let r = euler_matrix(rot_deg, n.static_str("Rotate.RotOrder").unwrap_or("XYZ")); + [r[0], r[4], r[8], r[1], r[5], r[9], r[2], r[6], r[10]] +} + +fn env_material(tex_node: Option, env_rot: [f32; 9], env_map_mode: u32, coord_space: f32) -> ResolvedMaterial { + ResolvedMaterial { + tex_node, + fx: MaterialFx { + env_mode: 1, + env_map_mode, + env_tex_slot: u32::from(tex_node.is_some()), + env_rot, + sfx: SurfaceFx { env: [coord_space, 0.0, 0.0, 0.0], ..SurfaceFx::default() }, + ..MaterialFx::default() + }, + ..flat([1.0; 4]) + } +} + +/// `SphereMap` along the view ray. `StartAngle`/`EndAngle` have no effect in Fusion's renderer. +pub(super) fn sphere_map(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { + let tex = n.connected_node("Image").and_then(|s| comp.find_node(s)).and_then(|id| resolve(id).tex_node); + let map_mode = comp.eval_number(n, "MapMode", time, 0.0, expr).round().clamp(0.0, 1.0) as u32; + env_material(tex, env_rotation(comp, n, time, expr), map_mode, 0.0) +} + +/// `CubeMap` from a vertical (`Layout` 1) or horizontal (2) cross, or separate faces (0). +/// `Convention` does not change Fusion's render. +pub(super) fn cube_map(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { + let env_rot = env_rotation(comp, n, time, expr); + let layout = comp.eval_number(n, "Layout", time, 1.0, expr).round() as i32; + let (input, mode) = match layout { + // Two texture slots cannot hold six faces, so separate images bind the face that the + // rotated forward (-Z) view direction sees. + 0 => { + let fwd = [-env_rot[6], -env_rot[7], -env_rot[8]]; + let axis = (0..3).max_by(|&a, &b| fwd[a].abs().total_cmp(&fwd[b].abs())).unwrap_or(2); + let sign = if fwd[axis] > 0.0 { "Positive" } else { "Negative" }; + (format!("{sign}{}", ["X", "Y", "Z"][axis]), 4) + } + 2 => ("CrossImage".to_string(), 3), + _ => ("CrossImage".to_string(), 2), + }; + let tex = n.connected_node(&input).and_then(|s| comp.find_node(s)).and_then(|id| resolve(id).tex_node); + let coord_space = match n.static_str("CoordSystem") { + Some("Model") => 1.0, + Some("Camera") => 2.0, + _ => 0.0, + }; + env_material(tex, env_rot, mode, coord_space) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scene3d::collect::resolve_test_material as resolve_in; + + #[test] + fn tex_gradient_maps_type_repeat_and_default_ramp() { + let mat = resolve_in( + "X = TexGradient { Inputs = { GradientType = Input { Value = FuID { \"Radial\" }, }, + Repeat = Input { Value = FuID { \"Ping-Pong\" }, }, Scale = Input { Value = 2, }, Offset = Input { Value = 0.25, }, }, },", + ); + assert!(mat.unlit); + assert_eq!(mat.fx.sfx.proc_a, [proc_kind::GRADIENT, 4.0, 2.0, 0.25]); + assert_eq!(mat.fx.sfx.proc_b[0], 2.0); + assert_eq!(mat.fx.sfx.lut[0], [0.0, 0.0, 0.0, 1.0]); + assert_eq!(mat.fx.sfx.lut[15], [1.0; 4]); + } + + #[test] + fn fast_noise_reads_fbm_params_and_source() { + let mat = resolve_in( + "Img = Background { }, + X = FastNoiseTexture3D { Inputs = { Detail = Input { Value = 3, }, XScale = Input { Value = 4, }, + Contrast = Input { Value = 2, }, Invert = Input { Value = 1, }, Discontinuous = Input { Value = 1, }, + SourceMaterial = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", + ); + assert!(mat.tex_node.is_some()); + assert_eq!(mat.fx.sfx.proc_a, [proc_kind::NOISE, 3.0, 4.0, 1.0]); + assert_eq!(mat.fx.sfx.proc_b, [2.0, 0.0, 1.0, 1.0]); + } + + #[test] + fn sphere_map_ignores_start_end_angles_and_transposes_rotation() { + let mat = resolve_in( + "Img = Background { }, + X = SphereMap { Inputs = { [\"Rotate.Y\"] = Input { Value = 90, }, MapMode = Input { Value = 1, }, + StartAngle = Input { Value = 30, }, Image = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", + ); + assert_eq!((mat.fx.env_mode, mat.fx.env_map_mode, mat.fx.env_tex_slot), (1, 1, 1)); + // R_y(90) maps +X to -Z, so R^T's first column is (0, 0, 1). + let c0 = &mat.fx.env_rot[0..3]; + assert!(c0[0].abs() < 1e-6 && (c0[2] - 1.0).abs() < 1e-6, "{c0:?}"); + } + + #[test] + fn cube_map_layouts_and_separate_face_choice() { + let cross = resolve_in( + "Img = Background { }, + X = CubeMap { Inputs = { Layout = Input { Value = 2, }, CoordSystem = Input { Value = FuID { \"Model\" }, }, + CrossImage = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", + ); + assert_eq!((cross.fx.env_map_mode, cross.fx.env_tex_slot), (3, 1)); + assert_eq!(cross.fx.sfx.env[0], 1.0); + let faces = "PX = Background { }, NZ = Background { }, + X = CubeMap { Inputs = { Layout = Input { Value = 0, }, [\"Rotate.Y\"] = Input { Value = ROT, }, + PositiveX = Input { SourceOp = \"PX\", Source = \"Output\", }, + NegativeZ = Input { SourceOp = \"NZ\", Source = \"Output\", }, }, },"; + let front = resolve_in(&faces.replace("ROT", "0")); + let turned = resolve_in(&faces.replace("ROT", "90")); + assert_eq!(front.fx.env_map_mode, 4); + assert!(front.tex_node.is_some() && turned.tex_node.is_some()); + assert_ne!(front.tex_node, turned.tex_node, "rotating the map brings +X to the front"); + } +} -- 2.54.1