diff --git a/crates/engine/src/scene3d/collect.rs b/crates/engine/src/scene3d/collect.rs index 49b6d98114bcba6abefbeda894b721b4f82758da..802b842d8f68733ea73f46dd9eaf60db86e9b4f6 100644 --- a/crates/engine/src/scene3d/collect.rs +++ b/crates/engine/src/scene3d/collect.rs @@ -2,6 +2,10 @@ use std::sync::Arc; +use super::deform::{ + apply_bender_to_meshes, extract_replicate_points, replicate_meshes, Bender3DParams, BenderMode, + Replicate3DParams, MAX_SCENE_MESHES, +}; use super::fbx::load_mesh_cached; use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, smooth_normals, triangle_soup}; use super::math::{ @@ -117,7 +121,6 @@ fn collect_scene_inner( visited: &mut Vec, depth: usize, ) { - const MAX_SCENE_MESHES: usize = 16_384; if depth > 32 || node_id.0 >= comp.nodes.len() || meshes.len() >= MAX_SCENE_MESHES { return; } @@ -220,6 +223,156 @@ fn collect_scene_inner( collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); } } + "Bender3D" => { + let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { + return; + }; + let mode = match node.static_str("Bender") { + Some("Taper") => BenderMode::Taper, + Some("Twist") => BenderMode::Twist, + Some("Shear") => BenderMode::Shear, + Some("Bend") => BenderMode::Bend, + _ => { + let idx = comp + .eval_number( + node, + "BenderType", + time, + comp.eval_number(node, "Bender", time, 0.0, expr), + expr, + ) + .round() as i32; + match idx { + 1 => BenderMode::Taper, + 2 => BenderMode::Twist, + 3 => BenderMode::Shear, + _ => BenderMode::Bend, + } + } + }; + let params = Bender3DParams { + mode, + amount: comp.eval_number(node, "Amount", time, 0.0, expr) as f32, + axis: comp.eval_number(node, "Axis", time, 1.0, expr).round().clamp(0.0, 2.0) as u32, + angle_deg: comp.eval_number(node, "Angle", time, 0.0, expr) as f32, + center: comp.eval_number(node, "Center", time, 0.5, expr) as f32, + range_min: comp.eval_number(node, "RangeMin", time, 0.0, expr) as f32, + range_max: comp.eval_number(node, "RangeMax", time, 1.0, expr) as f32, + group: comp.eval_number(node, "Group", time, 0.0, expr) > 0.5, + }; + 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, + ); + apply_bender_to_meshes(&mut child_meshes, world, ¶ms); + let remaining = MAX_SCENE_MESHES.saturating_sub(meshes.len()); + meshes.extend(child_meshes.into_iter().take(remaining)); + } + "Replicate3D" => { + let Some(dest_id) = node.connected_node("Destination").and_then(|s| comp.find_node(s)) else { + return; + }; + let mut src_names: Vec<&String> = node + .inputs + .keys() + .filter(|k| k.starts_with("Input") && k["Input".len()..].chars().all(|c| c.is_ascii_digit()) && k.len() > "Input".len()) + .collect(); + src_names.sort_by_cached_key(|k| (k["Input".len()..].parse::().unwrap_or(0), k.to_string())); + let mut src_ids: Vec = src_names + .into_iter() + .filter_map(|k| node.connected_node(k).and_then(|s| comp.find_node(s))) + .collect(); + if src_ids.is_empty() { + if let Some(sid) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + src_ids.push(sid); + } + } + if src_ids.is_empty() { + return; + } + let mut dest_meshes = Vec::new(); + let mut dest_cams = Vec::new(); + let mut dest_lights = SceneLights::default(); + collect_scene_inner( + comp, + dest_id, + time, + expr, + mat4_identity(), + render_aspect, + ovr, + &mut dest_cams, + &mut dest_meshes, + &mut dest_lights, + visited, + depth + 1, + ); + let mut source_templates = Vec::with_capacity(src_ids.len()); + for sid in src_ids { + let mut tpl = Vec::new(); + collect_scene_inner( + comp, + sid, + time, + expr, + mat4_identity(), + render_aspect, + ovr, + cameras, + &mut tpl, + lights, + visited, + depth + 1, + ); + if !tpl.is_empty() { + source_templates.push(tpl); + } + } + if dest_meshes.is_empty() || source_templates.is_empty() { + return; + } + let step = comp.eval_number(node, "Step", time, 1.0, expr).round().max(1.0) as usize; + let remaining = MAX_SCENE_MESHES.saturating_sub(meshes.len()); + let dest_points = extract_replicate_points(&dest_meshes, step, remaining); + let f = |k: &str, d: f64| comp.eval_number(node, k, time, d, expr) as f32; + let scale_lock = f("ScaleLock", 1.0) > 0.5; + let sx = f("Scale.X", 1.0); + let (sy, sz) = if scale_lock { (sx, sx) } else { (f("Scale.Y", 1.0), f("Scale.Z", 1.0)) }; + let rot_order = node.static_str("RotationOrder").unwrap_or("XYZ"); + let base_xform = trs_matrix( + [f("Translate.X", 0.0), f("Translate.Y", 0.0), f("Translate.Z", 0.0)], + [f("Rotate.X", 0.0), f("Rotate.Y", 0.0), f("Rotate.Z", 0.0)], + rot_order, + [sx, sy, sz], + [f("Pivot.X", 0.0), f("Pivot.Y", 0.0), f("Pivot.Z", 0.0)], + ); + let j_scale_lock = f("JitterScaleLock", 1.0) > 0.5; + let jsx = f("JitterScale.X", 0.0); + let (jsy, jsz) = if j_scale_lock { (jsx, jsx) } else { (f("JitterScale.Y", 0.0), f("JitterScale.Z", 0.0)) }; + let params = Replicate3DParams { + random_input: node.static_str("InputMode") == Some("Random"), + alignment: comp.eval_number(node, "Alignment", time, 0.0, expr).round() as i32, + base_xform, + random_seed: comp.eval_number(node, "RandomSeed", time, 0.0, expr).round().max(0.0) as u64, + jitter_prob: f("JitterProbability", 1.0).clamp(0.0, 1.0), + jitter_translate: [f("JitterTranslate.X", 0.0), f("JitterTranslate.Y", 0.0), f("JitterTranslate.Z", 0.0)], + jitter_rotate: [f("JitterRotate.X", 0.0), f("JitterRotate.Y", 0.0), f("JitterRotate.Z", 0.0)], + jitter_pivot: [f("JitterPivot.X", 0.0), f("JitterPivot.Y", 0.0), f("JitterPivot.Z", 0.0)], + jitter_scale: [jsx, jsy, jsz], + }; + replicate_meshes(&dest_points, &source_templates, world, ¶ms, meshes); + } "Duplicate3D" => { let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { return; @@ -897,7 +1050,60 @@ fn resolve_material_inner( ..default_mat } } - "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" => { + "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 + } + } + "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" | "MtlWard" => { let diff_in = n .connected_node("Diffuse.Color.Material") .or_else(|| n.connected_node("MaterialInput")) @@ -921,15 +1127,23 @@ fn resolve_material_inner( comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32, ]; let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32; - let (spec_exp, spec_model, refractive_index, do_fresnel) = match n.kind.as_str() { + let (spec_exp, spec_model, refractive_index, do_fresnel, ward_spread_v) = match n.kind.as_str() { "MtlCookTorrance" => ( comp.eval_number(n, "Specular.Roughness", time, 0.6, expr).clamp(0.05, 1.0) as f32, SpecModel::CookTorrance, comp.eval_number(n, "Specular.RefractiveIndex", time, 2.0, expr).max(1.0) as f32, comp.eval_number(n, "Specular.DoFresnel", time, 1.0, expr) > 0.5, + 0.16, ), - "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong, 2.0, true), - _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn, 2.0, true), + "MtlWard" => ( + comp.eval_number(n, "Specular.SpreadU", time, 0.05, expr).clamp(0.0001, 2.0) as f32, + SpecModel::Ward, + 2.0, + true, + comp.eval_number(n, "Specular.SpreadV", time, 0.16, expr).clamp(0.0001, 2.0) as f32, + ), + "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong, 2.0, true, 0.16), + _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn, 2.0, true, 0.16), }; let spec_model = if comp.eval_number(n, "EnablePBRMaterial", time, 0.0, expr) > 0.5 { SpecModel::Pbr } else { spec_model }; @@ -942,6 +1156,7 @@ fn resolve_material_inner( diffuse_color_alpha: col_alpha, refractive_index, do_fresnel, + ward_spread_v, ..diff_mat.fx }; if let Some(bm) = bump_mat { @@ -955,6 +1170,7 @@ fn resolve_material_inner( diffuse_color_alpha: col_alpha, refractive_index, do_fresnel, + ward_spread_v, ..bm.fx }; } @@ -979,6 +1195,222 @@ fn resolve_material_inner( has_material_shader: true, } } + "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 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 bump_node = bg_mat.bump_node; + let mut fx = bg_mat.fx; + fx.bump_only = false; + + if let Some(bm) = bump_mat { + 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; + fx.bump_uv = bm.fx.uv; + fx.bump_wrap = bm.fx.uv_wrap; + 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 { + if tex_node.is_none() { + tex_node = Some(en); + 1 + } else { + bump_node = Some(en); + 2 + } + } 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, + } + } + "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") { + 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 + } _ => ResolvedMaterial { tex_node: Some(mid), ..default_mat @@ -1819,4 +2251,132 @@ mod tests { assert!((s_fx.diffuse_color_alpha - 0.25).abs() < 1e-5); assert!((meshes[2].diffuse_col[3] - 0.6).abs() < 1e-5); } + + #[test] + fn bender3d_and_replicate3d_scene_collection() { + let src = comp_src( + r#"Plane = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.SubdivisionWidth"] = Input { Value = 4, }, }, }, + Bent = Bender3D { Inputs = { + SceneInput = Input { SourceOp = "Plane", Source = "Output", }, + Bender = Input { Value = FuID { "Taper" }, }, + Amount = Input { Value = 0.5, }, + Axis = Input { Value = 1, }, + Center = Input { Value = 0.5, }, + }, }, + DestCube = Shape3D { Inputs = { + Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, + ["SurfaceCubeInputs.Width"] = Input { Value = 2.0, }, + ["SurfaceCubeInputs.SubdivisionWidth"] = Input { Value = 1, }, + }, }, + SrcA = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 1.0, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.0, }, }, }, + SrcB = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.0, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 1.0, }, }, }, + Rep = Replicate3D { Inputs = { + Destination = Input { SourceOp = "DestCube", Source = "Output", }, + Input1 = Input { SourceOp = "SrcA", Source = "Output", }, + Input2 = Input { SourceOp = "SrcB", Source = "Output", }, + Step = Input { Value = 2, }, + Alignment = Input { Value = 1, }, + ["Scale.X"] = Input { Value = 0.25, }, + }, }, + M = Merge3D { Inputs = { + SceneInput1 = Input { SourceOp = "Bent", Source = "Output", }, + SceneInput2 = Input { SourceOp = "Rep", Source = "Output", }, + }, },"#, + ); + let (_, meshes, _) = collect(&src, "M"); + // 1 deformed plane + 4 replicated instances (8 unique cube corners / Step 2). + assert_eq!(meshes.len(), 5); + assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::CustomMesh(v) if !v.is_empty())); + // Loop mode alternates Input1 (red) and Input2 (green). + assert!((meshes[1].diffuse_col[0] - 1.0).abs() < 1e-4 && meshes[1].diffuse_col[1].abs() < 1e-4); + assert!(meshes[2].diffuse_col[0].abs() < 1e-4 && (meshes[2].diffuse_col[1] - 1.0).abs() < 1e-4); + } + + #[test] + fn spheremap_ward_reflect_and_chanbool_material_resolution() { + let src = comp_src( + r#"EnvBg = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 8, }, }, }, + DiffBg = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, }, }, + SMap = SphereMap { Inputs = { + Image = Input { SourceOp = "EnvBg", Source = "Output", }, + ["Rotate.Y"] = Input { Value = 90.0, }, + StartAngle = Input { Value = 30.0, }, + EndAngle = Input { Value = 330.0, }, + }, }, + Ward = MtlWard { Inputs = { + ["Diffuse.Color.Material"] = Input { SourceOp = "DiffBg", Source = "Output", }, + ["Specular.SpreadU"] = Input { Value = 0.04, }, + ["Specular.SpreadV"] = Input { Value = 0.28, }, + }, }, + Refl = MtlReflect { Inputs = { + BackgroundMaterial = Input { SourceOp = "Ward", Source = "MaterialOutput", }, + ["Reflection.Color.Material"] = Input { SourceOp = "SMap", Source = "MaterialOutput", }, + ["Reflection.GlancingStrength"] = Input { Value = 0.9, }, + ["Reflection.FaceOnStrength"] = Input { Value = 0.15, }, + ["Reflection.Falloff"] = Input { Value = 3.0, }, + ["Refraction.RefractiveIndex.RGB"] = Input { Value = 1.5, }, + }, }, + FgBlinn = MtlBlinn { Inputs = { + ["Diffuse.Color.Red"] = Input { Value = 0.2, }, + ["Diffuse.Color.Green"] = Input { Value = 0.4, }, + ["Diffuse.Color.Blue"] = Input { Value = 0.6, }, + }, }, + CB = MtlChanBool { Inputs = { + BackgroundMaterial = Input { SourceOp = "Ward", Source = "MaterialOutput", }, + ForegroundMaterial = Input { SourceOp = "FgBlinn", Source = "MaterialOutput", }, + OperandAR = Input { Value = 4, }, + OperationR = Input { Value = 4, }, + OperandBR = Input { Value = 0, }, + CoordSpace = Input { Value = FuID { "World" }, }, + }, }, + S0 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "SMap", Source = "MaterialOutput", }, }, }, + S1 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Ward", Source = "MaterialOutput", }, }, }, + S2 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Refl", Source = "MaterialOutput", }, }, }, + S3 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "CB", Source = "MaterialOutput", }, }, }, + M = Merge3D { Inputs = { + SceneInput1 = Input { SourceOp = "S0", Source = "Output", }, + SceneInput2 = Input { SourceOp = "S1", Source = "Output", }, + SceneInput3 = Input { SourceOp = "S2", Source = "Output", }, + SceneInput4 = Input { SourceOp = "S3", Source = "Output", }, + }, },"#, + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + let env_id = comp.find_node("EnvBg").unwrap(); + let diff_id = comp.find_node("DiffBg").unwrap(); + let (_, meshes, _) = collect(&src, "M"); + assert_eq!(meshes.len(), 4); + + // SphereMap standalone + let fx0 = meshes[0].shape.split_fx().1; + 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; + assert_eq!(fx1.spec_model, SpecModel::Ward); + assert!((meshes[1].specular_exponent - 0.04).abs() < 1e-5); + assert!((fx1.ward_spread_v - 0.28).abs() < 1e-5); + + // MtlReflect with both diffuse texture (in mat_tex) and SphereMap (in bump_tex slot 2) + let fx2 = meshes[2].shape.split_fx().1; + assert_eq!(meshes[2].material_node, Some(diff_id)); + assert_eq!(meshes[2].bump_node, Some(env_id)); + assert_eq!(fx2.env_mode, 2); + assert_eq!(fx2.env_tex_slot, 2); + assert!((fx2.refl_glancing_strength - 0.9).abs() < 1e-5); + assert!((fx2.refl_face_on_strength - 0.15).abs() < 1e-5); + assert!((fx2.refl_falloff - 3.0).abs() < 1e-5); + assert!((fx2.refract_ior - 1.5).abs() < 1e-5); + + // MtlChanBool + let fx3 = meshes[3].shape.split_fx().1; + assert!(fx3.cb_enabled); + assert_eq!(fx3.cb_ops_a[0], 4); + 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); + } } diff --git a/crates/engine/src/scene3d/deform.rs b/crates/engine/src/scene3d/deform.rs new file mode 100644 index 0000000000000000000000000000000000000000..11a378d7d2d19ab0c01aeb57cbba85b671da1f77 --- /dev/null +++ b/crates/engine/src/scene3d/deform.rs @@ -0,0 +1,791 @@ +//! 3D mesh deformers (`Bender3D`) and vertex instancing (`Replicate3D`). + +use std::collections::HashMap; +use std::sync::Arc; + +use super::collect::mat4_inverse; +use super::math::{ + mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, +}; +use super::mesh::{build_shape_mesh, triangle_soup}; +use super::{Mat4, MeshInstance, ShapeKind, Vertex3D}; + +/// Maximum number of meshes allowed in a collected 3D scene (shared with `collect.rs`). +pub(super) const MAX_SCENE_MESHES: usize = 16_384; + +/// Deformation mode of `Bender3D`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BenderMode { + Bend, + Taper, + Twist, + Shear, +} + +/// Evaluated parameters for a `Bender3D` node. +#[derive(Clone, Copy, Debug)] +pub struct Bender3DParams { + pub mode: BenderMode, + pub amount: f32, + /// `0 = X`, `1 = Y`, `2 = Z`. + pub axis: u32, + /// Bend/shear plane angle in degrees around the bend axis. + pub angle_deg: f32, + /// Pivot fraction along the bounding box on the chosen axis (`0..=1`, default `0.5`). + pub center: f32, + /// Lower active range fraction along the chosen axis (`0..=1`, default `0.0`). + pub range_min: f32, + /// Upper active range fraction along the chosen axis (`0..=1`, default `1.0`). + pub range_max: f32, + /// When true, all child meshes are deformed together inside their shared bounding box. + pub group: bool, +} + +impl Default for Bender3DParams { + fn default() -> Self { + Self { + mode: BenderMode::Bend, + amount: 0.0, + axis: 1, + angle_deg: 0.0, + center: 0.5, + range_min: 0.0, + range_max: 1.0, + group: false, + } + } +} + +#[inline] +fn vec3_dot(a: [f32; 3], b: [f32; 3]) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +#[inline] +fn vec3_sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +#[inline] +fn vec3_cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { + [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ] +} + +#[inline] +fn vec3_norm(a: [f32; 3]) -> Option<[f32; 3]> { + let l = vec3_dot(a, a).sqrt(); + (l > 1e-8).then(|| [a[0] / l, a[1] / l, a[2] / l]) +} + +#[inline] +fn xform_point(m: Mat4, p: [f32; 3]) -> [f32; 3] { + [ + m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12], + m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13], + m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14], + ] +} + +#[inline] +fn xform_vector(m: Mat4, v: [f32; 3]) -> [f32; 3] { + [ + m[0] * v[0] + m[4] * v[1] + m[8] * v[2], + m[1] * v[0] + m[5] * v[1] + m[9] * v[2], + m[2] * v[0] + m[6] * v[1] + m[10] * v[2], + ] +} + +/// Transforms a surface normal by the cofactor matrix of `m` (inverse-transpose up to scale), +/// preserving outward orientation under non-uniform scale and mirroring. +#[inline] +fn xform_normal(m: Mat4, n: [f32; 3]) -> [f32; 3] { + let c0 = [m[0], m[1], m[2]]; + let c1 = [m[4], m[5], m[6]]; + let c2 = [m[8], m[9], m[10]]; + let sign = if vec3_dot(c0, vec3_cross(c1, c2)) >= 0.0 { 1.0 } else { -1.0 }; + let r0 = vec3_cross(c1, c2); + let r1 = vec3_cross(c2, c0); + let r2 = vec3_cross(c0, c1); + let out = [ + (r0[0] * n[0] + r1[0] * n[1] + r2[0] * n[2]) * sign, + (r0[1] * n[0] + r1[1] * n[1] + r2[1] * n[2]) * sign, + (r0[2] * n[0] + r1[2] * n[1] + r2[2] * n[2]) * sign, + ]; + 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`. +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]), + }; + 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, + ]; + (u, v, w) +} + +fn axis_bounds_of(verts: &[Vertex3D], w: [f32; 3]) -> Option<[f32; 2]> { + let mut mn = f32::INFINITY; + let mut mx = f32::NEG_INFINITY; + for v in verts { + let p = vec3_dot(v.pos, w); + mn = mn.min(p); + mx = mx.max(p); + } + (mn.is_finite() && mx.is_finite()).then_some([mn, mx]) +} + +/// Applies `Bender3D` deformation to `verts` in-place and recomputes smooth vertex normals. +pub fn deform_mesh_vertices( + verts: &mut [Vertex3D], + indices: &[u32], + params: &Bender3DParams, + shared_bounds: Option<[f32; 2]>, +) { + if verts.is_empty() || params.amount.abs() < 1e-6 { + return; + } + let (u, v, w) = bender_basis(params.axis, params.angle_deg); + let Some([min_w, max_w]) = shared_bounds.or_else(|| axis_bounds_of(verts, w)) else { + return; + }; + let extent = max_w - min_w; + if extent <= 1e-6 { + return; + } + let r_min_frac = params.range_min.clamp(0.0, 1.0); + let r_max_frac = params.range_max.clamp(r_min_frac, 1.0); + if (r_max_frac - r_min_frac) <= 1e-6 { + return; + } + let center_frac = params.center.clamp(0.0, 1.0); + let w0 = min_w + center_frac * extent; + 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 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) + } + BenderMode::Taper => { + let s = (1.0 + amount * 2.0 * t).max(0.0); + (pu * s, pv * s, pw, nu_old, nv_old, nw_old) + } + 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) + } + 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; + } + } +} + +/// Applies `Bender3D` to a slice of collected child meshes (either individually or as a group). +pub fn apply_bender_to_meshes( + meshes: &mut [MeshInstance], + bender_world: Mat4, + params: &Bender3DParams, +) { + if meshes.is_empty() || params.amount.abs() < 1e-6 { + return; + } + + if params.group { + let inv_bender = mat4_inverse(bender_world); + let (_, _, w_axis) = bender_basis(params.axis, params.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 rel = mat4_mul(inv_bender, m.world); + let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), 1.0); + 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 (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), 1.0); + 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, + }; + } + } +} + +/// World-space destination point + orthonormal TBN frame extracted for `Replicate3D`. +#[derive(Clone, Copy, Debug)] +pub struct ReplicatePoint { + pub pos: [f32; 3], + pub normal: [f32; 3], + pub tangent: [f32; 3], + pub bitangent: [f32; 3], +} + +/// Extracts deduplicated world-space vertex frames from destination meshes for `Replicate3D`. +pub fn extract_replicate_points( + dest_meshes: &[MeshInstance], + step: usize, + max_points: usize, +) -> Vec { + if dest_meshes.is_empty() || max_points == 0 { + return Vec::new(); + } + let stride = step.max(1); + let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64); + + struct Accum { + pos: [f32; 3], + normal: [f32; 3], + tangent: [f32; 3], + } + + let mut order: Vec<[i64; 3]> = Vec::new(); + let mut table: HashMap<[i64; 3], Accum> = HashMap::new(); + + for dm in dest_meshes { + let (verts, indices) = build_shape_mesh(dm.shape.base_shape(), 1.0); + if verts.is_empty() { + continue; + } + // Compute per-vertex tangents from triangles when available. + let mut tangents = vec![[0.0_f32; 3]; verts.len()]; + for tri in indices.chunks_exact(3) { + let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize); + if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() { + continue; + } + let e1 = vec3_sub(verts[i1].pos, verts[i0].pos); + let e2 = vec3_sub(verts[i2].pos, verts[i0].pos); + let du1 = verts[i1].uv[0] - verts[i0].uv[0]; + let dv1 = verts[i1].uv[1] - verts[i0].uv[1]; + let du2 = verts[i2].uv[0] - verts[i0].uv[0]; + let dv2 = verts[i2].uv[1] - verts[i0].uv[1]; + let det = du1 * dv2 - dv1 * du2; + let t_tri = if det.abs() > 1e-6 { + let inv = 1.0 / det; + [ + (e1[0] * dv2 - e2[0] * dv1) * inv, + (e1[1] * dv2 - e2[1] * dv1) * inv, + (e1[2] * dv2 - e2[2] * dv1) * inv, + ] + } else { + e1 + }; + for idx in [i0, i1, i2] { + tangents[idx][0] += t_tri[0]; + tangents[idx][1] += t_tri[1]; + tangents[idx][2] += t_tri[2]; + } + } + + for (vi, v) in verts.iter().enumerate() { + let wp = xform_point(dm.world, v.pos); + let wn = xform_normal(dm.world, v.normal); + let wt = xform_vector(dm.world, tangents[vi]); + let k = key(wp); + if let Some(acc) = table.get_mut(&k) { + acc.normal[0] += wn[0]; + acc.normal[1] += wn[1]; + acc.normal[2] += wn[2]; + acc.tangent[0] += wt[0]; + acc.tangent[1] += wt[1]; + acc.tangent[2] += wt[2]; + } else { + order.push(k); + table.insert(k, Accum { pos: wp, normal: wn, tangent: wt }); + } + } + } + + let mut out = Vec::with_capacity((order.len() / stride + 1).min(max_points)); + for (idx, k) in order.into_iter().enumerate() { + if idx % stride != 0 { + continue; + } + if out.len() >= max_points { + break; + } + let acc = &table[&k]; + let n = vec3_norm(acc.normal).unwrap_or([0.0, 0.0, 1.0]); + // Gram-Schmidt orthogonalize tangent against normal; fallback when degenerate. + let t_proj = [ + acc.tangent[0] - n[0] * vec3_dot(acc.tangent, n), + acc.tangent[1] - n[1] * vec3_dot(acc.tangent, n), + acc.tangent[2] - n[2] * vec3_dot(acc.tangent, n), + ]; + let t = vec3_norm(t_proj).unwrap_or_else(|| { + let up = if n[1].abs() > 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; + vec3_norm(vec3_cross(up, n)).unwrap_or([1.0, 0.0, 0.0]) + }); + let b = vec3_norm(vec3_cross(n, t)).unwrap_or([0.0, 1.0, 0.0]); + out.push(ReplicatePoint { pos: acc.pos, normal: n, tangent: t, bitangent: b }); + } + out +} + +/// Builds the placement matrix for a destination point according to `Replicate3D.Alignment`: +/// - `0`: Not aligned (translation only) +/// - `1`: Aligned (aligns local `+Z` to destination vertex normal) +/// - `2`: TBN Aligned (aligns local X/Y/Z to destination vertex T/B/N frame) +pub fn replicate_alignment_matrix(pt: &ReplicatePoint, alignment: i32) -> Mat4 { + match alignment { + 1 => { + let z = pt.normal; + let up = if z[1].abs() > 0.99 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; + let x = vec3_norm(vec3_cross(up, z)).unwrap_or([1.0, 0.0, 0.0]); + let y = vec3_cross(z, x); + [ + x[0], x[1], x[2], 0.0, + y[0], y[1], y[2], 0.0, + z[0], z[1], z[2], 0.0, + pt.pos[0], pt.pos[1], pt.pos[2], 1.0, + ] + } + 2 => { + let x = pt.tangent; + let y = pt.bitangent; + let z = pt.normal; + [ + x[0], x[1], x[2], 0.0, + y[0], y[1], y[2], 0.0, + z[0], z[1], z[2], 0.0, + pt.pos[0], pt.pos[1], pt.pos[2], 1.0, + ] + } + _ => mat4_translate(pt.pos[0], pt.pos[1], pt.pos[2]), + } +} + +/// Evaluated parameters for a `Replicate3D` node. +#[derive(Clone, Debug)] +pub struct Replicate3DParams { + pub random_input: bool, + /// `0 = Not aligned`, `1 = Aligned`, `2 = TBN Aligned`. + pub alignment: i32, + pub base_xform: Mat4, + pub random_seed: u64, + pub jitter_prob: f32, + pub jitter_translate: [f32; 3], + pub jitter_rotate: [f32; 3], + pub jitter_pivot: [f32; 3], + pub jitter_scale: [f32; 3], +} + +fn splitmix64_signed(mut x: u64) -> f32 { + x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + x ^= x >> 31; + ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5 +} + +fn splitmix64_u64(mut x: u64) -> u64 { + x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + x ^ (x >> 31) +} + +/// Instantiates `source_templates` (`Input1..InputN`) onto `dest_points` while honoring +/// `MAX_SCENE_MESHES` so large destination meshes never exhaust memory. +pub fn replicate_meshes( + dest_points: &[ReplicatePoint], + source_templates: &[Vec], + node_world: Mat4, + params: &Replicate3DParams, + out_meshes: &mut Vec, +) { + if dest_points.is_empty() || source_templates.is_empty() { + return; + } + let has_jitter = params.jitter_translate.iter().any(|v| v.abs() > 1e-5) + || params.jitter_rotate.iter().any(|v| v.abs() > 1e-5) + || params.jitter_pivot.iter().any(|v| v.abs() > 1e-5) + || params.jitter_scale.iter().any(|v| v.abs() > 1e-5); + + for (idx, pt) in dest_points.iter().enumerate() { + if out_meshes.len() >= MAX_SCENE_MESHES { + break; + } + let s = params + .random_seed + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add((idx as u64).wrapping_mul(1_442_695_040_888_963_407)); + let tpl_idx = if params.random_input { + (splitmix64_u64(s ^ 17) as usize) % source_templates.len() + } else { + idx % source_templates.len() + }; + let template = &source_templates[tpl_idx]; + if template.is_empty() { + continue; + } + + let place = replicate_alignment_matrix(pt, params.alignment); + let mut inst_m = mat4_mul(node_world, mat4_mul(place, params.base_xform)); + if has_jitter && (params.jitter_prob >= 0.9999 || (splitmix64_signed(s ^ 13) + 0.5) <= params.jitter_prob) { + let tx = splitmix64_signed(s ^ 1) * params.jitter_translate[0]; + let ty = splitmix64_signed(s ^ 2) * params.jitter_translate[1]; + let tz = splitmix64_signed(s ^ 3) * params.jitter_translate[2]; + let rx = (splitmix64_signed(s ^ 4) * params.jitter_rotate[0]).to_radians(); + let ry = (splitmix64_signed(s ^ 5) * params.jitter_rotate[1]).to_radians(); + let rz = (splitmix64_signed(s ^ 6) * params.jitter_rotate[2]).to_radians(); + let sx = (1.0 + splitmix64_signed(s ^ 7) * params.jitter_scale[0]).max(1e-4); + let sy = (1.0 + splitmix64_signed(s ^ 8) * params.jitter_scale[1]).max(1e-4); + let sz = (1.0 + splitmix64_signed(s ^ 9) * params.jitter_scale[2]).max(1e-4); + let px = splitmix64_signed(s ^ 10) * params.jitter_pivot[0]; + let py = splitmix64_signed(s ^ 11) * params.jitter_pivot[1]; + let pz = splitmix64_signed(s ^ 12) * params.jitter_pivot[2]; + let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))); + let jm = mat4_mul( + mat4_translate(tx + px, ty + py, tz + pz), + mat4_mul(rot, mat4_mul(mat4_scale(sx, sy, sz), mat4_translate(-px, -py, -pz))), + ); + inst_m = mat4_mul(inst_m, jm); + } + + for src_m in template { + if out_meshes.len() >= MAX_SCENE_MESHES { + break; + } + let mut cloned = src_m.clone(); + cloned.world = mat4_mul(inst_m, src_m.world); + out_meshes.push(cloned); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scene3d::math::mat4_identity; + use crate::scene3d::MaterialFx; + + fn dummy_mesh(shape: ShapeKind, world: Mat4) -> MeshInstance { + MeshInstance { + world, + shape: ShapeKind::WithMaterialFx { + inner: Box::new(shape), + fx: MaterialFx::default(), + }, + material_node: None, + bump_node: None, + text3d: None, + diffuse_col: [1.0, 1.0, 1.0, 1.0], + specular_col: [1.0, 1.0, 1.0], + specular_intensity: 1.0, + specular_exponent: 50.0, + affected_by_lights: true, + casts_shadow: true, + receives_shadows: true, + flip_normals: false, + displace: None, + } + } + + #[test] + fn bender_bend_curves_plane_and_updates_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, + }; + 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 + })); + } + + #[test] + fn bender_taper_twist_shear_and_range_clamp() { + 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 { + mode: BenderMode::Taper, + amount: 0.5, + axis: 1, + center: 0.5, + ..Default::default() + }, None); + let max_x_top = v_taper.iter().filter(|v| v.pos[1] > 0.9).map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); + let max_x_bot = v_taper.iter().filter(|v| v.pos[1] < -0.9).map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); + 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 { + mode: BenderMode::Twist, + amount: 0.5, + axis: 1, + center: 0.5, + ..Default::default() + }, None); + let max_z = v_twist.iter().map(|v| v.pos[2].abs()).fold(0.0_f32, f32::max); + 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 { + mode: BenderMode::Shear, + amount: 1.0, + axis: 1, + center: 0.5, + range_min: 0.5, + 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]; + 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}"); + } + + #[test] + fn bender_group_mode_deforms_multiple_meshes_in_shared_bounds() { + let mut meshes = vec![ + dummy_mesh(ShapeKind::Cube { width: 1.0, sub: 2, faces: 0b11_1111 }, mat4_translate(0.0, -1.0, 0.0)), + dummy_mesh(ShapeKind::Cube { width: 1.0, sub: 2, faces: 0b11_1111 }, mat4_translate(0.0, 1.0, 0.0)), + ]; + apply_bender_to_meshes(&mut meshes, mat4_identity(), &Bender3DParams { + mode: BenderMode::Taper, + amount: 0.5, + axis: 1, + center: 0.5, + group: true, + ..Default::default() + }); + let ShapeKind::CustomMesh(v0) = meshes[0].shape.base_shape() else { panic!("expected custom mesh") }; + let ShapeKind::CustomMesh(v1) = meshes[1].shape.base_shape() else { panic!("expected custom mesh") }; + let bot_w = v0.iter().map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); + let top_w = v1.iter().map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); + assert!(top_w > bot_w * 1.4, "group taper should widen upper cube relative to lower cube: {top_w} vs {bot_w}"); + } + + #[test] + fn replicate_extracts_unique_vertices_aligns_normals_and_respects_cap() { + // 1x1 subdivided cube has 8 unique corner vertices (36 triangle-soup vertices across 6 faces). + let dest = vec![dummy_mesh(ShapeKind::Cube { width: 2.0, sub: 1, faces: 0b11_1111 }, mat4_identity())]; + let pts = extract_replicate_points(&dest, 1, MAX_SCENE_MESHES); + assert_eq!(pts.len(), 8, "cube with sub=1 should deduplicate to 8 corner points"); + for pt in &pts { + // Corner normal should point radially outward along pos. + assert!(vec3_dot(pt.pos, pt.normal) > 0.5, "corner normal should point outward: {pt:?}"); + } + + let src_tpl = vec![vec![dummy_mesh(ShapeKind::Plane { width: 0.2, height: 0.2, sub_w: 1, sub_h: 1 }, mat4_identity())]]; + let mut out = Vec::new(); + let params = Replicate3DParams { + random_input: false, + alignment: 1, + base_xform: mat4_identity(), + random_seed: 0, + jitter_prob: 1.0, + jitter_translate: [0.0; 3], + jitter_rotate: [0.0; 3], + jitter_pivot: [0.0; 3], + jitter_scale: [0.0; 3], + }; + replicate_meshes(&pts, &src_tpl, mat4_identity(), ¶ms, &mut out); + assert_eq!(out.len(), 8); + // Aligned mode aligns local +Z (column 2 of world) with destination normal. + let z_col = [out[0].world[8], out[0].world[9], out[0].world[10]]; + assert!(vec3_dot(z_col, pts[0].normal) > 0.99, "aligned +Z should match vertex normal"); + + // Cap enforcement: pre-fill close to MAX_SCENE_MESHES and verify we never exceed it. + let mut capped = vec![dummy_mesh(ShapeKind::Plane { width: 0.1, height: 0.1, sub_w: 1, sub_h: 1 }, mat4_identity()); MAX_SCENE_MESHES - 3]; + replicate_meshes(&pts, &src_tpl, mat4_identity(), ¶ms, &mut capped); + assert_eq!(capped.len(), MAX_SCENE_MESHES, "must strictly enforce MAX_SCENE_MESHES cap"); + } +} diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index 7458db5ec3ae5fcf3e9c3674d32f7069c3de354d..29a07c1ef4f0d99906b1631cb51941bc22e32706 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -7,6 +7,7 @@ //! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection. mod collect; +mod deform; mod fbx; mod math; mod mesh; @@ -283,7 +284,7 @@ impl UvAffine { } /// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for -/// `Blinn`/`Phong` and the roughness for `CookTorrance`. +/// `Blinn`/`Phong`, the roughness for `CookTorrance`, and `SpreadU` for `Ward`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum SpecModel { #[default] @@ -292,6 +293,8 @@ pub enum SpecModel { CookTorrance, /// `EnablePBRMaterial`: diffuse-only lights at 1/pi, no specular lobe. Pbr, + /// Anisotropic Ward BRDF (`MtlWard`). + Ward, } #[derive(Clone, Copy, Debug, PartialEq)] @@ -323,6 +326,40 @@ pub struct MaterialFx { pub refractive_index: f32, /// `MtlCookTorrance` `Specular.DoFresnel` toggle. pub do_fresnel: bool, + /// `MtlWard` `Specular.SpreadV` anisotropic roughness along V. + 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`. + 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, + pub refl_glancing_strength: f32, + pub refl_face_on_strength: f32, + pub refl_falloff: f32, + pub refl_tint: [f32; 3], + pub refl_has_bg: bool, + pub refract_ior: f32, + pub refract_tint: [f32; 3], + /// `MtlChanBool` per-channel boolean evaluation. + pub cb_enabled: bool, + 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, } impl Default for MaterialFx { @@ -345,6 +382,29 @@ impl Default for MaterialFx { diffuse_color_alpha: 1.0, refractive_index: 2.0, do_fresnel: true, + ward_spread_v: 0.16, + env_mode: 0, + 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, + refl_face_on_strength: 0.0, + refl_falloff: 2.0, + refl_tint: [1.0, 1.0, 1.0], + refl_has_bg: true, + refract_ior: 1.333, + refract_tint: [1.0, 1.0, 1.0], + cb_enabled: false, + 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, } } } @@ -369,6 +429,37 @@ impl MaterialFx { self.diffuse_color_alpha.to_bits().hash(h); self.refractive_index.to_bits().hash(h); self.do_fresnel.hash(h); + self.ward_spread_v.to_bits().hash(h); + self.env_mode.hash(h); + self.env_map_mode.hash(h); + self.env_tex_slot.hash(h); + 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); + self.refl_face_on_strength.to_bits().hash(h); + self.refl_falloff.to_bits().hash(h); + for v in self.refl_tint { + v.to_bits().hash(h); + } + self.refl_has_bg.hash(h); + self.refract_ior.to_bits().hash(h); + for v in self.refract_tint { + v.to_bits().hash(h); + } + self.cb_enabled.hash(h); + 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); } } @@ -1437,12 +1528,16 @@ impl Scene3DRenderer { dir_to_light[di] = [dl.to_light[0], dl.to_light[1], dl.to_light[2], 0.0]; 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 uni = MeshUniform { mvp, model: m.world, + view, dod, flags: [ - if m.tex.is_some() { 1.0 } else { 0.0 }, + if use_diffuse_tex { 1.0 } else { 0.0 }, if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 }, m.specular_intensity, if m.flip_normals { 1.0 } else { 0.0 }, @@ -1463,13 +1558,45 @@ impl Scene3DRenderer { uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, if lighting_enabled && fx.per_light_unlit { lights.count.max(1) as f32 } else { 1.0 }], mat_fx: [fx.bump_scale, fx.bump_mode as f32, if fx.bump_only { 1.0 } else { 0.0 }, fx.spec_model as u32 as f32], bump_uv_xform: fx.bump_uv.m, - bump_off_wrap: [fx.bump_uv.t[0], fx.bump_uv.t[1], fx.bump_wrap as f32, if bump_src.is_some() { 1.0 } else { 0.0 }], + bump_off_wrap: [fx.bump_uv.t[0], fx.bump_uv.t[1], fx.bump_wrap as f32, if has_bump_tex { 1.0 } else { 0.0 }], bump_dod, bump_params: [fx.bump_clamp_z, fx.bump_channel as f32, 0.0, 0.0], mtl_params: [ fx.diffuse_color_alpha, fx.refractive_index, if fx.do_fresnel { 1.0 } else { 0.0 }, + fx.ward_spread_v, + ], + 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_params: [ + fx.refl_glancing_strength, + fx.refl_face_on_strength, + fx.refl_falloff, + fx.refract_ior, + ], + refl_tint: [ + fx.refl_tint[0], + fx.refl_tint[1], + fx.refl_tint[2], + if fx.refl_has_bg { 1.0 } else { 0.0 }, + ], + refract_tint: [fx.refract_tint[0], fx.refract_tint[1], fx.refract_tint[2], 0.0], + 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, ], point_pos, @@ -2617,4 +2744,218 @@ mod tests { let (tex_cached_off, _) = eng.evaluate(&make_comp("Perspective", 0, 0), comp_off.find_node("R").unwrap(), 0.0); assert!(tex_cached_off.aux.is_none()); } + + #[test] + fn mtl_ward_anisotropic_spread_u_vs_v_stretches_specular_highlight() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let mut render = |su: f32, sv: f32| -> Vec { + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ + Ward = MtlWard {{ Inputs = {{ + ["Diffuse.Color.Red"] = Input {{ Value = 0.0, }}, + ["Diffuse.Color.Green"] = Input {{ Value = 0.0, }}, + ["Diffuse.Color.Blue"] = Input {{ Value = 0.0, }}, + ["Specular.Intensity"] = Input {{ Value = 1.0, }}, + ["Specular.SpreadU"] = Input {{ Value = {su}, }}, + ["Specular.SpreadV"] = Input {{ Value = {sv}, }}, + }}, }}, + S = Shape3D {{ Inputs = {{ + Shape = Input {{ Value = FuID {{ "SurfaceSphereInputs" }}, }}, + ["SurfaceSphereInputs.Radius"] = Input {{ Value = 1.0, }}, + MaterialInput = Input {{ SourceOp = "Ward", Source = "MaterialOutput", }}, + }}, }}, + L = LightDirectional {{ Inputs = {{ Intensity = Input {{ Value = 2.0, }}, }}, }}, + Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 5.5, }}, }}, }}, + M = Merge3D {{ Inputs = {{ + SceneInput1 = Input {{ SourceOp = "S", Source = "Output", }}, + SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }}, + SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }}, + }}, }}, + R = Renderer3D {{ Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 64, }}, + ["RendererSoftware.LightingEnabled"] = Input {{ Value = 1, }}, + SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, + }}, }}, + }} }}"# + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); + eng.readback_rgba(&tex).unwrap() + }; + let horiz = render(0.45, 0.05); + let vert = render(0.05, 0.45); + let px_r = |buf: &[u8], x: usize, y: usize| buf[(y * 64 + x) * 4] as f32; + // Sample off-center along horizontal vs vertical axes from sphere center (32, 32). + let h_horiz = px_r(&horiz, 40, 32) + px_r(&horiz, 24, 32); + let h_vert = px_r(&horiz, 32, 40) + px_r(&horiz, 32, 24); + let v_horiz = px_r(&vert, 40, 32) + px_r(&vert, 24, 32); + let v_vert = px_r(&vert, 32, 40) + px_r(&vert, 32, 24); + assert!(h_horiz > h_vert + 5.0, "wide SpreadU should stretch highlight horizontally: h={h_horiz} v={h_vert}"); + assert!(v_vert > v_horiz + 5.0, "wide SpreadV should stretch highlight vertically: h={v_horiz} v={v_vert}"); + } + + #[test] + fn spheremap_and_mtl_reflect_fresnel_and_constant_strength() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let mut render_reflect = |strength_var: u8, face_on: f32, glancing: f32, rot_y: f32| -> Vec { + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ + Env = Background {{ Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 32, }}, + Type = Input {{ Value = FuID {{ "Horizontal" }}, }}, + TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 0.0, }}, TopLeftBlue = Input {{ Value = 0.0, }}, + TopRightRed = Input {{ Value = 0.0, }}, TopRightGreen = Input {{ Value = 0.0, }}, TopRightBlue = Input {{ Value = 1.0, }}, + }}, }}, + SMap = SphereMap {{ Inputs = {{ + Image = Input {{ SourceOp = "Env", Source = "Output", }}, + ["Rotate.Y"] = Input {{ Value = {rot_y}, }}, + }}, }}, + Dark = MtlBlinn {{ Inputs = {{ + ["Diffuse.Color.Red"] = Input {{ Value = 0.0, }}, + ["Diffuse.Color.Green"] = Input {{ Value = 0.0, }}, + ["Diffuse.Color.Blue"] = Input {{ Value = 0.0, }}, + ["Specular.Intensity"] = Input {{ Value = 0.0, }}, + }}, }}, + Refl = MtlReflect {{ Inputs = {{ + BackgroundMaterial = Input {{ SourceOp = "Dark", Source = "MaterialOutput", }}, + ["Reflection.Color.Material"] = Input {{ SourceOp = "SMap", Source = "MaterialOutput", }}, + ["Reflection.StrengthVariability"] = Input {{ Value = {strength_var}, }}, + ["Reflection.ConstantStrength"] = Input {{ Value = 1.0, }}, + ["Reflection.FaceOnStrength"] = Input {{ Value = {face_on}, }}, + ["Reflection.GlancingStrength"] = Input {{ Value = {glancing}, }}, + ["Reflection.Falloff"] = Input {{ Value = 2.0, }}, + }}, }}, + S = Shape3D {{ Inputs = {{ + Shape = Input {{ Value = FuID {{ "SurfaceSphereInputs" }}, }}, + ["SurfaceSphereInputs.Radius"] = Input {{ Value = 1.0, }}, + MaterialInput = Input {{ SourceOp = "Refl", Source = "MaterialOutput", }}, + }}, }}, + Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 6.0, }}, }}, }}, + M = Merge3D {{ Inputs = {{ + SceneInput1 = Input {{ SourceOp = "S", Source = "Output", }}, + SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, + }}, }}, + R = Renderer3D {{ Inputs = {{ + Width = Input {{ Value = 64, }}, + Height = Input {{ Value = 64, }}, + SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, + }}, }}, + }} }}"# + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); + eng.readback_rgba(&tex).unwrap() + }; + let luma = |buf: &[u8], x: usize, y: usize| { + let o = (y * 64 + x) * 4; + buf[o] as f32 + buf[o + 1] as f32 + buf[o + 2] as f32 + }; + // Fresnel By-Angle: face-on center is dark (0), grazing rim is bright! + let fresnel = render_reflect(1, 0.0, 1.0, 0.0); + let center_l = luma(&fresnel, 32, 32); + let rim_l = (46..=56).map(|x| luma(&fresnel, x, 32)).fold(0.0_f32, f32::max); + assert!(center_l < 15.0 && rim_l > 80.0, "Fresnel center={center_l} rim={rim_l}"); + + // Constant full reflection reflects at center too, and rotating SphereMap by 180° shifts colors. + let c0 = render_reflect(0, 0.0, 1.0, 0.0); + let c180 = render_reflect(0, 0.0, 1.0, 180.0); + assert!(luma(&c0, 32, 32) > 80.0, "constant reflection should brighten center"); + let diff: f32 = (0..64 * 64 * 4).map(|i| (c0[i] as f32 - c180[i] as f32).abs()).sum::() / (64.0 * 64.0 * 4.0); + assert!(diff > 5.0, "rotating SphereMap by 180 deg must change reflected image, diff={diff}"); + } + + #[test] + fn mtl_chan_bool_inverts_swaps_and_combines_channels() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { + Bg = MtlBlinn { Inputs = { + ["Diffuse.Color.Red"] = Input { Value = 0.0, }, + ["Diffuse.Color.Green"] = Input { Value = 1.0, }, + ["Diffuse.Color.Blue"] = Input { Value = 0.0, }, + ReceivesLighting = Input { Value = 0, }, + }, }, + Fg = MtlBlinn { Inputs = { + ["Diffuse.Color.Red"] = Input { Value = 0.0, }, + ["Diffuse.Color.Green"] = Input { Value = 0.0, }, + ["Diffuse.Color.Blue"] = Input { Value = 0.5, }, + ReceivesLighting = Input { Value = 0, }, + }, }, + CB = MtlChanBool { Inputs = { + BackgroundMaterial = Input { SourceOp = "Bg", Source = "MaterialOutput", }, + ForegroundMaterial = Input { SourceOp = "Fg", Source = "MaterialOutput", }, + -- R = BG.G (5 -> 1.0), G = 1 - BG.G (op 2 -> 0.0), B = BG.B + FG.B (op 4 -> 0.5), A = White (9 -> 1.0) + OperandAR = Input { Value = 5, }, OperationR = Input { Value = 0, }, + OperandAG = Input { Value = 5, }, OperationG = Input { Value = 2, }, + OperandAB = Input { Value = 6, }, OperationB = Input { Value = 4, }, OperandBB = Input { Value = 2, }, + OperandAA = Input { Value = 9, }, OperationA = Input { Value = 0, }, + }, }, + P = Shape3D { Inputs = { + ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, + MaterialInput = Input { SourceOp = "CB", Source = "MaterialOutput", }, + }, }, + Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 2.0, }, }, }, + M = Merge3D { Inputs = { + SceneInput1 = Input { SourceOp = "P", Source = "Output", }, + SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, + }, }, + R = Renderer3D { Inputs = { + Width = Input { Value = 32, }, + Height = Input { Value = 32, }, + SceneInput = Input { SourceOp = "M", Source = "Output", }, + }, }, + } }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); + let px = eng.readback_rgba(&tex).unwrap(); + let o = (16 * 32 + 16) * 4; + let rgba = [px[o], px[o + 1], px[o + 2], px[o + 3]]; + assert!(rgba[0] >= 250 && rgba[1] <= 5 && (rgba[2] as i32 - 128).abs() <= 4 && rgba[3] >= 250, "unexpected MtlChanBool pixel {rgba:?}"); + } + + #[test] + fn bender3d_and_replicate3d_render_end_to_end() { + let Ok(mut eng) = Engine::new_headless() else { return }; + let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { + Dest = Shape3D { Inputs = { + ["SurfacePlaneInputs.Width"] = Input { Value = 1.6, }, + ["SurfacePlaneInputs.SubdivisionWidth"] = Input { Value = 1, }, + }, }, + Dot = Shape3D { Inputs = { + ["SurfacePlaneInputs.Width"] = Input { Value = 0.3, }, + ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 1.0, }, + ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.2, }, + ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.0, }, + ["MtlStdInputs.ReceivesLighting"] = Input { Value = 0, }, + }, }, + BentDot = Bender3D { Inputs = { + SceneInput = Input { SourceOp = "Dot", Source = "Output", }, + Bender = Input { Value = FuID { "Twist" }, }, + Amount = Input { Value = 0.25, }, + }, }, + Rep = Replicate3D { Inputs = { + Destination = Input { SourceOp = "Dest", Source = "Output", }, + Input1 = Input { SourceOp = "BentDot", Source = "Output", }, + }, }, + Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4.5, }, }, }, + M = Merge3D { Inputs = { + SceneInput1 = Input { SourceOp = "Rep", Source = "Output", }, + SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, + }, }, + R = Renderer3D { Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + SceneInput = Input { SourceOp = "M", Source = "Output", }, + }, }, + } }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); + let px = eng.readback_rgba(&tex).unwrap(); + // 4 corners of the destination plane should produce non-empty orange pixels, while center (32, 32) is empty! + let center_a = px[(32 * 64 + 32) * 4 + 3]; + let lit_pixels = px.chunks_exact(4).filter(|p| p[0] > 200 && p[3] > 200).count(); + assert_eq!(center_a, 0, "center between 4 replicated corners should be transparent"); + assert!(lit_pixels >= 40, "expected 4 replicated corner quads to render, got {lit_pixels} pixels"); + } } diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index 23f54575aa15f2ad94fc644d23d22049fae1a5a2..e90c4d27b900e3b86aff89532d7051863c9a26fc 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -24,13 +24,15 @@ pub struct Vertex3D { pub(super) struct MeshUniform { pub(super) mvp: [f32; 16], pub(super) model: [f32; 16], + /// Camera view matrix (used by `MtlChanBool` Eye-space position/normal operands). + pub(super) view: [f32; 16], /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture) pub(super) dod: [f32; 4], - /// `[use_tex, lighting_enabled, specular_intensity, flip_normals]` + /// `[use_diffuse_tex, lighting_enabled, specular_intensity, flip_normals]` pub(super) flags: [f32; 4], /// Diffuse color multiplier `(r, g, b, a)` pub(super) diffuse_col: [f32; 4], - /// Specular color `(r, g, b, shininess_exponent)` + /// Specular color `(r, g, b, shininess / roughness / ward_spread_u)` pub(super) specular_col: [f32; 4], /// Ambient light `(r, g, b, 0)` pub(super) ambient: [f32; 4], @@ -46,7 +48,7 @@ pub(super) struct MeshUniform { pub(super) uv_xform: [f32; 4], /// UV translation, wrap mode and unlit light-pass count `[tx, ty, wrap, passes]` pub(super) uv_off_wrap: [f32; 4], - /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance 3=Pbr]` + /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance 3=Pbr 4=Ward]` pub(super) mat_fx: [f32; 4], /// Bump UV affine matrix, column-major `[m00, m10, m01, m11]` pub(super) bump_uv_xform: [f32; 4], @@ -56,8 +58,32 @@ pub(super) struct MeshUniform { pub(super) bump_dod: [f32; 4], /// `[bump_clamp_z, bump_channel, bump_filter_size, 0]` pub(super) bump_params: [f32; 4], - /// `[diffuse_color_alpha, refractive_index, do_fresnel, 0]` + /// `[diffuse_color_alpha, refractive_index, do_fresnel, ward_spread_v]` 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`) + 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], + /// `[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]` + pub(super) refl_tint: [f32; 4], + /// `[refract_tint_r, refract_tint_g, refract_tint_b, 0]` + pub(super) refract_tint: [f32; 4], + /// `MtlChanBool` operand A indices `[r, g, b, a]` + pub(super) cb_ops_a: [f32; 4], + /// `MtlChanBool` operation indices `[r, g, b, a]` + 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]` + 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], /// Point light colors * intensity `(r, g, b, 0)` @@ -177,6 +203,7 @@ pub(super) const SHADER_3D: &str = r#" struct MeshUniform { mvp: mat4x4, model: mat4x4, + view: mat4x4, dod: vec4, flags: vec4, diffuse_col: vec4, @@ -194,6 +221,18 @@ struct MeshUniform { 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>, @@ -226,6 +265,8 @@ struct VsOut { @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 @@ -249,10 +290,14 @@ fn vs_mesh(v: VsIn) -> VsOut { 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; } @@ -307,8 +352,44 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3, n: vec3, light_pos: 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, @@ -356,6 +437,17 @@ fn eval_light_contrib( 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); } @@ -404,30 +496,9 @@ fn perturb_bump_normal( 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 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; - // Gram-Schmidt orthogonalize against base_n - 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; - } else { - 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); - } - } else { - 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); - } + 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); @@ -448,6 +519,126 @@ fn perturb_bump_normal( 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); @@ -456,109 +647,194 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { 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; } - 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; + 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), + ); } - // `rgb_alpha` is `tex_col.a * Diffuse.Opacity`; `Diffuse.Color.Alpha` (`u.mtl_params.x`) - // modulates output alpha without attenuating diffuse/specular RGB. - let rgb_alpha = col.a; - let out_alpha = rgb_alpha * u.mtl_params.x; - if (out_alpha <= 0.002) { - discard; - } - - // `u.diffuse_col` is straight (not premultiplied by `u.diffuse_col.a`), while `tex_col` is premultiplied. - let albedo = tex_straight * u.diffuse_col.rgb; - if (u.flags.y > 0.5) { - var n = 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 = 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), - ); - } - let v = normalize(u.cam_pos.xyz - in.world_pos); - 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, v, 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); - // Shadow density dims only the diffuse term; specular is cut outright. - var occ = 0.0; - if (u.light_counts.w > 0.5) { - occ = point_shadow_occlusion(i, in.world_pos, n, u.point_pos[i].xyz); - } - lit = lit + eval_light_contrib( - n, 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, - ); - } - 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; - // spot_dir.xyz is direction spotlight points; fragment direction from light is -l_dir - 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, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0); - } - } + var base_straight = vec3(0.0); + var rgb_alpha = u.diffuse_col.a; + var out_alpha = rgb_alpha * u.mtl_params.x; - col = vec4(clamp(lit * rgb_alpha, vec3(0.0), vec3(1.0)), out_alpha); + 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 { - col = vec4(clamp(albedo * u.uv_off_wrap.w * rgb_alpha, vec3(0.0), vec3(1.0)), out_alpha); + 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); + } } - return col; + + 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; + c_n = normalize(in.local_n); + } 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 @@ -589,7 +865,7 @@ fn fs_normal(in: VsOut) -> @location(0) vec4 { 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 (out_alpha <= 0.002) { + if (i32(u.env_rot_0.w + 0.5) == 0 && u.cb_flags.x < 0.5 && out_alpha <= 0.002) { discard; }