authoravatarclover caruso<git@paperclover.net>2026-12-02 01:43:25-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-02 02:02:30-08:00
logf09f4d4d1335865b7fda16b04dc7cafcff542f8f
tree4aec7ac4b486f8ad2ea5a6096cbb1aec05daacf0
parent08cecd16e637bc5a644a9c5cb974514af671ec74
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

feat(scene3d): implement Bender3D, Replicate3D, SphereMap, MtlWard, MtlReflect, and MtlChanBool


4 files changed, 2091 insertions(+), 123 deletions(-)

crates/engine/src/scene3d/collect.rs+565-5
...@@ -2,6 +2,10 @@...@@ -2,6 +2,10 @@
22
3use std::sync::Arc;3use std::sync::Arc;
44
5use super::deform::{
6 apply_bender_to_meshes, extract_replicate_points, replicate_meshes, Bender3DParams, BenderMode,
7 Replicate3DParams, MAX_SCENE_MESHES,
8};
5use super::fbx::load_mesh_cached;9use super::fbx::load_mesh_cached;
6use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, smooth_normals, triangle_soup};10use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, smooth_normals, triangle_soup};
7use super::math::{11use super::math::{
...@@ -117,7 +121,6 @@ fn collect_scene_inner(...@@ -117,7 +121,6 @@ fn collect_scene_inner(
117 visited: &mut Vec<NodeId>,121 visited: &mut Vec<NodeId>,
118 depth: usize,122 depth: usize,
119) {123) {
120 const MAX_SCENE_MESHES: usize = 16_384;
121 if depth > 32 || node_id.0 >= comp.nodes.len() || meshes.len() >= MAX_SCENE_MESHES {124 if depth > 32 || node_id.0 >= comp.nodes.len() || meshes.len() >= MAX_SCENE_MESHES {
122 return;125 return;
123 }126 }
...@@ -220,6 +223,156 @@ fn collect_scene_inner(...@@ -220,6 +223,156 @@ fn collect_scene_inner(
220 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);223 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
221 }224 }
222 }225 }
226 "Bender3D" => {
227 let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {
228 return;
229 };
230 let mode = match node.static_str("Bender") {
231 Some("Taper") => BenderMode::Taper,
232 Some("Twist") => BenderMode::Twist,
233 Some("Shear") => BenderMode::Shear,
234 Some("Bend") => BenderMode::Bend,
235 _ => {
236 let idx = comp
237 .eval_number(
238 node,
239 "BenderType",
240 time,
241 comp.eval_number(node, "Bender", time, 0.0, expr),
242 expr,
243 )
244 .round() as i32;
245 match idx {
246 1 => BenderMode::Taper,
247 2 => BenderMode::Twist,
248 3 => BenderMode::Shear,
249 _ => BenderMode::Bend,
250 }
251 }
252 };
253 let params = Bender3DParams {
254 mode,
255 amount: comp.eval_number(node, "Amount", time, 0.0, expr) as f32,
256 axis: comp.eval_number(node, "Axis", time, 1.0, expr).round().clamp(0.0, 2.0) as u32,
257 angle_deg: comp.eval_number(node, "Angle", time, 0.0, expr) as f32,
258 center: comp.eval_number(node, "Center", time, 0.5, expr) as f32,
259 range_min: comp.eval_number(node, "RangeMin", time, 0.0, expr) as f32,
260 range_max: comp.eval_number(node, "RangeMax", time, 1.0, expr) as f32,
261 group: comp.eval_number(node, "Group", time, 0.0, expr) > 0.5,
262 };
263 let mut child_meshes = Vec::new();
264 collect_scene_inner(
265 comp,
266 src_id,
267 time,
268 expr,
269 world,
270 render_aspect,
271 ovr,
272 cameras,
273 &mut child_meshes,
274 lights,
275 visited,
276 depth + 1,
277 );
278 apply_bender_to_meshes(&mut child_meshes, world, &params);
279 let remaining = MAX_SCENE_MESHES.saturating_sub(meshes.len());
280 meshes.extend(child_meshes.into_iter().take(remaining));
281 }
282 "Replicate3D" => {
283 let Some(dest_id) = node.connected_node("Destination").and_then(|s| comp.find_node(s)) else {
284 return;
285 };
286 let mut src_names: Vec<&String> = node
287 .inputs
288 .keys()
289 .filter(|k| k.starts_with("Input") && k["Input".len()..].chars().all(|c| c.is_ascii_digit()) && k.len() > "Input".len())
290 .collect();
291 src_names.sort_by_cached_key(|k| (k["Input".len()..].parse::<u32>().unwrap_or(0), k.to_string()));
292 let mut src_ids: Vec<NodeId> = src_names
293 .into_iter()
294 .filter_map(|k| node.connected_node(k).and_then(|s| comp.find_node(s)))
295 .collect();
296 if src_ids.is_empty() {
297 if let Some(sid) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
298 src_ids.push(sid);
299 }
300 }
301 if src_ids.is_empty() {
302 return;
303 }
304 let mut dest_meshes = Vec::new();
305 let mut dest_cams = Vec::new();
306 let mut dest_lights = SceneLights::default();
307 collect_scene_inner(
308 comp,
309 dest_id,
310 time,
311 expr,
312 mat4_identity(),
313 render_aspect,
314 ovr,
315 &mut dest_cams,
316 &mut dest_meshes,
317 &mut dest_lights,
318 visited,
319 depth + 1,
320 );
321 let mut source_templates = Vec::with_capacity(src_ids.len());
322 for sid in src_ids {
323 let mut tpl = Vec::new();
324 collect_scene_inner(
325 comp,
326 sid,
327 time,
328 expr,
329 mat4_identity(),
330 render_aspect,
331 ovr,
332 cameras,
333 &mut tpl,
334 lights,
335 visited,
336 depth + 1,
337 );
338 if !tpl.is_empty() {
339 source_templates.push(tpl);
340 }
341 }
342 if dest_meshes.is_empty() || source_templates.is_empty() {
343 return;
344 }
345 let step = comp.eval_number(node, "Step", time, 1.0, expr).round().max(1.0) as usize;
346 let remaining = MAX_SCENE_MESHES.saturating_sub(meshes.len());
347 let dest_points = extract_replicate_points(&dest_meshes, step, remaining);
348 let f = |k: &str, d: f64| comp.eval_number(node, k, time, d, expr) as f32;
349 let scale_lock = f("ScaleLock", 1.0) > 0.5;
350 let sx = f("Scale.X", 1.0);
351 let (sy, sz) = if scale_lock { (sx, sx) } else { (f("Scale.Y", 1.0), f("Scale.Z", 1.0)) };
352 let rot_order = node.static_str("RotationOrder").unwrap_or("XYZ");
353 let base_xform = trs_matrix(
354 [f("Translate.X", 0.0), f("Translate.Y", 0.0), f("Translate.Z", 0.0)],
355 [f("Rotate.X", 0.0), f("Rotate.Y", 0.0), f("Rotate.Z", 0.0)],
356 rot_order,
357 [sx, sy, sz],
358 [f("Pivot.X", 0.0), f("Pivot.Y", 0.0), f("Pivot.Z", 0.0)],
359 );
360 let j_scale_lock = f("JitterScaleLock", 1.0) > 0.5;
361 let jsx = f("JitterScale.X", 0.0);
362 let (jsy, jsz) = if j_scale_lock { (jsx, jsx) } else { (f("JitterScale.Y", 0.0), f("JitterScale.Z", 0.0)) };
363 let params = Replicate3DParams {
364 random_input: node.static_str("InputMode") == Some("Random"),
365 alignment: comp.eval_number(node, "Alignment", time, 0.0, expr).round() as i32,
366 base_xform,
367 random_seed: comp.eval_number(node, "RandomSeed", time, 0.0, expr).round().max(0.0) as u64,
368 jitter_prob: f("JitterProbability", 1.0).clamp(0.0, 1.0),
369 jitter_translate: [f("JitterTranslate.X", 0.0), f("JitterTranslate.Y", 0.0), f("JitterTranslate.Z", 0.0)],
370 jitter_rotate: [f("JitterRotate.X", 0.0), f("JitterRotate.Y", 0.0), f("JitterRotate.Z", 0.0)],
371 jitter_pivot: [f("JitterPivot.X", 0.0), f("JitterPivot.Y", 0.0), f("JitterPivot.Z", 0.0)],
372 jitter_scale: [jsx, jsy, jsz],
373 };
374 replicate_meshes(&dest_points, &source_templates, world, &params, meshes);
375 }
223 "Duplicate3D" => {376 "Duplicate3D" => {
224 let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {377 let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {
225 return;378 return;
...@@ -897,7 +1050,60 @@ fn resolve_material_inner(...@@ -897,7 +1050,60 @@ fn resolve_material_inner(
897 ..default_mat1050 ..default_mat
898 }1051 }
899 }1052 }
900 "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" => {1053 "SphereMap" => {
1054 let img_in = n
1055 .connected_node("Image")
1056 .or_else(|| n.connected_node("Input"))
1057 .or_else(|| n.connected_node("MaterialInput"))
1058 .and_then(|s| comp.find_node(s));
1059 let img_node = img_in.and_then(|id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1).tex_node);
1060 let f = |k: &str, fb: &str, d: f64| {
1061 comp.eval_number(n, k, time, comp.eval_number(n, fb, time, d, expr), expr) as f32
1062 };
1063 let rot_deg = [
1064 f("Rotate.X", "Transform3DOp.Rotate.X", 0.0),
1065 f("Rotate.Y", "Transform3DOp.Rotate.Y", 0.0),
1066 f("Rotate.Z", "Transform3DOp.Rotate.Z", 0.0),
1067 ];
1068 let rot_order = n
1069 .static_str("Rotate.RotOrder")
1070 .or_else(|| n.static_str("Transform3DOp.Rotate.RotOrder"))
1071 .unwrap_or("XYZ");
1072 // Rotating the environment sphere by R means sampling world directions via R^T.
1073 let r = euler_matrix(rot_deg, rot_order);
1074 let env_rot = [
1075 r[0], r[4], r[8],
1076 r[1], r[5], r[9],
1077 r[2], r[6], r[10],
1078 ];
1079 let start_angle = comp.eval_number(n, "StartAngle", time, 0.0, expr) as f32;
1080 let end_angle = comp.eval_number(n, "EndAngle", time, 360.0, expr) as f32;
1081 let map_mode = comp.eval_number(n, "MapMode", time, 0.0, expr).round().clamp(0.0, 1.0) as u32;
1082 let tint = [
1083 comp.eval_number(n, "Color.Red", time, 1.0, expr) as f32,
1084 comp.eval_number(n, "Color.Green", time, 1.0, expr) as f32,
1085 comp.eval_number(n, "Color.Blue", time, 1.0, expr) as f32,
1086 1.0,
1087 ];
1088 ResolvedMaterial {
1089 tex_node: img_node,
1090 diffuse_col: tint,
1091 fx: MaterialFx {
1092 env_mode: 1,
1093 env_map_mode: map_mode,
1094 env_tex_slot: if img_node.is_some() { 1 } else { 0 },
1095 env_rot,
1096 env_start_angle: start_angle,
1097 env_end_angle: end_angle,
1098 refl_tint: [tint[0], tint[1], tint[2]],
1099 ..default_mat.fx
1100 },
1101 unlit: true,
1102 has_material_shader: true,
1103 ..default_mat
1104 }
1105 }
1106 "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" | "MtlWard" => {
901 let diff_in = n1107 let diff_in = n
902 .connected_node("Diffuse.Color.Material")1108 .connected_node("Diffuse.Color.Material")
903 .or_else(|| n.connected_node("MaterialInput"))1109 .or_else(|| n.connected_node("MaterialInput"))
...@@ -921,15 +1127,23 @@ fn resolve_material_inner(...@@ -921,15 +1127,23 @@ fn resolve_material_inner(
921 comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32,1127 comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32,
922 ];1128 ];
923 let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32;1129 let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32;
924 let (spec_exp, spec_model, refractive_index, do_fresnel) = match n.kind.as_str() {1130 let (spec_exp, spec_model, refractive_index, do_fresnel, ward_spread_v) = match n.kind.as_str() {
925 "MtlCookTorrance" => (1131 "MtlCookTorrance" => (
926 comp.eval_number(n, "Specular.Roughness", time, 0.6, expr).clamp(0.05, 1.0) as f32,1132 comp.eval_number(n, "Specular.Roughness", time, 0.6, expr).clamp(0.05, 1.0) as f32,
927 SpecModel::CookTorrance,1133 SpecModel::CookTorrance,
928 comp.eval_number(n, "Specular.RefractiveIndex", time, 2.0, expr).max(1.0) as f32,1134 comp.eval_number(n, "Specular.RefractiveIndex", time, 2.0, expr).max(1.0) as f32,
929 comp.eval_number(n, "Specular.DoFresnel", time, 1.0, expr) > 0.5,1135 comp.eval_number(n, "Specular.DoFresnel", time, 1.0, expr) > 0.5,
1136 0.16,
1137 ),
1138 "MtlWard" => (
1139 comp.eval_number(n, "Specular.SpreadU", time, 0.05, expr).clamp(0.0001, 2.0) as f32,
1140 SpecModel::Ward,
1141 2.0,
1142 true,
1143 comp.eval_number(n, "Specular.SpreadV", time, 0.16, expr).clamp(0.0001, 2.0) as f32,
930 ),1144 ),
931 "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong, 2.0, true),1145 "MtlPhong" => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Phong, 2.0, true, 0.16),
932 _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn, 2.0, true),1146 _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn, 2.0, true, 0.16),
933 };1147 };
9341148
935 let spec_model = if comp.eval_number(n, "EnablePBRMaterial", time, 0.0, expr) > 0.5 { SpecModel::Pbr } else { spec_model };1149 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(...@@ -942,6 +1156,7 @@ fn resolve_material_inner(
942 diffuse_color_alpha: col_alpha,1156 diffuse_color_alpha: col_alpha,
943 refractive_index,1157 refractive_index,
944 do_fresnel,1158 do_fresnel,
1159 ward_spread_v,
945 ..diff_mat.fx1160 ..diff_mat.fx
946 };1161 };
947 if let Some(bm) = bump_mat {1162 if let Some(bm) = bump_mat {
...@@ -955,6 +1170,7 @@ fn resolve_material_inner(...@@ -955,6 +1170,7 @@ fn resolve_material_inner(
955 diffuse_color_alpha: col_alpha,1170 diffuse_color_alpha: col_alpha,
956 refractive_index,1171 refractive_index,
957 do_fresnel,1172 do_fresnel,
1173 ward_spread_v,
958 ..bm.fx1174 ..bm.fx
959 };1175 };
960 }1176 }
...@@ -979,6 +1195,222 @@ fn resolve_material_inner(...@@ -979,6 +1195,222 @@ fn resolve_material_inner(
979 has_material_shader: true,1195 has_material_shader: true,
980 }1196 }
981 }1197 }
1198 "MtlReflect" => {
1199 let bg_in = n.connected_node("BackgroundMaterial").and_then(|s| comp.find_node(s));
1200 let has_bg = bg_in.is_some();
1201 let bg_mat = if has_bg {
1202 resolve_material_inner(comp, bg_in, time, expr, visited, depth + 1)
1203 } else {
1204 ResolvedMaterial {
1205 diffuse_col: [0.0, 0.0, 0.0, 0.0],
1206 unlit: true,
1207 ..default_mat
1208 }
1209 };
1210 let refl_in = n
1211 .connected_node("Reflection.Color.Material")
1212 .or_else(|| n.connected_node("ReflectionMaterial"))
1213 .and_then(|s| comp.find_node(s));
1214 let refl_mat = refl_in.map(|rid| resolve_material_inner(comp, Some(rid), time, expr, visited, depth + 1));
1215 let bump_in = n.connected_node("Bumpmap.Material").and_then(|s| comp.find_node(s));
1216 let bump_mat = bump_in.map(|bid| resolve_material_inner(comp, Some(bid), time, expr, visited, depth + 1));
1217
1218 let f2 = |k: &str, fb: &str, d: f64| {
1219 comp.eval_number(n, k, time, comp.eval_number(n, fb, time, d, expr), expr) as f32
1220 };
1221 let strength_var = comp.eval_number(n, "Reflection.StrengthVariability", time, 1.0, expr).round().clamp(0.0, 1.0) as u32;
1222 let const_str = f2("Reflection.ConstantStrength", "Reflection.ConstantReflection", 1.0);
1223 let glancing = f2("Reflection.GlancingStrength", "GlancingStrength", 0.8);
1224 let face_on = f2("Reflection.FaceOnStrength", "FaceOnStrength", 0.0);
1225 let falloff = f2("Reflection.Falloff", "Falloff", 2.0);
1226 let ior = f2("Refraction.RefractiveIndex.RGB", "RefractionIndex", 1.333).max(0.01);
1227 let refract_tint = [
1228 comp.eval_number(n, "Refraction.Tint.Red", time, 1.0, expr) as f32,
1229 comp.eval_number(n, "Refraction.Tint.Green", time, 1.0, expr) as f32,
1230 comp.eval_number(n, "Refraction.Tint.Blue", time, 1.0, expr) as f32,
1231 ];
1232 let base_refl_tint = [
1233 f2("Reflection.Color.Red", "ReflectionColor.Red", 1.0),
1234 f2("Reflection.Color.Green", "ReflectionColor.Green", 1.0),
1235 f2("Reflection.Color.Blue", "ReflectionColor.Blue", 1.0),
1236 ];
1237 let (env_node, env_rot, env_map_mode, env_start, env_end, refl_tint) = if let Some(rm) = &refl_mat {
1238 let tint = [
1239 base_refl_tint[0] * rm.diffuse_col[0],
1240 base_refl_tint[1] * rm.diffuse_col[1],
1241 base_refl_tint[2] * rm.diffuse_col[2],
1242 ];
1243 if rm.fx.env_mode == 1 {
1244 (rm.tex_node, rm.fx.env_rot, rm.fx.env_map_mode, rm.fx.env_start_angle, rm.fx.env_end_angle, tint)
1245 } else {
1246 (rm.tex_node, MaterialFx::default().env_rot, 0, 0.0, 360.0, tint)
1247 }
1248 } else {
1249 (None, MaterialFx::default().env_rot, 0, 0.0, 360.0, base_refl_tint)
1250 };
1251
1252 let bg_has_diffuse_tex = bg_mat.tex_node.is_some() && !bg_mat.fx.bump_only;
1253 let mut tex_node = if bg_has_diffuse_tex { bg_mat.tex_node } else { None };
1254 let mut bump_node = bg_mat.bump_node;
1255 let mut fx = bg_mat.fx;
1256 fx.bump_only = false;
1257
1258 if let Some(bm) = bump_mat {
1259 bump_node = bm.bump_node.or(bm.tex_node);
1260 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };
1261 fx.bump_mode = bm.fx.bump_mode;
1262 fx.bump_uv = bm.fx.uv;
1263 fx.bump_wrap = bm.fx.uv_wrap;
1264 fx.bump_clamp_z = bm.fx.bump_clamp_z;
1265 fx.bump_channel = bm.fx.bump_channel;
1266 }
1267
1268 let env_tex_slot = if let Some(en) = env_node {
1269 if tex_node.is_none() {
1270 tex_node = Some(en);
1271 1
1272 } else {
1273 bump_node = Some(en);
1274 2
1275 }
1276 } else {
1277 0
1278 };
1279
1280 fx.env_mode = 2;
1281 fx.env_map_mode = env_map_mode;
1282 fx.env_tex_slot = env_tex_slot;
1283 fx.env_rot = env_rot;
1284 fx.env_start_angle = env_start;
1285 fx.env_end_angle = env_end;
1286 fx.refl_strength_var = strength_var;
1287 fx.refl_constant_strength = const_str;
1288 fx.refl_glancing_strength = glancing;
1289 fx.refl_face_on_strength = face_on;
1290 fx.refl_falloff = falloff;
1291 fx.refl_tint = refl_tint;
1292 fx.refl_has_bg = has_bg;
1293 fx.refract_ior = ior;
1294 fx.refract_tint = refract_tint;
1295
1296 ResolvedMaterial {
1297 tex_node,
1298 bump_node,
1299 diffuse_col: bg_mat.diffuse_col,
1300 specular_col: bg_mat.specular_col,
1301 specular_intensity: bg_mat.specular_intensity,
1302 specular_exponent: bg_mat.specular_exponent,
1303 fx,
1304 unlit: if has_bg { bg_mat.unlit } else { true },
1305 receives_shadows: bg_mat.receives_shadows,
1306 has_material_shader: true,
1307 }
1308 }
1309 "MtlChanBool" => {
1310 let bg_in = n
1311 .connected_node("BackgroundMaterial")
1312 .or_else(|| n.connected_node("Background"))
1313 .and_then(|s| comp.find_node(s));
1314 let fg_in = n
1315 .connected_node("ForegroundMaterial")
1316 .or_else(|| n.connected_node("Foreground"))
1317 .and_then(|s| comp.find_node(s));
1318 let mut bg_mat = if bg_in.is_some() {
1319 resolve_material_inner(comp, bg_in, time, expr, visited, depth + 1)
1320 } else {
1321 ResolvedMaterial {
1322 diffuse_col: [0.0, 0.0, 0.0, 0.0],
1323 unlit: true,
1324 ..default_mat
1325 }
1326 };
1327 let fg_mat = fg_in.map(|fid| resolve_material_inner(comp, Some(fid), time, expr, visited, depth + 1));
1328
1329 let has_native_cb = ["OperandAR", "OperandAG", "OperandAB", "OperandAA", "OperationR", "OperationG", "OperationB", "OperationA", "OperandBR", "OperandBG", "OperandBB", "OperandBA"]
1330 .iter()
1331 .any(|k| n.inputs.contains_key(*k));
1332 let has_legacy_cb = ["Operation", "ToRed", "ToGreen", "ToBlue", "ToAlpha"]
1333 .iter()
1334 .any(|k| n.inputs.contains_key(*k));
1335
1336 let (cb_ops_a, cb_ops, cb_ops_b) = if has_native_cb || !has_legacy_cb {
1337 let g = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr).round().clamp(0.0, 30.0) as u8;
1338 let op = |k: &str| comp.eval_number(n, k, time, 0.0, expr).round().clamp(0.0, 10.0) as u8;
1339 (
1340 [g("OperandAR", 4.0), g("OperandAG", 5.0), g("OperandAB", 6.0), g("OperandAA", 7.0)],
1341 [op("OperationR"), op("OperationG"), op("OperationB"), op("OperationA")],
1342 [g("OperandBR", 0.0), g("OperandBG", 1.0), g("OperandBB", 2.0), g("OperandBA", 3.0)],
1343 )
1344 } else {
1345 // Fallback mapping for 2D ChannelBoolean-style keys (Operation + ToRed/Green/Blue/Alpha).
1346 let leg_op = comp.eval_number(n, "Operation", time, 0.0, expr).round() as i32;
1347 let mapped_op: u8 = match leg_op {
1348 1 => 4, // Add -> A + B
1349 2 => 5, // Subtract -> A - B
1350 6 | 3 => 6, // Multiply / And -> A * B
1351 7 => 7, // Divide -> A / B
1352 8 => 9, // Maximum -> max(A, B)
1353 9 => 8, // Minimum -> min(A, B)
1354 10 => 3, // Negative -> 1 - B
1355 _ => 1, // Copy -> B
1356 };
1357 let map_ch = |k: &str, bg_idx: u8, def_ch: f64| -> (u8, u8) {
1358 let v = comp.eval_number(n, k, time, def_ch, expr).round() as i32;
1359 match v {
1360 0..=3 => (mapped_op, v as u8),
1361 4 => (0, bg_idx), // Do Nothing -> keep A (BG)
1362 5..=8 => (mapped_op, (v - 1) as u8), // BG RGBA -> 4..=7
1363 15 => (mapped_op, 8), // Black
1364 16 => (mapped_op, 9), // White
1365 _ => (mapped_op, bg_idx),
1366 }
1367 };
1368 let (or, br) = map_ch("ToRed", 4, 0.0);
1369 let (og, bg_b) = map_ch("ToGreen", 5, 1.0);
1370 let (ob, bb) = map_ch("ToBlue", 6, 2.0);
1371 let (oa, ba) = map_ch("ToAlpha", 7, 3.0);
1372 ([4, 5, 6, 7], [or, og, ob, oa], [br, bg_b, bb, ba])
1373 };
1374
1375 let coord_space = match n.static_str("CoordSpace") {
1376 Some("Model") => 0,
1377 Some("World") => 1,
1378 _ => 2,
1379 };
1380
1381 let (fg_col, fg_tex_slot) = if let Some(fm) = fg_mat {
1382 let col = [
1383 fm.diffuse_col[0],
1384 fm.diffuse_col[1],
1385 fm.diffuse_col[2],
1386 fm.diffuse_col[3] * fm.fx.diffuse_color_alpha,
1387 ];
1388 let slot = if let Some(ftex) = fm.tex_node.filter(|_| !fm.fx.bump_only) {
1389 if bg_mat.bump_node.is_none() && bg_mat.fx.env_tex_slot != 2 {
1390 bg_mat.bump_node = Some(ftex);
1391 bg_mat.fx.bump_wrap = fm.fx.uv_wrap;
1392 2
1393 } else {
1394 0
1395 }
1396 } else {
1397 0
1398 };
1399 (col, slot)
1400 } else {
1401 ([0.0, 0.0, 0.0, 0.0], 0)
1402 };
1403
1404 bg_mat.fx.cb_enabled = true;
1405 bg_mat.fx.cb_ops_a = cb_ops_a;
1406 bg_mat.fx.cb_ops = cb_ops;
1407 bg_mat.fx.cb_ops_b = cb_ops_b;
1408 bg_mat.fx.cb_fg_col = fg_col;
1409 bg_mat.fx.cb_coord_space = coord_space;
1410 bg_mat.fx.cb_fg_tex_slot = fg_tex_slot;
1411 bg_mat.has_material_shader = true;
1412 bg_mat
1413 }
982 _ => ResolvedMaterial {1414 _ => ResolvedMaterial {
983 tex_node: Some(mid),1415 tex_node: Some(mid),
984 ..default_mat1416 ..default_mat
...@@ -1819,4 +2251,132 @@ mod tests {...@@ -1819,4 +2251,132 @@ mod tests {
1819 assert!((s_fx.diffuse_color_alpha - 0.25).abs() < 1e-5);2251 assert!((s_fx.diffuse_color_alpha - 0.25).abs() < 1e-5);
1820 assert!((meshes[2].diffuse_col[3] - 0.6).abs() < 1e-5);2252 assert!((meshes[2].diffuse_col[3] - 0.6).abs() < 1e-5);
1821 }2253 }
2254
2255 #[test]
2256 fn bender3d_and_replicate3d_scene_collection() {
2257 let src = comp_src(
2258 r#"Plane = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.SubdivisionWidth"] = Input { Value = 4, }, }, },
2259 Bent = Bender3D { Inputs = {
2260 SceneInput = Input { SourceOp = "Plane", Source = "Output", },
2261 Bender = Input { Value = FuID { "Taper" }, },
2262 Amount = Input { Value = 0.5, },
2263 Axis = Input { Value = 1, },
2264 Center = Input { Value = 0.5, },
2265 }, },
2266 DestCube = Shape3D { Inputs = {
2267 Shape = Input { Value = FuID { "SurfaceCubeInputs" }, },
2268 ["SurfaceCubeInputs.Width"] = Input { Value = 2.0, },
2269 ["SurfaceCubeInputs.SubdivisionWidth"] = Input { Value = 1, },
2270 }, },
2271 SrcA = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 1.0, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.0, }, }, },
2272 SrcB = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.0, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 1.0, }, }, },
2273 Rep = Replicate3D { Inputs = {
2274 Destination = Input { SourceOp = "DestCube", Source = "Output", },
2275 Input1 = Input { SourceOp = "SrcA", Source = "Output", },
2276 Input2 = Input { SourceOp = "SrcB", Source = "Output", },
2277 Step = Input { Value = 2, },
2278 Alignment = Input { Value = 1, },
2279 ["Scale.X"] = Input { Value = 0.25, },
2280 }, },
2281 M = Merge3D { Inputs = {
2282 SceneInput1 = Input { SourceOp = "Bent", Source = "Output", },
2283 SceneInput2 = Input { SourceOp = "Rep", Source = "Output", },
2284 }, },"#,
2285 );
2286 let (_, meshes, _) = collect(&src, "M");
2287 // 1 deformed plane + 4 replicated instances (8 unique cube corners / Step 2).
2288 assert_eq!(meshes.len(), 5);
2289 assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::CustomMesh(v) if !v.is_empty()));
2290 // Loop mode alternates Input1 (red) and Input2 (green).
2291 assert!((meshes[1].diffuse_col[0] - 1.0).abs() < 1e-4 && meshes[1].diffuse_col[1].abs() < 1e-4);
2292 assert!(meshes[2].diffuse_col[0].abs() < 1e-4 && (meshes[2].diffuse_col[1] - 1.0).abs() < 1e-4);
2293 }
2294
2295 #[test]
2296 fn spheremap_ward_reflect_and_chanbool_material_resolution() {
2297 let src = comp_src(
2298 r#"EnvBg = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 8, }, }, },
2299 DiffBg = Background { Inputs = { Width = Input { Value = 16, }, Height = Input { Value = 16, }, }, },
2300 SMap = SphereMap { Inputs = {
2301 Image = Input { SourceOp = "EnvBg", Source = "Output", },
2302 ["Rotate.Y"] = Input { Value = 90.0, },
2303 StartAngle = Input { Value = 30.0, },
2304 EndAngle = Input { Value = 330.0, },
2305 }, },
2306 Ward = MtlWard { Inputs = {
2307 ["Diffuse.Color.Material"] = Input { SourceOp = "DiffBg", Source = "Output", },
2308 ["Specular.SpreadU"] = Input { Value = 0.04, },
2309 ["Specular.SpreadV"] = Input { Value = 0.28, },
2310 }, },
2311 Refl = MtlReflect { Inputs = {
2312 BackgroundMaterial = Input { SourceOp = "Ward", Source = "MaterialOutput", },
2313 ["Reflection.Color.Material"] = Input { SourceOp = "SMap", Source = "MaterialOutput", },
2314 ["Reflection.GlancingStrength"] = Input { Value = 0.9, },
2315 ["Reflection.FaceOnStrength"] = Input { Value = 0.15, },
2316 ["Reflection.Falloff"] = Input { Value = 3.0, },
2317 ["Refraction.RefractiveIndex.RGB"] = Input { Value = 1.5, },
2318 }, },
2319 FgBlinn = MtlBlinn { Inputs = {
2320 ["Diffuse.Color.Red"] = Input { Value = 0.2, },
2321 ["Diffuse.Color.Green"] = Input { Value = 0.4, },
2322 ["Diffuse.Color.Blue"] = Input { Value = 0.6, },
2323 }, },
2324 CB = MtlChanBool { Inputs = {
2325 BackgroundMaterial = Input { SourceOp = "Ward", Source = "MaterialOutput", },
2326 ForegroundMaterial = Input { SourceOp = "FgBlinn", Source = "MaterialOutput", },
2327 OperandAR = Input { Value = 4, },
2328 OperationR = Input { Value = 4, },
2329 OperandBR = Input { Value = 0, },
2330 CoordSpace = Input { Value = FuID { "World" }, },
2331 }, },
2332 S0 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "SMap", Source = "MaterialOutput", }, }, },
2333 S1 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Ward", Source = "MaterialOutput", }, }, },
2334 S2 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Refl", Source = "MaterialOutput", }, }, },
2335 S3 = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "CB", Source = "MaterialOutput", }, }, },
2336 M = Merge3D { Inputs = {
2337 SceneInput1 = Input { SourceOp = "S0", Source = "Output", },
2338 SceneInput2 = Input { SourceOp = "S1", Source = "Output", },
2339 SceneInput3 = Input { SourceOp = "S2", Source = "Output", },
2340 SceneInput4 = Input { SourceOp = "S3", Source = "Output", },
2341 }, },"#,
2342 );
2343 let comp = Comp::from_fusion_str(&src).unwrap();
2344 let env_id = comp.find_node("EnvBg").unwrap();
2345 let diff_id = comp.find_node("DiffBg").unwrap();
2346 let (_, meshes, _) = collect(&src, "M");
2347 assert_eq!(meshes.len(), 4);
2348
2349 // SphereMap standalone
2350 let fx0 = meshes[0].shape.split_fx().1;
2351 assert_eq!(meshes[0].material_node, Some(env_id));
2352 assert_eq!(fx0.env_mode, 1);
2353 assert_eq!(fx0.env_tex_slot, 1);
2354 assert!((fx0.env_start_angle - 30.0).abs() < 1e-4 && (fx0.env_end_angle - 330.0).abs() < 1e-4);
2355
2356 // MtlWard
2357 let fx1 = meshes[1].shape.split_fx().1;
2358 assert_eq!(fx1.spec_model, SpecModel::Ward);
2359 assert!((meshes[1].specular_exponent - 0.04).abs() < 1e-5);
2360 assert!((fx1.ward_spread_v - 0.28).abs() < 1e-5);
2361
2362 // MtlReflect with both diffuse texture (in mat_tex) and SphereMap (in bump_tex slot 2)
2363 let fx2 = meshes[2].shape.split_fx().1;
2364 assert_eq!(meshes[2].material_node, Some(diff_id));
2365 assert_eq!(meshes[2].bump_node, Some(env_id));
2366 assert_eq!(fx2.env_mode, 2);
2367 assert_eq!(fx2.env_tex_slot, 2);
2368 assert!((fx2.refl_glancing_strength - 0.9).abs() < 1e-5);
2369 assert!((fx2.refl_face_on_strength - 0.15).abs() < 1e-5);
2370 assert!((fx2.refl_falloff - 3.0).abs() < 1e-5);
2371 assert!((fx2.refract_ior - 1.5).abs() < 1e-5);
2372
2373 // MtlChanBool
2374 let fx3 = meshes[3].shape.split_fx().1;
2375 assert!(fx3.cb_enabled);
2376 assert_eq!(fx3.cb_ops_a[0], 4);
2377 assert_eq!(fx3.cb_ops[0], 4);
2378 assert_eq!(fx3.cb_ops_b[0], 0);
2379 assert_eq!(fx3.cb_coord_space, 1);
2380 assert!((fx3.cb_fg_col[0] - 0.2).abs() < 1e-5 && (fx3.cb_fg_col[2] - 0.6).abs() < 1e-5);
2381 }
1822}2382}
crates/engine/src/scene3d/deform.rs created+791
...@@ -0,0 +1,791 @@
1//! 3D mesh deformers (`Bender3D`) and vertex instancing (`Replicate3D`).
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use super::collect::mat4_inverse;
7use super::math::{
8 mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
9};
10use super::mesh::{build_shape_mesh, triangle_soup};
11use super::{Mat4, MeshInstance, ShapeKind, Vertex3D};
12
13/// Maximum number of meshes allowed in a collected 3D scene (shared with `collect.rs`).
14pub(super) const MAX_SCENE_MESHES: usize = 16_384;
15
16/// Deformation mode of `Bender3D`.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum BenderMode {
19 Bend,
20 Taper,
21 Twist,
22 Shear,
23}
24
25/// Evaluated parameters for a `Bender3D` node.
26#[derive(Clone, Copy, Debug)]
27pub struct Bender3DParams {
28 pub mode: BenderMode,
29 pub amount: f32,
30 /// `0 = X`, `1 = Y`, `2 = Z`.
31 pub axis: u32,
32 /// Bend/shear plane angle in degrees around the bend axis.
33 pub angle_deg: f32,
34 /// Pivot fraction along the bounding box on the chosen axis (`0..=1`, default `0.5`).
35 pub center: f32,
36 /// Lower active range fraction along the chosen axis (`0..=1`, default `0.0`).
37 pub range_min: f32,
38 /// Upper active range fraction along the chosen axis (`0..=1`, default `1.0`).
39 pub range_max: f32,
40 /// When true, all child meshes are deformed together inside their shared bounding box.
41 pub group: bool,
42}
43
44impl Default for Bender3DParams {
45 fn default() -> Self {
46 Self {
47 mode: BenderMode::Bend,
48 amount: 0.0,
49 axis: 1,
50 angle_deg: 0.0,
51 center: 0.5,
52 range_min: 0.0,
53 range_max: 1.0,
54 group: false,
55 }
56 }
57}
58
59#[inline]
60fn vec3_dot(a: [f32; 3], b: [f32; 3]) -> f32 {
61 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
62}
63
64#[inline]
65fn vec3_sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
66 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
67}
68
69#[inline]
70fn vec3_cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
71 [
72 a[1] * b[2] - a[2] * b[1],
73 a[2] * b[0] - a[0] * b[2],
74 a[0] * b[1] - a[1] * b[0],
75 ]
76}
77
78#[inline]
79fn vec3_norm(a: [f32; 3]) -> Option<[f32; 3]> {
80 let l = vec3_dot(a, a).sqrt();
81 (l > 1e-8).then(|| [a[0] / l, a[1] / l, a[2] / l])
82}
83
84#[inline]
85fn xform_point(m: Mat4, p: [f32; 3]) -> [f32; 3] {
86 [
87 m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12],
88 m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13],
89 m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14],
90 ]
91}
92
93#[inline]
94fn xform_vector(m: Mat4, v: [f32; 3]) -> [f32; 3] {
95 [
96 m[0] * v[0] + m[4] * v[1] + m[8] * v[2],
97 m[1] * v[0] + m[5] * v[1] + m[9] * v[2],
98 m[2] * v[0] + m[6] * v[1] + m[10] * v[2],
99 ]
100}
101
102/// Transforms a surface normal by the cofactor matrix of `m` (inverse-transpose up to scale),
103/// preserving outward orientation under non-uniform scale and mirroring.
104#[inline]
105fn xform_normal(m: Mat4, n: [f32; 3]) -> [f32; 3] {
106 let c0 = [m[0], m[1], m[2]];
107 let c1 = [m[4], m[5], m[6]];
108 let c2 = [m[8], m[9], m[10]];
109 let sign = if vec3_dot(c0, vec3_cross(c1, c2)) >= 0.0 { 1.0 } else { -1.0 };
110 let r0 = vec3_cross(c1, c2);
111 let r1 = vec3_cross(c2, c0);
112 let r2 = vec3_cross(c0, c1);
113 let out = [
114 (r0[0] * n[0] + r1[0] * n[1] + r2[0] * n[2]) * sign,
115 (r0[1] * n[0] + r1[1] * n[1] + r2[1] * n[2]) * sign,
116 (r0[2] * n[0] + r1[2] * n[1] + r2[2] * n[2]) * sign,
117 ];
118 vec3_norm(out).unwrap_or([0.0, 0.0, 1.0])
119}
120
121/// Right-handed orthonormal basis `(u, v, w)` where `w` is the bend axis rotated by `angle_deg`.
122fn bender_basis(axis: u32, angle_deg: f32) -> ([f32; 3], [f32; 3], [f32; 3]) {
123 let (u0, v0, w) = match axis {
124 0 => ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]),
125 2 => ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
126 _ => ([1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]),
127 };
128 let (s, c) = angle_deg.to_radians().sin_cos();
129 let u = [
130 u0[0] * c + v0[0] * s,
131 u0[1] * c + v0[1] * s,
132 u0[2] * c + v0[2] * s,
133 ];
134 let v = [
135 -u0[0] * s + v0[0] * c,
136 -u0[1] * s + v0[1] * c,
137 -u0[2] * s + v0[2] * c,
138 ];
139 (u, v, w)
140}
141
142fn axis_bounds_of(verts: &[Vertex3D], w: [f32; 3]) -> Option<[f32; 2]> {
143 let mut mn = f32::INFINITY;
144 let mut mx = f32::NEG_INFINITY;
145 for v in verts {
146 let p = vec3_dot(v.pos, w);
147 mn = mn.min(p);
148 mx = mx.max(p);
149 }
150 (mn.is_finite() && mx.is_finite()).then_some([mn, mx])
151}
152
153/// Applies `Bender3D` deformation to `verts` in-place and recomputes smooth vertex normals.
154pub fn deform_mesh_vertices(
155 verts: &mut [Vertex3D],
156 indices: &[u32],
157 params: &Bender3DParams,
158 shared_bounds: Option<[f32; 2]>,
159) {
160 if verts.is_empty() || params.amount.abs() < 1e-6 {
161 return;
162 }
163 let (u, v, w) = bender_basis(params.axis, params.angle_deg);
164 let Some([min_w, max_w]) = shared_bounds.or_else(|| axis_bounds_of(verts, w)) else {
165 return;
166 };
167 let extent = max_w - min_w;
168 if extent <= 1e-6 {
169 return;
170 }
171 let r_min_frac = params.range_min.clamp(0.0, 1.0);
172 let r_max_frac = params.range_max.clamp(r_min_frac, 1.0);
173 if (r_max_frac - r_min_frac) <= 1e-6 {
174 return;
175 }
176 let center_frac = params.center.clamp(0.0, 1.0);
177 let w0 = min_w + center_frac * extent;
178 let r_min = min_w + r_min_frac * extent;
179 let r_max = min_w + r_max_frac * extent;
180 let amount = params.amount;
181
182 for vert in verts.iter_mut() {
183 let pu = vec3_dot(vert.pos, u);
184 let pv = vec3_dot(vert.pos, v);
185 let pw = vec3_dot(vert.pos, w);
186 let wc = pw.clamp(r_min, r_max);
187 let w_ext = pw - wc;
188 let t = (wc - w0) / extent;
189
190 let nu_old = vec3_dot(vert.normal, u);
191 let nv_old = vec3_dot(vert.normal, v);
192 let nw_old = vec3_dot(vert.normal, w);
193
194 let (nu, nv, nw, rnu, rnv, rnw) = match params.mode {
195 BenderMode::Bend => {
196 // Amount = 1.0 bends the full extent by PI radians (180 degrees).
197 let k = amount * std::f32::consts::PI / extent;
198 let theta = k * (wc - w0);
199 let (st, ct) = theta.sin_cos();
200 let (pos_u, pos_w) = if k.abs() > 1e-6 {
201 let r = 1.0 / k;
202 (
203 r - (r - pu) * ct - w_ext * st,
204 w0 + (r - pu) * st + w_ext * ct,
205 )
206 } else {
207 (pu, pw)
208 };
209 // Rotate normal by the local bend angle so face orientation checks stay accurate.
210 let n_u = nu_old * ct - nw_old * st;
211 let n_w = nu_old * st + nw_old * ct;
212 (pos_u, pv, pos_w, n_u, nv_old, n_w)
213 }
214 BenderMode::Taper => {
215 let s = (1.0 + amount * 2.0 * t).max(0.0);
216 (pu * s, pv * s, pw, nu_old, nv_old, nw_old)
217 }
218 BenderMode::Twist => {
219 let theta = amount * std::f32::consts::TAU * t;
220 let (st, ct) = theta.sin_cos();
221 let pos_u = pu * ct - pv * st;
222 let pos_v = pu * st + pv * ct;
223 let n_u = nu_old * ct - nv_old * st;
224 let n_v = nu_old * st + nv_old * ct;
225 (pos_u, pos_v, pw, n_u, n_v, nw_old)
226 }
227 BenderMode::Shear => {
228 let pos_u = pu + amount * (wc - w0);
229 let n_w = nw_old - amount * nu_old;
230 (pos_u, pv, pw, nu_old, nv_old, n_w)
231 }
232 };
233
234 vert.pos = [
235 u[0] * nu + v[0] * nv + w[0] * nw,
236 u[1] * nu + v[1] * nv + w[1] * nw,
237 u[2] * nu + v[2] * nv + w[2] * nw,
238 ];
239 let approx_n = [
240 u[0] * rnu + v[0] * rnv + w[0] * rnw,
241 u[1] * rnu + v[1] * rnv + w[1] * rnw,
242 u[2] * rnu + v[2] * rnv + w[2] * rnw,
243 ];
244 vert.normal = vec3_norm(approx_n).unwrap_or(vert.normal);
245 }
246
247 recompute_smooth_normals(verts, indices, 60.0);
248}
249
250/// Recomputes smooth vertex normals across welded vertex positions, orienting each triangle
251/// consistently with the approximate vertex normals and preserving creases sharper than `crease_deg`.
252pub fn recompute_smooth_normals(verts: &mut [Vertex3D], indices: &[u32], crease_deg: f32) {
253 let tris: Vec<[u32; 3]> = indices
254 .chunks_exact(3)
255 .filter_map(|t| {
256 let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize);
257 (a < verts.len() && b < verts.len() && c < verts.len()).then_some([t[0], t[1], t[2]])
258 })
259 .collect();
260 if tris.is_empty() {
261 return;
262 }
263
264 let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64);
265 let mut face_normals: Vec<Option<[f32; 3]>> = Vec::with_capacity(tris.len());
266 let mut face_areas: Vec<f32> = Vec::with_capacity(tris.len());
267 let mut at_pos: HashMap<[i64; 3], Vec<usize>> = HashMap::new();
268
269 for (ti, t) in tris.iter().enumerate() {
270 let p = t.map(|i| verts[i as usize].pos);
271 let raw = vec3_cross(vec3_sub(p[1], p[0]), vec3_sub(p[2], p[0]));
272 let area = vec3_dot(raw, raw).sqrt();
273 if area > 1e-10 {
274 let mut fn_u = [raw[0] / area, raw[1] / area, raw[2] / area];
275 // Match each builder's outward winding using the Jacobian-transformed vertex normals.
276 let outward = t.iter().fold(0.0_f32, |acc, &i| acc + vec3_dot(verts[i as usize].normal, fn_u));
277 if outward < 0.0 {
278 fn_u = [-fn_u[0], -fn_u[1], -fn_u[2]];
279 }
280 face_normals.push(Some(fn_u));
281 face_areas.push(area);
282 for &i in t {
283 at_pos.entry(key(verts[i as usize].pos)).or_default().push(ti);
284 }
285 } else {
286 face_normals.push(None);
287 face_areas.push(0.0);
288 }
289 }
290
291 let cos_limit = crease_deg.to_radians().cos() - 1e-4;
292 let mut new_normals: Vec<Option<[f32; 3]>> = vec![None; verts.len()];
293 for (ti, t) in tris.iter().enumerate() {
294 let Some(own_n) = face_normals[ti] else {
295 continue;
296 };
297 for &vi in t {
298 let v_idx = vi as usize;
299 let k = key(verts[v_idx].pos);
300 let mut sum = [0.0_f32; 3];
301 if let Some(group) = at_pos.get(&k) {
302 for &fi in group {
303 if let Some(fn_u) = face_normals[fi] {
304 if vec3_dot(fn_u, own_n) >= cos_limit {
305 let w = face_areas[fi];
306 sum[0] += fn_u[0] * w;
307 sum[1] += fn_u[1] * w;
308 sum[2] += fn_u[2] * w;
309 }
310 }
311 }
312 }
313 let smoothed = vec3_norm(sum).unwrap_or(own_n);
314 if let Some(prev) = new_normals[v_idx] {
315 new_normals[v_idx] = vec3_norm([
316 prev[0] + smoothed[0],
317 prev[1] + smoothed[1],
318 prev[2] + smoothed[2],
319 ])
320 .or(Some(smoothed));
321 } else {
322 new_normals[v_idx] = Some(smoothed);
323 }
324 }
325 }
326 for (v, n_opt) in verts.iter_mut().zip(new_normals) {
327 if let Some(n) = n_opt {
328 v.normal = n;
329 }
330 }
331}
332
333/// Applies `Bender3D` to a slice of collected child meshes (either individually or as a group).
334pub fn apply_bender_to_meshes(
335 meshes: &mut [MeshInstance],
336 bender_world: Mat4,
337 params: &Bender3DParams,
338) {
339 if meshes.is_empty() || params.amount.abs() < 1e-6 {
340 return;
341 }
342
343 if params.group {
344 let inv_bender = mat4_inverse(bender_world);
345 let (_, _, w_axis) = bender_basis(params.axis, params.angle_deg);
346 let mut baked: Vec<(Vec<Vertex3D>, Vec<u32>)> = Vec::with_capacity(meshes.len());
347 let mut g_min = f32::INFINITY;
348 let mut g_max = f32::NEG_INFINITY;
349
350 for m in meshes.iter() {
351 let rel = mat4_mul(inv_bender, m.world);
352 let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), 1.0);
353 for vert in &mut verts {
354 vert.pos = xform_point(rel, vert.pos);
355 vert.normal = xform_normal(rel, vert.normal);
356 let p = vec3_dot(vert.pos, w_axis);
357 g_min = g_min.min(p);
358 g_max = g_max.max(p);
359 }
360 baked.push((verts, idx));
361 }
362 let shared = (g_min.is_finite() && g_max.is_finite()).then_some([g_min, g_max]);
363 for (m, (mut verts, idx)) in meshes.iter_mut().zip(baked) {
364 if idx.is_empty() {
365 continue;
366 }
367 deform_mesh_vertices(&mut verts, &idx, params, shared);
368 let soup = triangle_soup((verts, idx));
369 let (_, fx) = m.shape.split_fx();
370 m.shape = ShapeKind::WithMaterialFx {
371 inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))),
372 fx,
373 };
374 m.world = bender_world;
375 }
376 } else {
377 for m in meshes.iter_mut() {
378 let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), 1.0);
379 if idx.is_empty() {
380 continue;
381 }
382 deform_mesh_vertices(&mut verts, &idx, params, None);
383 let soup = triangle_soup((verts, idx));
384 let (_, fx) = m.shape.split_fx();
385 m.shape = ShapeKind::WithMaterialFx {
386 inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))),
387 fx,
388 };
389 }
390 }
391}
392
393/// World-space destination point + orthonormal TBN frame extracted for `Replicate3D`.
394#[derive(Clone, Copy, Debug)]
395pub struct ReplicatePoint {
396 pub pos: [f32; 3],
397 pub normal: [f32; 3],
398 pub tangent: [f32; 3],
399 pub bitangent: [f32; 3],
400}
401
402/// Extracts deduplicated world-space vertex frames from destination meshes for `Replicate3D`.
403pub fn extract_replicate_points(
404 dest_meshes: &[MeshInstance],
405 step: usize,
406 max_points: usize,
407) -> Vec<ReplicatePoint> {
408 if dest_meshes.is_empty() || max_points == 0 {
409 return Vec::new();
410 }
411 let stride = step.max(1);
412 let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64);
413
414 struct Accum {
415 pos: [f32; 3],
416 normal: [f32; 3],
417 tangent: [f32; 3],
418 }
419
420 let mut order: Vec<[i64; 3]> = Vec::new();
421 let mut table: HashMap<[i64; 3], Accum> = HashMap::new();
422
423 for dm in dest_meshes {
424 let (verts, indices) = build_shape_mesh(dm.shape.base_shape(), 1.0);
425 if verts.is_empty() {
426 continue;
427 }
428 // Compute per-vertex tangents from triangles when available.
429 let mut tangents = vec![[0.0_f32; 3]; verts.len()];
430 for tri in indices.chunks_exact(3) {
431 let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize);
432 if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
433 continue;
434 }
435 let e1 = vec3_sub(verts[i1].pos, verts[i0].pos);
436 let e2 = vec3_sub(verts[i2].pos, verts[i0].pos);
437 let du1 = verts[i1].uv[0] - verts[i0].uv[0];
438 let dv1 = verts[i1].uv[1] - verts[i0].uv[1];
439 let du2 = verts[i2].uv[0] - verts[i0].uv[0];
440 let dv2 = verts[i2].uv[1] - verts[i0].uv[1];
441 let det = du1 * dv2 - dv1 * du2;
442 let t_tri = if det.abs() > 1e-6 {
443 let inv = 1.0 / det;
444 [
445 (e1[0] * dv2 - e2[0] * dv1) * inv,
446 (e1[1] * dv2 - e2[1] * dv1) * inv,
447 (e1[2] * dv2 - e2[2] * dv1) * inv,
448 ]
449 } else {
450 e1
451 };
452 for idx in [i0, i1, i2] {
453 tangents[idx][0] += t_tri[0];
454 tangents[idx][1] += t_tri[1];
455 tangents[idx][2] += t_tri[2];
456 }
457 }
458
459 for (vi, v) in verts.iter().enumerate() {
460 let wp = xform_point(dm.world, v.pos);
461 let wn = xform_normal(dm.world, v.normal);
462 let wt = xform_vector(dm.world, tangents[vi]);
463 let k = key(wp);
464 if let Some(acc) = table.get_mut(&k) {
465 acc.normal[0] += wn[0];
466 acc.normal[1] += wn[1];
467 acc.normal[2] += wn[2];
468 acc.tangent[0] += wt[0];
469 acc.tangent[1] += wt[1];
470 acc.tangent[2] += wt[2];
471 } else {
472 order.push(k);
473 table.insert(k, Accum { pos: wp, normal: wn, tangent: wt });
474 }
475 }
476 }
477
478 let mut out = Vec::with_capacity((order.len() / stride + 1).min(max_points));
479 for (idx, k) in order.into_iter().enumerate() {
480 if idx % stride != 0 {
481 continue;
482 }
483 if out.len() >= max_points {
484 break;
485 }
486 let acc = &table[&k];
487 let n = vec3_norm(acc.normal).unwrap_or([0.0, 0.0, 1.0]);
488 // Gram-Schmidt orthogonalize tangent against normal; fallback when degenerate.
489 let t_proj = [
490 acc.tangent[0] - n[0] * vec3_dot(acc.tangent, n),
491 acc.tangent[1] - n[1] * vec3_dot(acc.tangent, n),
492 acc.tangent[2] - n[2] * vec3_dot(acc.tangent, n),
493 ];
494 let t = vec3_norm(t_proj).unwrap_or_else(|| {
495 let up = if n[1].abs() > 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] };
496 vec3_norm(vec3_cross(up, n)).unwrap_or([1.0, 0.0, 0.0])
497 });
498 let b = vec3_norm(vec3_cross(n, t)).unwrap_or([0.0, 1.0, 0.0]);
499 out.push(ReplicatePoint { pos: acc.pos, normal: n, tangent: t, bitangent: b });
500 }
501 out
502}
503
504/// Builds the placement matrix for a destination point according to `Replicate3D.Alignment`:
505/// - `0`: Not aligned (translation only)
506/// - `1`: Aligned (aligns local `+Z` to destination vertex normal)
507/// - `2`: TBN Aligned (aligns local X/Y/Z to destination vertex T/B/N frame)
508pub fn replicate_alignment_matrix(pt: &ReplicatePoint, alignment: i32) -> Mat4 {
509 match alignment {
510 1 => {
511 let z = pt.normal;
512 let up = if z[1].abs() > 0.99 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] };
513 let x = vec3_norm(vec3_cross(up, z)).unwrap_or([1.0, 0.0, 0.0]);
514 let y = vec3_cross(z, x);
515 [
516 x[0], x[1], x[2], 0.0,
517 y[0], y[1], y[2], 0.0,
518 z[0], z[1], z[2], 0.0,
519 pt.pos[0], pt.pos[1], pt.pos[2], 1.0,
520 ]
521 }
522 2 => {
523 let x = pt.tangent;
524 let y = pt.bitangent;
525 let z = pt.normal;
526 [
527 x[0], x[1], x[2], 0.0,
528 y[0], y[1], y[2], 0.0,
529 z[0], z[1], z[2], 0.0,
530 pt.pos[0], pt.pos[1], pt.pos[2], 1.0,
531 ]
532 }
533 _ => mat4_translate(pt.pos[0], pt.pos[1], pt.pos[2]),
534 }
535}
536
537/// Evaluated parameters for a `Replicate3D` node.
538#[derive(Clone, Debug)]
539pub struct Replicate3DParams {
540 pub random_input: bool,
541 /// `0 = Not aligned`, `1 = Aligned`, `2 = TBN Aligned`.
542 pub alignment: i32,
543 pub base_xform: Mat4,
544 pub random_seed: u64,
545 pub jitter_prob: f32,
546 pub jitter_translate: [f32; 3],
547 pub jitter_rotate: [f32; 3],
548 pub jitter_pivot: [f32; 3],
549 pub jitter_scale: [f32; 3],
550}
551
552fn splitmix64_signed(mut x: u64) -> f32 {
553 x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
554 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
555 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
556 x ^= x >> 31;
557 ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5
558}
559
560fn splitmix64_u64(mut x: u64) -> u64 {
561 x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
562 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
563 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
564 x ^ (x >> 31)
565}
566
567/// Instantiates `source_templates` (`Input1..InputN`) onto `dest_points` while honoring
568/// `MAX_SCENE_MESHES` so large destination meshes never exhaust memory.
569pub fn replicate_meshes(
570 dest_points: &[ReplicatePoint],
571 source_templates: &[Vec<MeshInstance>],
572 node_world: Mat4,
573 params: &Replicate3DParams,
574 out_meshes: &mut Vec<MeshInstance>,
575) {
576 if dest_points.is_empty() || source_templates.is_empty() {
577 return;
578 }
579 let has_jitter = params.jitter_translate.iter().any(|v| v.abs() > 1e-5)
580 || params.jitter_rotate.iter().any(|v| v.abs() > 1e-5)
581 || params.jitter_pivot.iter().any(|v| v.abs() > 1e-5)
582 || params.jitter_scale.iter().any(|v| v.abs() > 1e-5);
583
584 for (idx, pt) in dest_points.iter().enumerate() {
585 if out_meshes.len() >= MAX_SCENE_MESHES {
586 break;
587 }
588 let s = params
589 .random_seed
590 .wrapping_mul(6_364_136_223_846_793_005)
591 .wrapping_add((idx as u64).wrapping_mul(1_442_695_040_888_963_407));
592 let tpl_idx = if params.random_input {
593 (splitmix64_u64(s ^ 17) as usize) % source_templates.len()
594 } else {
595 idx % source_templates.len()
596 };
597 let template = &source_templates[tpl_idx];
598 if template.is_empty() {
599 continue;
600 }
601
602 let place = replicate_alignment_matrix(pt, params.alignment);
603 let mut inst_m = mat4_mul(node_world, mat4_mul(place, params.base_xform));
604 if has_jitter && (params.jitter_prob >= 0.9999 || (splitmix64_signed(s ^ 13) + 0.5) <= params.jitter_prob) {
605 let tx = splitmix64_signed(s ^ 1) * params.jitter_translate[0];
606 let ty = splitmix64_signed(s ^ 2) * params.jitter_translate[1];
607 let tz = splitmix64_signed(s ^ 3) * params.jitter_translate[2];
608 let rx = (splitmix64_signed(s ^ 4) * params.jitter_rotate[0]).to_radians();
609 let ry = (splitmix64_signed(s ^ 5) * params.jitter_rotate[1]).to_radians();
610 let rz = (splitmix64_signed(s ^ 6) * params.jitter_rotate[2]).to_radians();
611 let sx = (1.0 + splitmix64_signed(s ^ 7) * params.jitter_scale[0]).max(1e-4);
612 let sy = (1.0 + splitmix64_signed(s ^ 8) * params.jitter_scale[1]).max(1e-4);
613 let sz = (1.0 + splitmix64_signed(s ^ 9) * params.jitter_scale[2]).max(1e-4);
614 let px = splitmix64_signed(s ^ 10) * params.jitter_pivot[0];
615 let py = splitmix64_signed(s ^ 11) * params.jitter_pivot[1];
616 let pz = splitmix64_signed(s ^ 12) * params.jitter_pivot[2];
617 let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx)));
618 let jm = mat4_mul(
619 mat4_translate(tx + px, ty + py, tz + pz),
620 mat4_mul(rot, mat4_mul(mat4_scale(sx, sy, sz), mat4_translate(-px, -py, -pz))),
621 );
622 inst_m = mat4_mul(inst_m, jm);
623 }
624
625 for src_m in template {
626 if out_meshes.len() >= MAX_SCENE_MESHES {
627 break;
628 }
629 let mut cloned = src_m.clone();
630 cloned.world = mat4_mul(inst_m, src_m.world);
631 out_meshes.push(cloned);
632 }
633 }
634}
635
636#[cfg(test)]
637mod tests {
638 use super::*;
639 use crate::scene3d::math::mat4_identity;
640 use crate::scene3d::MaterialFx;
641
642 fn dummy_mesh(shape: ShapeKind, world: Mat4) -> MeshInstance {
643 MeshInstance {
644 world,
645 shape: ShapeKind::WithMaterialFx {
646 inner: Box::new(shape),
647 fx: MaterialFx::default(),
648 },
649 material_node: None,
650 bump_node: None,
651 text3d: None,
652 diffuse_col: [1.0, 1.0, 1.0, 1.0],
653 specular_col: [1.0, 1.0, 1.0],
654 specular_intensity: 1.0,
655 specular_exponent: 50.0,
656 affected_by_lights: true,
657 casts_shadow: true,
658 receives_shadows: true,
659 flip_normals: false,
660 displace: None,
661 }
662 }
663
664 #[test]
665 fn bender_bend_curves_plane_and_updates_normals() {
666 let shape = ShapeKind::Plane { width: 1.0, height: 2.0, sub_w: 4, sub_h: 8 };
667 let (mut verts, idx) = build_shape_mesh(&shape, 1.0);
668 let params = Bender3DParams {
669 mode: BenderMode::Bend,
670 amount: 1.0,
671 axis: 1, // Y axis
672 angle_deg: 0.0,
673 center: 0.5,
674 range_min: 0.0,
675 range_max: 1.0,
676 group: false,
677 };
678 deform_mesh_vertices(&mut verts, &idx, &params, None);
679 // Plane was originally flat at z=0 with normal +Z; bending around Y along X curls X into a circle
680 // and tilts top/bottom vertices in X while keeping finite unit normals.
681 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;
682 assert!(top_x > 0.2, "top edge should bend toward +X, got {top_x}");
683 assert!(verts.iter().all(|v| {
684 let l = vec3_dot(v.normal, v.normal).sqrt();
685 l.is_finite() && (l - 1.0).abs() < 1e-3
686 }));
687 }
688
689 #[test]
690 fn bender_taper_twist_shear_and_range_clamp() {
691 let shape = ShapeKind::Plane { width: 2.0, height: 2.0, sub_w: 4, sub_h: 4 };
692
693 // Taper: top (+Y) expands, bottom (-Y) shrinks.
694 let (mut v_taper, idx) = build_shape_mesh(&shape, 1.0);
695 deform_mesh_vertices(&mut v_taper, &idx, &Bender3DParams {
696 mode: BenderMode::Taper,
697 amount: 0.5,
698 axis: 1,
699 center: 0.5,
700 ..Default::default()
701 }, None);
702 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);
703 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);
704 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}");
705
706 // Twist: rotates corners out of z=0 plane.
707 let (mut v_twist, idx) = build_shape_mesh(&shape, 1.0);
708 deform_mesh_vertices(&mut v_twist, &idx, &Bender3DParams {
709 mode: BenderMode::Twist,
710 amount: 0.5,
711 axis: 1,
712 center: 0.5,
713 ..Default::default()
714 }, None);
715 let max_z = v_twist.iter().map(|v| v.pos[2].abs()).fold(0.0_f32, f32::max);
716 assert!(max_z > 0.5, "twist should rotate vertices out of XY plane, max_z={max_z}");
717
718 // Shear with RangeMin=0.5 leaves bottom half unsheared (all at constant offset for wc=0) and shears top half.
719 let (mut v_shear, idx) = build_shape_mesh(&shape, 1.0);
720 deform_mesh_vertices(&mut v_shear, &idx, &Bender3DParams {
721 mode: BenderMode::Shear,
722 amount: 1.0,
723 axis: 1,
724 center: 0.5,
725 range_min: 0.5,
726 range_max: 1.0,
727 ..Default::default()
728 }, None);
729 let top_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] < 0.01).unwrap().pos[0];
730 let bot_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] > 0.99).unwrap().pos[0];
731 assert!((top_shift - 1.0).abs() < 1e-4, "top center should shear by +1.0, got {top_shift}");
732 assert!(bot_shift.abs() < 1e-4, "bottom below RangeMin should stay at 0, got {bot_shift}");
733 }
734
735 #[test]
736 fn bender_group_mode_deforms_multiple_meshes_in_shared_bounds() {
737 let mut meshes = vec![
738 dummy_mesh(ShapeKind::Cube { width: 1.0, sub: 2, faces: 0b11_1111 }, mat4_translate(0.0, -1.0, 0.0)),
739 dummy_mesh(ShapeKind::Cube { width: 1.0, sub: 2, faces: 0b11_1111 }, mat4_translate(0.0, 1.0, 0.0)),
740 ];
741 apply_bender_to_meshes(&mut meshes, mat4_identity(), &Bender3DParams {
742 mode: BenderMode::Taper,
743 amount: 0.5,
744 axis: 1,
745 center: 0.5,
746 group: true,
747 ..Default::default()
748 });
749 let ShapeKind::CustomMesh(v0) = meshes[0].shape.base_shape() else { panic!("expected custom mesh") };
750 let ShapeKind::CustomMesh(v1) = meshes[1].shape.base_shape() else { panic!("expected custom mesh") };
751 let bot_w = v0.iter().map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max);
752 let top_w = v1.iter().map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max);
753 assert!(top_w > bot_w * 1.4, "group taper should widen upper cube relative to lower cube: {top_w} vs {bot_w}");
754 }
755
756 #[test]
757 fn replicate_extracts_unique_vertices_aligns_normals_and_respects_cap() {
758 // 1x1 subdivided cube has 8 unique corner vertices (36 triangle-soup vertices across 6 faces).
759 let dest = vec![dummy_mesh(ShapeKind::Cube { width: 2.0, sub: 1, faces: 0b11_1111 }, mat4_identity())];
760 let pts = extract_replicate_points(&dest, 1, MAX_SCENE_MESHES);
761 assert_eq!(pts.len(), 8, "cube with sub=1 should deduplicate to 8 corner points");
762 for pt in &pts {
763 // Corner normal should point radially outward along pos.
764 assert!(vec3_dot(pt.pos, pt.normal) > 0.5, "corner normal should point outward: {pt:?}");
765 }
766
767 let src_tpl = vec![vec![dummy_mesh(ShapeKind::Plane { width: 0.2, height: 0.2, sub_w: 1, sub_h: 1 }, mat4_identity())]];
768 let mut out = Vec::new();
769 let params = Replicate3DParams {
770 random_input: false,
771 alignment: 1,
772 base_xform: mat4_identity(),
773 random_seed: 0,
774 jitter_prob: 1.0,
775 jitter_translate: [0.0; 3],
776 jitter_rotate: [0.0; 3],
777 jitter_pivot: [0.0; 3],
778 jitter_scale: [0.0; 3],
779 };
780 replicate_meshes(&pts, &src_tpl, mat4_identity(), &params, &mut out);
781 assert_eq!(out.len(), 8);
782 // Aligned mode aligns local +Z (column 2 of world) with destination normal.
783 let z_col = [out[0].world[8], out[0].world[9], out[0].world[10]];
784 assert!(vec3_dot(z_col, pts[0].normal) > 0.99, "aligned +Z should match vertex normal");
785
786 // Cap enforcement: pre-fill close to MAX_SCENE_MESHES and verify we never exceed it.
787 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];
788 replicate_meshes(&pts, &src_tpl, mat4_identity(), &params, &mut capped);
789 assert_eq!(capped.len(), MAX_SCENE_MESHES, "must strictly enforce MAX_SCENE_MESHES cap");
790 }
791}
crates/engine/src/scene3d/mod.rs+344-3
...@@ -7,6 +7,7 @@...@@ -7,6 +7,7 @@
7//! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection.7//! and `Camera3D` film-gate `AoV` / `ApertureW` / `ApertureH` projection.
88
9mod collect;9mod collect;
10mod deform;
10mod fbx;11mod fbx;
11mod math;12mod math;
12mod mesh;13mod mesh;
...@@ -283,7 +284,7 @@ impl UvAffine {...@@ -283,7 +284,7 @@ impl UvAffine {
283}284}
284285
285/// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for286/// Specular lobe of a material; `MeshInstance::specular_exponent` is the exponent for
286/// `Blinn`/`Phong` and the roughness for `CookTorrance`.287/// `Blinn`/`Phong`, the roughness for `CookTorrance`, and `SpreadU` for `Ward`.
287#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]288#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
288pub enum SpecModel {289pub enum SpecModel {
289 #[default]290 #[default]
...@@ -292,6 +293,8 @@ pub enum SpecModel {...@@ -292,6 +293,8 @@ pub enum SpecModel {
292 CookTorrance,293 CookTorrance,
293 /// `EnablePBRMaterial`: diffuse-only lights at 1/pi, no specular lobe.294 /// `EnablePBRMaterial`: diffuse-only lights at 1/pi, no specular lobe.
294 Pbr,295 Pbr,
296 /// Anisotropic Ward BRDF (`MtlWard`).
297 Ward,
295}298}
296299
297#[derive(Clone, Copy, Debug, PartialEq)]300#[derive(Clone, Copy, Debug, PartialEq)]
...@@ -323,6 +326,40 @@ pub struct MaterialFx {...@@ -323,6 +326,40 @@ pub struct MaterialFx {
323 pub refractive_index: f32,326 pub refractive_index: f32,
324 /// `MtlCookTorrance` `Specular.DoFresnel` toggle.327 /// `MtlCookTorrance` `Specular.DoFresnel` toggle.
325 pub do_fresnel: bool,328 pub do_fresnel: bool,
329 /// `MtlWard` `Specular.SpreadV` anisotropic roughness along V.
330 pub ward_spread_v: f32,
331 /// Environment shading mode: `0 = none`, `1 = standalone SphereMap`, `2 = MtlReflect`.
332 pub env_mode: u32,
333 /// `SphereMap.MapMode`: `0 = equirectangular`, `1 = angular`.
334 pub env_map_mode: u32,
335 /// Texture slot carrying the environment image: `0 = solid/none`, `1 = mat_tex`, `2 = bump_tex`.
336 pub env_tex_slot: u32,
337 /// Column-major 3x3 inverse rotation matrix for `SphereMap` direction lookup.
338 pub env_rot: [f32; 9],
339 /// `SphereMap.StartAngle` in degrees.
340 pub env_start_angle: f32,
341 /// `SphereMap.EndAngle` in degrees.
342 pub env_end_angle: f32,
343 /// `MtlReflect.Reflection.StrengthVariability`: `0 = Constant`, `1 = By Angle`.
344 pub refl_strength_var: u32,
345 pub refl_constant_strength: f32,
346 pub refl_glancing_strength: f32,
347 pub refl_face_on_strength: f32,
348 pub refl_falloff: f32,
349 pub refl_tint: [f32; 3],
350 pub refl_has_bg: bool,
351 pub refract_ior: f32,
352 pub refract_tint: [f32; 3],
353 /// `MtlChanBool` per-channel boolean evaluation.
354 pub cb_enabled: bool,
355 pub cb_ops_a: [u8; 4],
356 pub cb_ops: [u8; 4],
357 pub cb_ops_b: [u8; 4],
358 pub cb_fg_col: [f32; 4],
359 /// `0 = Model`, `1 = World`, `2 = Eye`.
360 pub cb_coord_space: u8,
361 /// `0 = constant fg_col`, `2 = sample bump_tex for FG`.
362 pub cb_fg_tex_slot: u8,
326}363}
327364
328impl Default for MaterialFx {365impl Default for MaterialFx {
...@@ -345,6 +382,29 @@ impl Default for MaterialFx {...@@ -345,6 +382,29 @@ impl Default for MaterialFx {
345 diffuse_color_alpha: 1.0,382 diffuse_color_alpha: 1.0,
346 refractive_index: 2.0,383 refractive_index: 2.0,
347 do_fresnel: true,384 do_fresnel: true,
385 ward_spread_v: 0.16,
386 env_mode: 0,
387 env_map_mode: 0,
388 env_tex_slot: 0,
389 env_rot: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
390 env_start_angle: 0.0,
391 env_end_angle: 360.0,
392 refl_strength_var: 1,
393 refl_constant_strength: 1.0,
394 refl_glancing_strength: 0.8,
395 refl_face_on_strength: 0.0,
396 refl_falloff: 2.0,
397 refl_tint: [1.0, 1.0, 1.0],
398 refl_has_bg: true,
399 refract_ior: 1.333,
400 refract_tint: [1.0, 1.0, 1.0],
401 cb_enabled: false,
402 cb_ops_a: [4, 5, 6, 7],
403 cb_ops: [0, 0, 0, 0],
404 cb_ops_b: [0, 1, 2, 3],
405 cb_fg_col: [0.0, 0.0, 0.0, 0.0],
406 cb_coord_space: 2,
407 cb_fg_tex_slot: 0,
348 }408 }
349 }409 }
350}410}
...@@ -369,6 +429,37 @@ impl MaterialFx {...@@ -369,6 +429,37 @@ impl MaterialFx {
369 self.diffuse_color_alpha.to_bits().hash(h);429 self.diffuse_color_alpha.to_bits().hash(h);
370 self.refractive_index.to_bits().hash(h);430 self.refractive_index.to_bits().hash(h);
371 self.do_fresnel.hash(h);431 self.do_fresnel.hash(h);
432 self.ward_spread_v.to_bits().hash(h);
433 self.env_mode.hash(h);
434 self.env_map_mode.hash(h);
435 self.env_tex_slot.hash(h);
436 for v in self.env_rot {
437 v.to_bits().hash(h);
438 }
439 self.env_start_angle.to_bits().hash(h);
440 self.env_end_angle.to_bits().hash(h);
441 self.refl_strength_var.hash(h);
442 self.refl_constant_strength.to_bits().hash(h);
443 self.refl_glancing_strength.to_bits().hash(h);
444 self.refl_face_on_strength.to_bits().hash(h);
445 self.refl_falloff.to_bits().hash(h);
446 for v in self.refl_tint {
447 v.to_bits().hash(h);
448 }
449 self.refl_has_bg.hash(h);
450 self.refract_ior.to_bits().hash(h);
451 for v in self.refract_tint {
452 v.to_bits().hash(h);
453 }
454 self.cb_enabled.hash(h);
455 self.cb_ops_a.hash(h);
456 self.cb_ops.hash(h);
457 self.cb_ops_b.hash(h);
458 for v in self.cb_fg_col {
459 v.to_bits().hash(h);
460 }
461 self.cb_coord_space.hash(h);
462 self.cb_fg_tex_slot.hash(h);
372 }463 }
373}464}
374465
...@@ -1437,12 +1528,16 @@ impl Scene3DRenderer {...@@ -1437,12 +1528,16 @@ impl Scene3DRenderer {
1437 dir_to_light[di] = [dl.to_light[0], dl.to_light[1], dl.to_light[2], 0.0];1528 dir_to_light[di] = [dl.to_light[0], dl.to_light[1], dl.to_light[2], 0.0];
1438 dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0];1529 dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0];
1439 }1530 }
1531 let use_diffuse_tex = m.tex.is_some() && fx.env_tex_slot != 1;
1532 let has_bump_tex = bump_src.is_some() && fx.env_tex_slot != 2 && fx.cb_fg_tex_slot != 2;
1533 let env_span = ((fx.env_end_angle - fx.env_start_angle) / 360.0).abs().max(1e-4);
1440 let uni = MeshUniform {1534 let uni = MeshUniform {
1441 mvp,1535 mvp,
1442 model: m.world,1536 model: m.world,
1537 view,
1443 dod,1538 dod,
1444 flags: [1539 flags: [
1445 if m.tex.is_some() { 1.0 } else { 0.0 },1540 if use_diffuse_tex { 1.0 } else { 0.0 },
1446 if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 },1541 if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 },
1447 m.specular_intensity,1542 m.specular_intensity,
1448 if m.flip_normals { 1.0 } else { 0.0 },1543 if m.flip_normals { 1.0 } else { 0.0 },
...@@ -1463,13 +1558,45 @@ impl Scene3DRenderer {...@@ -1463,13 +1558,45 @@ impl Scene3DRenderer {
1463 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 }],1558 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 }],
1464 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],1559 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],
1465 bump_uv_xform: fx.bump_uv.m,1560 bump_uv_xform: fx.bump_uv.m,
1466 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 }],1561 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 }],
1467 bump_dod,1562 bump_dod,
1468 bump_params: [fx.bump_clamp_z, fx.bump_channel as f32, 0.0, 0.0],1563 bump_params: [fx.bump_clamp_z, fx.bump_channel as f32, 0.0, 0.0],
1469 mtl_params: [1564 mtl_params: [
1470 fx.diffuse_color_alpha,1565 fx.diffuse_color_alpha,
1471 fx.refractive_index,1566 fx.refractive_index,
1472 if fx.do_fresnel { 1.0 } else { 0.0 },1567 if fx.do_fresnel { 1.0 } else { 0.0 },
1568 fx.ward_spread_v,
1569 ],
1570 env_rot_0: [fx.env_rot[0], fx.env_rot[1], fx.env_rot[2], fx.env_mode as f32],
1571 env_rot_1: [fx.env_rot[3], fx.env_rot[4], fx.env_rot[5], fx.env_map_mode as f32],
1572 env_rot_2: [fx.env_rot[6], fx.env_rot[7], fx.env_rot[8], fx.env_tex_slot as f32],
1573 env_angles: [
1574 fx.env_start_angle / 360.0,
1575 1.0 / env_span,
1576 fx.refl_strength_var as f32,
1577 fx.refl_constant_strength,
1578 ],
1579 refl_params: [
1580 fx.refl_glancing_strength,
1581 fx.refl_face_on_strength,
1582 fx.refl_falloff,
1583 fx.refract_ior,
1584 ],
1585 refl_tint: [
1586 fx.refl_tint[0],
1587 fx.refl_tint[1],
1588 fx.refl_tint[2],
1589 if fx.refl_has_bg { 1.0 } else { 0.0 },
1590 ],
1591 refract_tint: [fx.refract_tint[0], fx.refract_tint[1], fx.refract_tint[2], 0.0],
1592 cb_ops_a: fx.cb_ops_a.map(f32::from),
1593 cb_ops: fx.cb_ops.map(f32::from),
1594 cb_ops_b: fx.cb_ops_b.map(f32::from),
1595 cb_fg_col: fx.cb_fg_col,
1596 cb_flags: [
1597 if fx.cb_enabled { 1.0 } else { 0.0 },
1598 f32::from(fx.cb_coord_space),
1599 f32::from(fx.cb_fg_tex_slot),
1473 0.0,1600 0.0,
1474 ],1601 ],
1475 point_pos,1602 point_pos,
...@@ -2617,4 +2744,218 @@ mod tests {...@@ -2617,4 +2744,218 @@ mod tests {
2617 let (tex_cached_off, _) = eng.evaluate(&make_comp("Perspective", 0, 0), comp_off.find_node("R").unwrap(), 0.0);2744 let (tex_cached_off, _) = eng.evaluate(&make_comp("Perspective", 0, 0), comp_off.find_node("R").unwrap(), 0.0);
2618 assert!(tex_cached_off.aux.is_none());2745 assert!(tex_cached_off.aux.is_none());
2619 }2746 }
2747
2748 #[test]
2749 fn mtl_ward_anisotropic_spread_u_vs_v_stretches_specular_highlight() {
2750 let Ok(mut eng) = Engine::new_headless() else { return };
2751 let mut render = |su: f32, sv: f32| -> Vec<u8> {
2752 let src = format!(
2753 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{
2754 Ward = MtlWard {{ Inputs = {{
2755 ["Diffuse.Color.Red"] = Input {{ Value = 0.0, }},
2756 ["Diffuse.Color.Green"] = Input {{ Value = 0.0, }},
2757 ["Diffuse.Color.Blue"] = Input {{ Value = 0.0, }},
2758 ["Specular.Intensity"] = Input {{ Value = 1.0, }},
2759 ["Specular.SpreadU"] = Input {{ Value = {su}, }},
2760 ["Specular.SpreadV"] = Input {{ Value = {sv}, }},
2761 }}, }},
2762 S = Shape3D {{ Inputs = {{
2763 Shape = Input {{ Value = FuID {{ "SurfaceSphereInputs" }}, }},
2764 ["SurfaceSphereInputs.Radius"] = Input {{ Value = 1.0, }},
2765 MaterialInput = Input {{ SourceOp = "Ward", Source = "MaterialOutput", }},
2766 }}, }},
2767 L = LightDirectional {{ Inputs = {{ Intensity = Input {{ Value = 2.0, }}, }}, }},
2768 Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 5.5, }}, }}, }},
2769 M = Merge3D {{ Inputs = {{
2770 SceneInput1 = Input {{ SourceOp = "S", Source = "Output", }},
2771 SceneInput2 = Input {{ SourceOp = "L", Source = "Output", }},
2772 SceneInput3 = Input {{ SourceOp = "Cam", Source = "Output", }},
2773 }}, }},
2774 R = Renderer3D {{ Inputs = {{
2775 Width = Input {{ Value = 64, }},
2776 Height = Input {{ Value = 64, }},
2777 ["RendererSoftware.LightingEnabled"] = Input {{ Value = 1, }},
2778 SceneInput = Input {{ SourceOp = "M", Source = "Output", }},
2779 }}, }},
2780 }} }}"#
2781 );
2782 let comp = Comp::from_fusion_str(&src).unwrap();
2783 let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0);
2784 eng.readback_rgba(&tex).unwrap()
2785 };
2786 let horiz = render(0.45, 0.05);
2787 let vert = render(0.05, 0.45);
2788 let px_r = |buf: &[u8], x: usize, y: usize| buf[(y * 64 + x) * 4] as f32;
2789 // Sample off-center along horizontal vs vertical axes from sphere center (32, 32).
2790 let h_horiz = px_r(&horiz, 40, 32) + px_r(&horiz, 24, 32);
2791 let h_vert = px_r(&horiz, 32, 40) + px_r(&horiz, 32, 24);
2792 let v_horiz = px_r(&vert, 40, 32) + px_r(&vert, 24, 32);
2793 let v_vert = px_r(&vert, 32, 40) + px_r(&vert, 32, 24);
2794 assert!(h_horiz > h_vert + 5.0, "wide SpreadU should stretch highlight horizontally: h={h_horiz} v={h_vert}");
2795 assert!(v_vert > v_horiz + 5.0, "wide SpreadV should stretch highlight vertically: h={v_horiz} v={v_vert}");
2796 }
2797
2798 #[test]
2799 fn spheremap_and_mtl_reflect_fresnel_and_constant_strength() {
2800 let Ok(mut eng) = Engine::new_headless() else { return };
2801 let mut render_reflect = |strength_var: u8, face_on: f32, glancing: f32, rot_y: f32| -> Vec<u8> {
2802 let src = format!(
2803 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{
2804 Env = Background {{ Inputs = {{
2805 Width = Input {{ Value = 64, }},
2806 Height = Input {{ Value = 32, }},
2807 Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
2808 TopLeftRed = Input {{ Value = 1.0, }}, TopLeftGreen = Input {{ Value = 0.0, }}, TopLeftBlue = Input {{ Value = 0.0, }},
2809 TopRightRed = Input {{ Value = 0.0, }}, TopRightGreen = Input {{ Value = 0.0, }}, TopRightBlue = Input {{ Value = 1.0, }},
2810 }}, }},
2811 SMap = SphereMap {{ Inputs = {{
2812 Image = Input {{ SourceOp = "Env", Source = "Output", }},
2813 ["Rotate.Y"] = Input {{ Value = {rot_y}, }},
2814 }}, }},
2815 Dark = MtlBlinn {{ Inputs = {{
2816 ["Diffuse.Color.Red"] = Input {{ Value = 0.0, }},
2817 ["Diffuse.Color.Green"] = Input {{ Value = 0.0, }},
2818 ["Diffuse.Color.Blue"] = Input {{ Value = 0.0, }},
2819 ["Specular.Intensity"] = Input {{ Value = 0.0, }},
2820 }}, }},
2821 Refl = MtlReflect {{ Inputs = {{
2822 BackgroundMaterial = Input {{ SourceOp = "Dark", Source = "MaterialOutput", }},
2823 ["Reflection.Color.Material"] = Input {{ SourceOp = "SMap", Source = "MaterialOutput", }},
2824 ["Reflection.StrengthVariability"] = Input {{ Value = {strength_var}, }},
2825 ["Reflection.ConstantStrength"] = Input {{ Value = 1.0, }},
2826 ["Reflection.FaceOnStrength"] = Input {{ Value = {face_on}, }},
2827 ["Reflection.GlancingStrength"] = Input {{ Value = {glancing}, }},
2828 ["Reflection.Falloff"] = Input {{ Value = 2.0, }},
2829 }}, }},
2830 S = Shape3D {{ Inputs = {{
2831 Shape = Input {{ Value = FuID {{ "SurfaceSphereInputs" }}, }},
2832 ["SurfaceSphereInputs.Radius"] = Input {{ Value = 1.0, }},
2833 MaterialInput = Input {{ SourceOp = "Refl", Source = "MaterialOutput", }},
2834 }}, }},
2835 Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 6.0, }}, }}, }},
2836 M = Merge3D {{ Inputs = {{
2837 SceneInput1 = Input {{ SourceOp = "S", Source = "Output", }},
2838 SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }},
2839 }}, }},
2840 R = Renderer3D {{ Inputs = {{
2841 Width = Input {{ Value = 64, }},
2842 Height = Input {{ Value = 64, }},
2843 SceneInput = Input {{ SourceOp = "M", Source = "Output", }},
2844 }}, }},
2845 }} }}"#
2846 );
2847 let comp = Comp::from_fusion_str(&src).unwrap();
2848 let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0);
2849 eng.readback_rgba(&tex).unwrap()
2850 };
2851 let luma = |buf: &[u8], x: usize, y: usize| {
2852 let o = (y * 64 + x) * 4;
2853 buf[o] as f32 + buf[o + 1] as f32 + buf[o + 2] as f32
2854 };
2855 // Fresnel By-Angle: face-on center is dark (0), grazing rim is bright!
2856 let fresnel = render_reflect(1, 0.0, 1.0, 0.0);
2857 let center_l = luma(&fresnel, 32, 32);
2858 let rim_l = (46..=56).map(|x| luma(&fresnel, x, 32)).fold(0.0_f32, f32::max);
2859 assert!(center_l < 15.0 && rim_l > 80.0, "Fresnel center={center_l} rim={rim_l}");
2860
2861 // Constant full reflection reflects at center too, and rotating SphereMap by 180° shifts colors.
2862 let c0 = render_reflect(0, 0.0, 1.0, 0.0);
2863 let c180 = render_reflect(0, 0.0, 1.0, 180.0);
2864 assert!(luma(&c0, 32, 32) > 80.0, "constant reflection should brighten center");
2865 let diff: f32 = (0..64 * 64 * 4).map(|i| (c0[i] as f32 - c180[i] as f32).abs()).sum::<f32>() / (64.0 * 64.0 * 4.0);
2866 assert!(diff > 5.0, "rotating SphereMap by 180 deg must change reflected image, diff={diff}");
2867 }
2868
2869 #[test]
2870 fn mtl_chan_bool_inverts_swaps_and_combines_channels() {
2871 let Ok(mut eng) = Engine::new_headless() else { return };
2872 let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() {
2873 Bg = MtlBlinn { Inputs = {
2874 ["Diffuse.Color.Red"] = Input { Value = 0.0, },
2875 ["Diffuse.Color.Green"] = Input { Value = 1.0, },
2876 ["Diffuse.Color.Blue"] = Input { Value = 0.0, },
2877 ReceivesLighting = Input { Value = 0, },
2878 }, },
2879 Fg = MtlBlinn { Inputs = {
2880 ["Diffuse.Color.Red"] = Input { Value = 0.0, },
2881 ["Diffuse.Color.Green"] = Input { Value = 0.0, },
2882 ["Diffuse.Color.Blue"] = Input { Value = 0.5, },
2883 ReceivesLighting = Input { Value = 0, },
2884 }, },
2885 CB = MtlChanBool { Inputs = {
2886 BackgroundMaterial = Input { SourceOp = "Bg", Source = "MaterialOutput", },
2887 ForegroundMaterial = Input { SourceOp = "Fg", Source = "MaterialOutput", },
2888 -- 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)
2889 OperandAR = Input { Value = 5, }, OperationR = Input { Value = 0, },
2890 OperandAG = Input { Value = 5, }, OperationG = Input { Value = 2, },
2891 OperandAB = Input { Value = 6, }, OperationB = Input { Value = 4, }, OperandBB = Input { Value = 2, },
2892 OperandAA = Input { Value = 9, }, OperationA = Input { Value = 0, },
2893 }, },
2894 P = Shape3D { Inputs = {
2895 ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, },
2896 MaterialInput = Input { SourceOp = "CB", Source = "MaterialOutput", },
2897 }, },
2898 Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 2.0, }, }, },
2899 M = Merge3D { Inputs = {
2900 SceneInput1 = Input { SourceOp = "P", Source = "Output", },
2901 SceneInput2 = Input { SourceOp = "Cam", Source = "Output", },
2902 }, },
2903 R = Renderer3D { Inputs = {
2904 Width = Input { Value = 32, },
2905 Height = Input { Value = 32, },
2906 SceneInput = Input { SourceOp = "M", Source = "Output", },
2907 }, },
2908 } }"#;
2909 let comp = Comp::from_fusion_str(src).unwrap();
2910 let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0);
2911 let px = eng.readback_rgba(&tex).unwrap();
2912 let o = (16 * 32 + 16) * 4;
2913 let rgba = [px[o], px[o + 1], px[o + 2], px[o + 3]];
2914 assert!(rgba[0] >= 250 && rgba[1] <= 5 && (rgba[2] as i32 - 128).abs() <= 4 && rgba[3] >= 250, "unexpected MtlChanBool pixel {rgba:?}");
2915 }
2916
2917 #[test]
2918 fn bender3d_and_replicate3d_render_end_to_end() {
2919 let Ok(mut eng) = Engine::new_headless() else { return };
2920 let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() {
2921 Dest = Shape3D { Inputs = {
2922 ["SurfacePlaneInputs.Width"] = Input { Value = 1.6, },
2923 ["SurfacePlaneInputs.SubdivisionWidth"] = Input { Value = 1, },
2924 }, },
2925 Dot = Shape3D { Inputs = {
2926 ["SurfacePlaneInputs.Width"] = Input { Value = 0.3, },
2927 ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 1.0, },
2928 ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.2, },
2929 ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.0, },
2930 ["MtlStdInputs.ReceivesLighting"] = Input { Value = 0, },
2931 }, },
2932 BentDot = Bender3D { Inputs = {
2933 SceneInput = Input { SourceOp = "Dot", Source = "Output", },
2934 Bender = Input { Value = FuID { "Twist" }, },
2935 Amount = Input { Value = 0.25, },
2936 }, },
2937 Rep = Replicate3D { Inputs = {
2938 Destination = Input { SourceOp = "Dest", Source = "Output", },
2939 Input1 = Input { SourceOp = "BentDot", Source = "Output", },
2940 }, },
2941 Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4.5, }, }, },
2942 M = Merge3D { Inputs = {
2943 SceneInput1 = Input { SourceOp = "Rep", Source = "Output", },
2944 SceneInput2 = Input { SourceOp = "Cam", Source = "Output", },
2945 }, },
2946 R = Renderer3D { Inputs = {
2947 Width = Input { Value = 64, },
2948 Height = Input { Value = 64, },
2949 SceneInput = Input { SourceOp = "M", Source = "Output", },
2950 }, },
2951 } }"#;
2952 let comp = Comp::from_fusion_str(src).unwrap();
2953 let (tex, _) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0);
2954 let px = eng.readback_rgba(&tex).unwrap();
2955 // 4 corners of the destination plane should produce non-empty orange pixels, while center (32, 32) is empty!
2956 let center_a = px[(32 * 64 + 32) * 4 + 3];
2957 let lit_pixels = px.chunks_exact(4).filter(|p| p[0] > 200 && p[3] > 200).count();
2958 assert_eq!(center_a, 0, "center between 4 replicated corners should be transparent");
2959 assert!(lit_pixels >= 40, "expected 4 replicated corner quads to render, got {lit_pixels} pixels");
2960 }
2620}2961}
crates/engine/src/scene3d/shader.rs+391-115
...@@ -24,13 +24,15 @@ pub struct Vertex3D {...@@ -24,13 +24,15 @@ pub struct Vertex3D {
24pub(super) struct MeshUniform {24pub(super) struct MeshUniform {
25 pub(super) mvp: [f32; 16],25 pub(super) mvp: [f32; 16],
26 pub(super) model: [f32; 16],26 pub(super) model: [f32; 16],
27 /// Camera view matrix (used by `MtlChanBool` Eye-space position/normal operands).
28 pub(super) view: [f32; 16],
27 /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture)29 /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture)
28 pub(super) dod: [f32; 4],30 pub(super) dod: [f32; 4],
29 /// `[use_tex, lighting_enabled, specular_intensity, flip_normals]`31 /// `[use_diffuse_tex, lighting_enabled, specular_intensity, flip_normals]`
30 pub(super) flags: [f32; 4],32 pub(super) flags: [f32; 4],
31 /// Diffuse color multiplier `(r, g, b, a)`33 /// Diffuse color multiplier `(r, g, b, a)`
32 pub(super) diffuse_col: [f32; 4],34 pub(super) diffuse_col: [f32; 4],
33 /// Specular color `(r, g, b, shininess_exponent)`35 /// Specular color `(r, g, b, shininess / roughness / ward_spread_u)`
34 pub(super) specular_col: [f32; 4],36 pub(super) specular_col: [f32; 4],
35 /// Ambient light `(r, g, b, 0)`37 /// Ambient light `(r, g, b, 0)`
36 pub(super) ambient: [f32; 4],38 pub(super) ambient: [f32; 4],
...@@ -46,7 +48,7 @@ pub(super) struct MeshUniform {...@@ -46,7 +48,7 @@ pub(super) struct MeshUniform {
46 pub(super) uv_xform: [f32; 4],48 pub(super) uv_xform: [f32; 4],
47 /// UV translation, wrap mode and unlit light-pass count `[tx, ty, wrap, passes]`49 /// UV translation, wrap mode and unlit light-pass count `[tx, ty, wrap, passes]`
48 pub(super) uv_off_wrap: [f32; 4],50 pub(super) uv_off_wrap: [f32; 4],
49 /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance 3=Pbr]`51 /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance 3=Pbr 4=Ward]`
50 pub(super) mat_fx: [f32; 4],52 pub(super) mat_fx: [f32; 4],
51 /// Bump UV affine matrix, column-major `[m00, m10, m01, m11]`53 /// Bump UV affine matrix, column-major `[m00, m10, m01, m11]`
52 pub(super) bump_uv_xform: [f32; 4],54 pub(super) bump_uv_xform: [f32; 4],
...@@ -56,8 +58,32 @@ pub(super) struct MeshUniform {...@@ -56,8 +58,32 @@ pub(super) struct MeshUniform {
56 pub(super) bump_dod: [f32; 4],58 pub(super) bump_dod: [f32; 4],
57 /// `[bump_clamp_z, bump_channel, bump_filter_size, 0]`59 /// `[bump_clamp_z, bump_channel, bump_filter_size, 0]`
58 pub(super) bump_params: [f32; 4],60 pub(super) bump_params: [f32; 4],
59 /// `[diffuse_color_alpha, refractive_index, do_fresnel, 0]`61 /// `[diffuse_color_alpha, refractive_index, do_fresnel, ward_spread_v]`
60 pub(super) mtl_params: [f32; 4],62 pub(super) mtl_params: [f32; 4],
63 /// Environment inverse rotation col 0 + `env_mode` (`0=none, 1=SphereMap, 2=MtlReflect`)
64 pub(super) env_rot_0: [f32; 4],
65 /// Environment inverse rotation col 1 + `env_map_mode` (`0=equirect, 1=angular`)
66 pub(super) env_rot_1: [f32; 4],
67 /// Environment inverse rotation col 2 + `env_tex_slot` (`0=solid, 1=mat_tex, 2=bump_tex`)
68 pub(super) env_rot_2: [f32; 4],
69 /// `[start_angle_norm, inv_angle_span, strength_variability, constant_strength]`
70 pub(super) env_angles: [f32; 4],
71 /// `[glancing_strength, face_on_strength, falloff, refract_ior]`
72 pub(super) refl_params: [f32; 4],
73 /// `[refl_tint_r, refl_tint_g, refl_tint_b, has_bg_material]`
74 pub(super) refl_tint: [f32; 4],
75 /// `[refract_tint_r, refract_tint_g, refract_tint_b, 0]`
76 pub(super) refract_tint: [f32; 4],
77 /// `MtlChanBool` operand A indices `[r, g, b, a]`
78 pub(super) cb_ops_a: [f32; 4],
79 /// `MtlChanBool` operation indices `[r, g, b, a]`
80 pub(super) cb_ops: [f32; 4],
81 /// `MtlChanBool` operand B indices `[r, g, b, a]`
82 pub(super) cb_ops_b: [f32; 4],
83 /// `MtlChanBool` foreground material constant RGBA
84 pub(super) cb_fg_col: [f32; 4],
85 /// `[cb_enabled, cb_coord_space (0=Model,1=World,2=Eye), cb_fg_tex_slot (0=none,2=bump_tex), 0]`
86 pub(super) cb_flags: [f32; 4],
61 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`87 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`
62 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],88 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],
63 /// Point light colors * intensity `(r, g, b, 0)`89 /// Point light colors * intensity `(r, g, b, 0)`
...@@ -177,6 +203,7 @@ pub(super) const SHADER_3D: &str = r#"...@@ -177,6 +203,7 @@ pub(super) const SHADER_3D: &str = r#"
177struct MeshUniform {203struct MeshUniform {
178 mvp: mat4x4<f32>,204 mvp: mat4x4<f32>,
179 model: mat4x4<f32>,205 model: mat4x4<f32>,
206 view: mat4x4<f32>,
180 dod: vec4<f32>,207 dod: vec4<f32>,
181 flags: vec4<f32>,208 flags: vec4<f32>,
182 diffuse_col: vec4<f32>,209 diffuse_col: vec4<f32>,
...@@ -194,6 +221,18 @@ struct MeshUniform {...@@ -194,6 +221,18 @@ struct MeshUniform {
194 bump_dod: vec4<f32>,221 bump_dod: vec4<f32>,
195 bump_params: vec4<f32>,222 bump_params: vec4<f32>,
196 mtl_params: vec4<f32>,223 mtl_params: vec4<f32>,
224 env_rot_0: vec4<f32>,
225 env_rot_1: vec4<f32>,
226 env_rot_2: vec4<f32>,
227 env_angles: vec4<f32>,
228 refl_params: vec4<f32>,
229 refl_tint: vec4<f32>,
230 refract_tint: vec4<f32>,
231 cb_ops_a: vec4<f32>,
232 cb_ops: vec4<f32>,
233 cb_ops_b: vec4<f32>,
234 cb_fg_col: vec4<f32>,
235 cb_flags: vec4<f32>,
197 point_pos: array<vec4<f32>, MAX_LIGHTS>,236 point_pos: array<vec4<f32>, MAX_LIGHTS>,
198 point_col: array<vec4<f32>, MAX_LIGHTS>,237 point_col: array<vec4<f32>, MAX_LIGHTS>,
199 spot_pos: array<vec4<f32>, MAX_LIGHTS>,238 spot_pos: array<vec4<f32>, MAX_LIGHTS>,
...@@ -226,6 +265,8 @@ struct VsOut {...@@ -226,6 +265,8 @@ struct VsOut {
226 @location(0) uv: vec2<f32>,265 @location(0) uv: vec2<f32>,
227 @location(1) world_pos: vec3<f32>,266 @location(1) world_pos: vec3<f32>,
228 @location(2) world_n: vec3<f32>,267 @location(2) world_n: vec3<f32>,
268 @location(3) local_pos: vec3<f32>,
269 @location(4) local_n: vec3<f32>,
229};270};
230271
231// Cofactor matrix of the upper-left 3x3 of `m` (inverse-transpose up to scale), so normals stay272// 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 {...@@ -249,10 +290,14 @@ fn vs_mesh(v: VsIn) -> VsOut {
249 let wn = normal_matrix(u.model) * v.normal;290 let wn = normal_matrix(u.model) * v.normal;
250 let nlen = length(wn);291 let nlen = length(wn);
251 var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5);292 var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5);
293 var ln = v.normal;
252 if (u.flags.w > 0.5) {294 if (u.flags.w > 0.5) {
253 n_norm = -n_norm;295 n_norm = -n_norm;
296 ln = -ln;
254 }297 }
255 out.world_n = n_norm;298 out.world_n = n_norm;
299 out.local_pos = v.pos;
300 out.local_n = ln;
256 return out;301 return out;
257}302}
258303
...@@ -307,8 +352,44 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos:...@@ -307,8 +352,44 @@ fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos:
307 return occluded / 9.0;352 return occluded / 9.0;
308}353}
309354
355struct TangentFrame {
356 t: vec3<f32>,
357 b: vec3<f32>,
358};
359
360fn compute_tangent_frame(
361 base_n: vec3<f32>,
362 dpdx_w: vec3<f32>,
363 dpdy_w: vec3<f32>,
364 duvdx: vec2<f32>,
365 duvdy: vec2<f32>,
366) -> TangentFrame {
367 let det = duvdx.x * duvdy.y - duvdx.y * duvdy.x;
368 var t_vec: vec3<f32>;
369 var b_vec: vec3<f32>;
370 if (abs(det) > 1e-6) {
371 let inv_det = 1.0 / det;
372 t_vec = (dpdx_w * duvdy.y - dpdy_w * duvdx.y) * inv_det;
373 b_vec = (dpdy_w * duvdx.x - dpdx_w * duvdy.x) * inv_det;
374 t_vec = t_vec - base_n * dot(t_vec, base_n);
375 let t_len = length(t_vec);
376 if (t_len > 1e-5) {
377 t_vec = t_vec / t_len;
378 let b_sign = select(-1.0, 1.0, dot(cross(base_n, t_vec), b_vec) >= 0.0);
379 b_vec = cross(base_n, t_vec) * b_sign;
380 return TangentFrame(t_vec, b_vec);
381 }
382 }
383 let up = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(base_n.y) > 0.9);
384 t_vec = normalize(cross(up, base_n));
385 b_vec = cross(base_n, t_vec);
386 return TangentFrame(t_vec, b_vec);
387}
388
310fn eval_light_contrib(389fn eval_light_contrib(
311 n: vec3<f32>,390 n: vec3<f32>,
391 t_vec: vec3<f32>,
392 b_vec: vec3<f32>,
312 v: vec3<f32>,393 v: vec3<f32>,
313 l: vec3<f32>,394 l: vec3<f32>,
314 light_rgb: vec3<f32>,395 light_rgb: vec3<f32>,
...@@ -356,6 +437,17 @@ fn eval_light_contrib(...@@ -356,6 +437,17 @@ fn eval_light_contrib(
356 fresnel = 0.5 * r_s * r_s * (1.0 + r_p * r_p);437 fresnel = 0.5 * r_s * r_s * (1.0 + r_p * r_p);
357 }438 }
358 lobe = (fresnel * d_term * g_term) / (4.0 * nv);439 lobe = (fresnel * d_term * g_term) / (4.0 * nv);
440 } else if (model == 4) {
441 // Anisotropic Ward (1992) BRDF * (N·L) using tangent frame (T, B) and SpreadU/SpreadV.
442 let nh = max(dot(n, h), 1e-3);
443 let nv = max(dot(n, v), 1e-3);
444 let su = max(shininess, 1e-3);
445 let sv = max(u.mtl_params.w, 1e-3);
446 let ht = dot(h, t_vec) / su;
447 let hb = dot(h, b_vec) / sv;
448 let expo = -(ht * ht + hb * hb) / (nh * nh);
449 let denom = max(4.0 * 3.14159265 * su * sv * sqrt(nv), 1e-4);
450 lobe = (sqrt(ndotl) / denom) * exp(max(expo, -80.0));
359 } else {451 } else {
360 lobe = pow(max(dot(n, h), 0.0), shininess);452 lobe = pow(max(dot(n, h), 0.0), shininess);
361 }453 }
...@@ -404,30 +496,9 @@ fn perturb_bump_normal(...@@ -404,30 +496,9 @@ fn perturb_bump_normal(
404 let canvas_px = vec2<f32>(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w);496 let canvas_px = vec2<f32>(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w);
405 uv = (canvas_px - u.bump_dod.xy) / bdims;497 uv = (canvas_px - u.bump_dod.xy) / bdims;
406 }498 }
407 let det = duvdx.x * duvdy.y - duvdx.y * duvdy.x;499 let frame = compute_tangent_frame(base_n, dpdx_w, dpdy_w, duvdx, duvdy);
408 var t_vec: vec3<f32>;500 let t_vec = frame.t;
409 var b_vec: vec3<f32>;501 let b_vec = frame.b;
410 if (abs(det) > 1e-6) {
411 let inv_det = 1.0 / det;
412 t_vec = (dpdx_w * duvdy.y - dpdy_w * duvdx.y) * inv_det;
413 b_vec = (dpdy_w * duvdx.x - dpdx_w * duvdy.x) * inv_det;
414 // Gram-Schmidt orthogonalize against base_n
415 t_vec = t_vec - base_n * dot(t_vec, base_n);
416 let t_len = length(t_vec);
417 if (t_len > 1e-5) {
418 t_vec = t_vec / t_len;
419 let b_sign = select(-1.0, 1.0, dot(cross(base_n, t_vec), b_vec) >= 0.0);
420 b_vec = cross(base_n, t_vec) * b_sign;
421 } else {
422 let up = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(base_n.y) > 0.9);
423 t_vec = normalize(cross(up, base_n));
424 b_vec = cross(base_n, t_vec);
425 }
426 } else {
427 let up = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(base_n.y) > 0.9);
428 t_vec = normalize(cross(up, base_n));
429 b_vec = cross(base_n, t_vec);
430 }
431502
432 if (bump_mode > 0.5) {503 if (bump_mode > 0.5) {
433 let b_col = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv, bump_wrap), 0.0);504 let b_col = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv, bump_wrap), 0.0);
...@@ -448,6 +519,126 @@ fn perturb_bump_normal(...@@ -448,6 +519,126 @@ fn perturb_bump_normal(
448 return normalize(base_n - t_vec * dhdu + b_vec * dhdv);519 return normalize(base_n - t_vec * dhdu + b_vec * dhdv);
449}520}
450521
522fn sample_sphere_map(world_dir: vec3<f32>) -> vec4<f32> {
523 let slot = i32(u.env_rot_2.w + 0.5);
524 if (slot == 0) {
525 return vec4<f32>(u.refl_tint.rgb, 1.0);
526 }
527 let rot = mat3x3<f32>(u.env_rot_0.xyz, u.env_rot_1.xyz, u.env_rot_2.xyz);
528 let d = normalize(rot * world_dir);
529 let map_mode = i32(u.env_rot_1.w + 0.5);
530 var uv: vec2<f32>;
531 if (map_mode == 1) {
532 let r_xy = length(d.xy);
533 let r = select(0.0, acos(clamp(-d.z, -1.0, 1.0)) / (3.14159265 * r_xy), r_xy > 1e-5);
534 uv = clamp(vec2<f32>(0.5 + d.x * r * 0.5, 0.5 - d.y * r * 0.5), vec2<f32>(0.0), vec2<f32>(1.0));
535 } else {
536 let theta = atan2(d.x, d.z);
537 var u_c = fract(theta / 6.2831853 + 0.75);
538 u_c = fract((u_c - u.env_angles.x) * u.env_angles.y);
539 let v_c = acos(clamp(d.y, -1.0, 1.0)) / 3.14159265;
540 uv = vec2<f32>(u_c, v_c);
541 }
542 var raw: vec4<f32>;
543 if (slot == 2) {
544 if (u.bump_dod.z > 0.5 && u.bump_dod.w > 0.5) {
545 let dims = vec2<f32>(textureDimensions(bump_tex));
546 uv = clamp((vec2<f32>(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w) - u.bump_dod.xy) / dims, vec2<f32>(0.0), vec2<f32>(1.0));
547 }
548 raw = textureSampleLevel(bump_tex, mat_samp, uv, 0.0);
549 } else {
550 if (u.dod.z > 0.5 && u.dod.w > 0.5) {
551 let dims = vec2<f32>(textureDimensions(mat_tex));
552 uv = clamp((vec2<f32>(uv.x * u.dod.z, uv.y * u.dod.w) - u.dod.xy) / dims, vec2<f32>(0.0), vec2<f32>(1.0));
553 }
554 raw = textureSampleLevel(mat_tex, mat_samp, uv, 0.0);
555 }
556 let straight = select(vec3<f32>(0.0), raw.rgb / max(raw.a, 1e-5), raw.a > 1e-5);
557 return vec4<f32>(straight * u.refl_tint.rgb, raw.a);
558}
559
560fn cb_hls(c: vec3<f32>) -> vec3<f32> {
561 let mx = max(c.r, max(c.g, c.b));
562 let mn = min(c.r, min(c.g, c.b));
563 let l = 0.5 * (mx + mn);
564 let d = mx - mn;
565 if (d <= 1e-6) {
566 return vec3<f32>(0.0, l, 0.0);
567 }
568 let s = d / max(1.0 - abs(2.0 * l - 1.0), 1e-6);
569 var h = 0.0;
570 if (mx == c.r) {
571 h = (c.g - c.b) / d + select(0.0, 6.0, c.g < c.b);
572 } else if (mx == c.g) {
573 h = (c.b - c.r) / d + 2.0;
574 } else {
575 h = (c.r - c.g) / d + 4.0;
576 }
577 return vec3<f32>(h / 6.0, l, clamp(s, 0.0, 1.0));
578}
579
580fn cb_operand(
581 idx: i32,
582 bg: vec4<f32>,
583 fg: vec4<f32>,
584 pos: vec3<f32>,
585 uv: vec2<f32>,
586 env_c: vec3<f32>,
587 n: vec3<f32>,
588) -> f32 {
589 switch idx {
590 case 0: { return fg.r; }
591 case 1: { return fg.g; }
592 case 2: { return fg.b; }
593 case 3: { return fg.a; }
594 case 4: { return bg.r; }
595 case 5: { return bg.g; }
596 case 6: { return bg.b; }
597 case 7: { return bg.a; }
598 case 8: { return 0.0; }
599 case 9: { return 1.0; }
600 case 10: { return 0.5; }
601 case 11: { return cb_hls(fg.rgb).x; }
602 case 12: { return cb_hls(fg.rgb).y; }
603 case 13: { return cb_hls(fg.rgb).z; }
604 case 14: { return cb_hls(bg.rgb).x; }
605 case 15: { return cb_hls(bg.rgb).y; }
606 case 16: { return cb_hls(bg.rgb).z; }
607 case 17: { return dot(fg.rgb, vec3<f32>(0.299, 0.587, 0.114)); }
608 case 18: { return dot(bg.rgb, vec3<f32>(0.299, 0.587, 0.114)); }
609 case 19: { return pos.x; }
610 case 20: { return pos.y; }
611 case 21: { return pos.z; }
612 case 22: { return uv.x; }
613 case 23: { return 1.0 - uv.y; }
614 case 24: { return 0.0; }
615 case 25: { return env_c.x; }
616 case 26: { return env_c.y; }
617 case 27: { return env_c.z; }
618 case 28: { return n.x; }
619 case 29: { return n.y; }
620 case 30: { return n.z; }
621 default: { return bg.r; }
622 }
623}
624
625fn cb_combine(op: i32, a: f32, b: f32) -> f32 {
626 switch op {
627 case 0: { return a; }
628 case 1: { return b; }
629 case 2: { return 1.0 - a; }
630 case 3: { return 1.0 - b; }
631 case 4: { return a + b; }
632 case 5: { return a - b; }
633 case 6: { return a * b; }
634 case 7: { return select(a / b, 0.0, abs(b) <= 1e-5); }
635 case 8: { return min(a, b); }
636 case 9: { return max(a, b); }
637 case 10: { return 0.5 * (a + b); }
638 default: { return a; }
639 }
640}
641
451@fragment642@fragment
452fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {643fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
453 let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap);644 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<f32> {...@@ -456,109 +647,194 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
456 let dpdy_w = dpdy(in.world_pos);647 let dpdy_w = dpdy(in.world_pos);
457 let duvdx = dpdx(uv_bump_xformed);648 let duvdx = dpdx(uv_bump_xformed);
458 let duvdy = dpdy(uv_bump_xformed);649 let duvdy = dpdy(uv_bump_xformed);
650 let duvdx_main = dpdx(uv_xformed);
651 let duvdy_main = dpdy(uv_xformed);
459 let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0;652 let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0;
460 if (facing_away != BACK_PASS) {653 if (facing_away != BACK_PASS) {
461 discard;654 discard;
462 }655 }
463656
464 var col = u.diffuse_col;657 let env_mode = i32(u.env_rot_0.w + 0.5);
465 var tex_col = vec4<f32>(1.0);658 let cb_on = u.cb_flags.x > 0.5;
466 var uv_samp = uv_xformed;659 let v_dir = normalize(u.cam_pos.xyz - in.world_pos);
467 var tex_straight = vec3<f32>(1.0);660 var n_surf = normalize(in.world_n);
468 if (u.flags.x > 0.5) {661 if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) {
469 if (u.dod.z > 0.5 && u.dod.w > 0.5) {662 n_surf = perturb_bump_normal(
470 let tdims = vec2<f32>(textureDimensions(mat_tex));663 n_surf,
471 let canvas_px = vec2<f32>(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w);664 dpdx_w,
472 uv_samp = (canvas_px - u.dod.xy) / tdims;665 dpdy_w,
473 if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) {666 duvdx,
474 discard;667 duvdy,
475 }668 uv_bump_xformed,
476 }669 u.mat_fx.x,
477 tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0);670 u.mat_fx.y,
478 if (u.mat_fx.z <= 0.5) {671 u.bump_off_wrap.z,
479 tex_straight = select(vec3<f32>(0.0), tex_col.rgb / max(tex_col.a, 1e-5), tex_col.a > 1e-5);672 u.bump_params.x,
480 }673 i32(u.bump_params.y + 0.5),
481 col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col;674 );
482 }
483 // `rgb_alpha` is `tex_col.a * Diffuse.Opacity`; `Diffuse.Color.Alpha` (`u.mtl_params.x`)
484 // modulates output alpha without attenuating diffuse/specular RGB.
485 let rgb_alpha = col.a;
486 let out_alpha = rgb_alpha * u.mtl_params.x;
487 if (out_alpha <= 0.002) {
488 discard;
489 }675 }
490676
491 // `u.diffuse_col` is straight (not premultiplied by `u.diffuse_col.a`), while `tex_col` is premultiplied.677 var base_straight = vec3<f32>(0.0);
492 let albedo = tex_straight * u.diffuse_col.rgb;678 var rgb_alpha = u.diffuse_col.a;
493 if (u.flags.y > 0.5) {679 var out_alpha = rgb_alpha * u.mtl_params.x;
494 var n = normalize(in.world_n);680
495 if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) {681 if (env_mode == 1) {
496 n = perturb_bump_normal(682 // Standalone SphereMap shader: equirectangular/angular lookup along view ray.
497 n,683 let env_c = sample_sphere_map(-v_dir);
498 dpdx_w,684 base_straight = env_c.rgb * u.diffuse_col.rgb;
499 dpdy_w,685 rgb_alpha = env_c.a * u.diffuse_col.a;
500 duvdx,686 out_alpha = rgb_alpha * u.mtl_params.x;
501 duvdy,687 } else {
502 uv_bump_xformed,688 var col = u.diffuse_col;
503 u.mat_fx.x,689 var tex_col = vec4<f32>(1.0);
504 u.mat_fx.y,690 var uv_samp = uv_xformed;
505 u.bump_off_wrap.z,691 var tex_straight = vec3<f32>(1.0);
506 u.bump_params.x,692 if (u.flags.x > 0.5) {
507 i32(u.bump_params.y + 0.5),693 if (u.dod.z > 0.5 && u.dod.w > 0.5) {
508 );694 let tdims = vec2<f32>(textureDimensions(mat_tex));
695 let canvas_px = vec2<f32>(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w);
696 uv_samp = (canvas_px - u.dod.xy) / tdims;
697 if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) {
698 discard;
699 }
700 }
701 tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0);
702 if (u.mat_fx.z <= 0.5) {
703 tex_straight = select(vec3<f32>(0.0), tex_col.rgb / max(tex_col.a, 1e-5), tex_col.a > 1e-5);
704 }
705 col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col;
509 }706 }
510 let v = normalize(u.cam_pos.xyz - in.world_pos);707 // `rgb_alpha` is `tex_col.a * Diffuse.Opacity`; `Diffuse.Color.Alpha` (`u.mtl_params.x`)
511 let spec_rgb = u.specular_col.rgb;708 // modulates output alpha without attenuating diffuse/specular RGB.
512 let shininess = select(max(u.specular_col.w, 1.0), u.specular_col.w, u.mat_fx.w > 1.5);709 rgb_alpha = col.a;
513 let spec_int = u.flags.z;710 out_alpha = rgb_alpha * u.mtl_params.x;
514711 if (env_mode == 0 && !cb_on && out_alpha <= 0.002) {
515 var lit = albedo * u.ambient.rgb;712 discard;
516 let n_dir = i32(u.light_counts.z + 0.5);
517 for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) {
518 if (i >= n_dir) { break; }
519 let l = normalize(u.dir_to_light[i].xyz);
520 lit = lit + eval_light_contrib(n, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0);
521 }713 }
522714
523 let n_pt = i32(u.light_counts.x + 0.5);715 let albedo = tex_straight * u.diffuse_col.rgb;
524 for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) {716 if (env_mode == 2 && u.refl_tint.w < 0.5) {
525 if (i >= n_pt) { break; }717 base_straight = vec3<f32>(0.0);
526 let to_l = u.point_pos[i].xyz - in.world_pos;718 rgb_alpha = 0.0;
527 let dist = max(length(to_l), 1e-4);719 out_alpha = 0.0;
528 let att = light_attenuation(dist, u.point_pos[i].w);720 } else if (u.flags.y > 0.5) {
529 // Shadow density dims only the diffuse term; specular is cut outright.721 let tframe = compute_tangent_frame(n_surf, dpdx_w, dpdy_w, duvdx_main, duvdy_main);
530 var occ = 0.0;722 let spec_rgb = u.specular_col.rgb;
531 if (u.light_counts.w > 0.5) {723 let shininess = select(max(u.specular_col.w, 1.0), u.specular_col.w, u.mat_fx.w > 1.5);
532 occ = point_shadow_occlusion(i, in.world_pos, n, u.point_pos[i].xyz);724 let spec_int = u.flags.z;
725
726 var lit = albedo * u.ambient.rgb;
727 let n_dir = i32(u.light_counts.z + 0.5);
728 for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) {
729 if (i >= n_dir) { break; }
730 let l = normalize(u.dir_to_light[i].xyz);
731 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);
732 }
733
734 let n_pt = i32(u.light_counts.x + 0.5);
735 for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) {
736 if (i >= n_pt) { break; }
737 let to_l = u.point_pos[i].xyz - in.world_pos;
738 let dist = max(length(to_l), 1e-4);
739 let att = light_attenuation(dist, u.point_pos[i].w);
740 var occ = 0.0;
741 if (u.light_counts.w > 0.5) {
742 occ = point_shadow_occlusion(i, in.world_pos, n_surf, u.point_pos[i].xyz);
743 }
744 lit = lit + eval_light_contrib(
745 n_surf, tframe.t, tframe.b, v_dir, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess,
746 1.0 - shadow.point[i].y * occ, 1.0 - occ,
747 );
533 }748 }
534 lit = lit + eval_light_contrib(749
535 n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess,750 let n_sp = i32(u.light_counts.y + 0.5);
536 1.0 - shadow.point[i].y * occ, 1.0 - occ,751 for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) {
537 );752 if (i >= n_sp) { break; }
753 let to_l = u.spot_pos[i].xyz - in.world_pos;
754 let dist = max(length(to_l), 1e-4);
755 let l_dir = to_l / dist;
756 let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz));
757 let cos_inner = u.spot_pos[i].w;
758 let cos_outer = u.spot_dir[i].w;
759 let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0);
760 if (cone > 0.0) {
761 let att = light_attenuation(dist, u.spot_col[i].w) * cone;
762 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);
763 }
764 }
765 base_straight = lit;
766 } else {
767 base_straight = albedo * u.uv_off_wrap.w;
538 }768 }
539769
540 let n_sp = i32(u.light_counts.y + 0.5);770 if (env_mode == 2) {
541 for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) {771 let r_dir = reflect(-v_dir, n_surf);
542 if (i >= n_sp) { break; }772 let refl_c = sample_sphere_map(r_dir);
543 let to_l = u.spot_pos[i].xyz - in.world_pos;773 let strength_var = i32(u.env_angles.z + 0.5);
544 let dist = max(length(to_l), 1e-4);774 var refl_str = clamp(u.env_angles.w, 0.0, 1.0);
545 let l_dir = to_l / dist;775 if (strength_var != 0) {
546 // spot_dir.xyz is direction spotlight points; fragment direction from light is -l_dir776 let cos_nv = clamp(dot(n_surf, v_dir), 0.0, 1.0);
547 let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz));777 let f_ang = pow(1.0 - cos_nv, max(u.refl_params.z, 1e-4));
548 let cos_inner = u.spot_pos[i].w;778 refl_str = clamp(mix(u.refl_params.y, u.refl_params.x, f_ang), 0.0, 1.0);
549 let cos_outer = u.spot_dir[i].w;779 }
550 let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0);780 var under_rgb = base_straight;
551 if (cone > 0.0) {781 var under_a = rgb_alpha;
552 let att = light_attenuation(dist, u.spot_col[i].w) * cone;782 if (rgb_alpha < 0.999 && u.refl_params.w > 0.01 && u.env_rot_2.w > 0.5 && u.refl_tint.w > 0.5) {
553 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);783 let eta = 1.0 / max(u.refl_params.w, 0.01);
784 var refr_dir = refract(-v_dir, n_surf, eta);
785 if (dot(refr_dir, refr_dir) < 1e-5) {
786 refr_dir = r_dir;
787 }
788 let refr_c = sample_sphere_map(refr_dir);
789 under_rgb = mix(refr_c.rgb * u.refract_tint.rgb, base_straight, rgb_alpha);
790 under_a = clamp(max(rgb_alpha, refr_c.a * (1.0 - rgb_alpha)), 0.0, 1.0);
554 }791 }
792 let under_premul = under_rgb * under_a;
793 let refl_a = refl_str * refl_c.a;
794 let out_premul = under_premul * (1.0 - refl_str) + refl_c.rgb * refl_a;
795 let final_a = clamp(under_a * (1.0 - refl_str) + refl_a, 0.0, 1.0);
796 base_straight = select(vec3<f32>(0.0), out_premul / max(final_a, 1e-5), final_a > 1e-5);
797 rgb_alpha = final_a;
798 out_alpha = clamp(out_alpha * (1.0 - refl_str) + refl_a, 0.0, 1.0);
555 }799 }
800 }
556801
557 col = vec4<f32>(clamp(lit * rgb_alpha, vec3<f32>(0.0), vec3<f32>(1.0)), out_alpha);802 if (cb_on) {
558 } else {803 let bg_c = vec4<f32>(base_straight, out_alpha);
559 col = vec4<f32>(clamp(albedo * u.uv_off_wrap.w * rgb_alpha, vec3<f32>(0.0), vec3<f32>(1.0)), out_alpha);804 var fg_c = u.cb_fg_col;
805 if (u.cb_flags.z > 1.5) {
806 let fg_raw = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv_xformed, u.bump_off_wrap.z), 0.0);
807 let fg_s = select(vec3<f32>(0.0), fg_raw.rgb / max(fg_raw.a, 1e-5), fg_raw.a > 1e-5);
808 fg_c = vec4<f32>(fg_s * u.cb_fg_col.rgb, fg_raw.a * u.cb_fg_col.a);
809 }
810 let cspace = i32(u.cb_flags.y + 0.5);
811 var c_pos = in.world_pos;
812 var c_n = n_surf;
813 if (cspace == 0) {
814 c_pos = in.local_pos;
815 c_n = normalize(in.local_n);
816 } else if (cspace == 2) {
817 c_pos = (u.view * vec4<f32>(in.world_pos, 1.0)).xyz;
818 let en = (u.view * vec4<f32>(n_surf, 0.0)).xyz;
819 let elen = length(en);
820 c_n = select(vec3<f32>(0.0, 0.0, 1.0), en / elen, elen > 1e-5);
821 }
822 let env_c = reflect(-v_dir, n_surf);
823 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));
824 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));
825 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));
826 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));
827 let clamped_a = clamp(a_out, 0.0, 1.0);
828 if (clamped_a <= 0.002) {
829 discard;
830 }
831 return vec4<f32>(clamp(vec3<f32>(r_out, g_out, b_out) * clamped_a, vec3<f32>(0.0), vec3<f32>(1.0)), clamped_a);
560 }832 }
561 return col;833
834 if (out_alpha <= 0.002) {
835 discard;
836 }
837 return vec4<f32>(clamp(base_straight * rgb_alpha, vec3<f32>(0.0), vec3<f32>(1.0)), out_alpha);
562}838}
563839
564@fragment840@fragment
...@@ -589,7 +865,7 @@ fn fs_normal(in: VsOut) -> @location(0) vec4<f32> {...@@ -589,7 +865,7 @@ fn fs_normal(in: VsOut) -> @location(0) vec4<f32> {
589 col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col;865 col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col;
590 }866 }
591 let out_alpha = col.a * u.mtl_params.x;867 let out_alpha = col.a * u.mtl_params.x;
592 if (out_alpha <= 0.002) {868 if (i32(u.env_rot_0.w + 0.5) == 0 && u.cb_flags.x < 0.5 && out_alpha <= 0.002) {
593 discard;869 discard;
594 }870 }
595871