| 1 | //! 3D mesh deformers (`Bender3D`) and vertex instancing (`Replicate3D`). |
| 2 | |
| 3 | use std::collections::HashMap; |
| 4 | use std::sync::Arc; |
| 5 | |
| 6 | use super::collect::mat4_inverse; |
| 7 | use super::math::{ |
| 8 | mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, |
| 9 | }; |
| 10 | use super::mesh::{build_shape_mesh, triangle_soup}; |
| 11 | use super::{Mat4, MeshInstance, ShapeKind, Vertex3D}; |
| 12 | |
| 13 | /// Maximum number of meshes allowed in a collected 3D scene (shared with `collect.rs`). |
| 14 | pub(super) const MAX_SCENE_MESHES: usize = 16_384; |
| 15 | |
| 16 | /// Deformation mode of `Bender3D`. |
| 17 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 18 | pub enum BenderMode { |
| 19 | Bend, |
| 20 | Taper, |
| 21 | Twist, |
| 22 | Shear, |
| 23 | } |
| 24 | |
| 25 | /// Evaluated parameters for a `Bender3D` node. |
| 26 | #[derive(Clone, Copy, Debug)] |
| 27 | pub 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 | |
| 44 | impl 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] |
| 60 | fn 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] |
| 65 | fn 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] |
| 70 | fn 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] |
| 79 | fn 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] |
| 85 | pub(super) fn 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] |
| 94 | fn 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] |
| 105 | pub(super) fn 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 basis `(u, v, w)`: `w` is the bend axis and `u` the direction the ends bend |
| 122 | /// toward (`X -> +Y`, `Y -> +Z`, `Z -> +X`), rotated by `angle_deg` toward `v = w x u`. |
| 123 | fn bender_basis(axis: u32, angle_deg: f32) -> ([f32; 3], [f32; 3], [f32; 3]) { |
| 124 | let (u0, v0, w) = match axis { |
| 125 | 0 => ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]), |
| 126 | 2 => ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), |
| 127 | _ => ([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), |
| 128 | }; |
| 129 | let (s, c) = angle_deg.to_radians().sin_cos(); |
| 130 | let u = [0, 1, 2].map(|i| u0[i] * c + v0[i] * s); |
| 131 | let v = [0, 1, 2].map(|i| -u0[i] * s + v0[i] * c); |
| 132 | (u, v, w) |
| 133 | } |
| 134 | |
| 135 | fn axis_bounds_of(verts: &[Vertex3D], w: [f32; 3]) -> Option<[f32; 2]> { |
| 136 | let mut mn = f32::INFINITY; |
| 137 | let mut mx = f32::NEG_INFINITY; |
| 138 | for v in verts { |
| 139 | let p = vec3_dot(v.pos, w); |
| 140 | mn = mn.min(p); |
| 141 | mx = mx.max(p); |
| 142 | } |
| 143 | (mn.is_finite() && mx.is_finite()).then_some([mn, mx]) |
| 144 | } |
| 145 | |
| 146 | /// Applies `Bender3D` deformation to `verts` in-place, turning their normals with it. |
| 147 | pub fn deform_mesh_vertices( |
| 148 | verts: &mut [Vertex3D], |
| 149 | params: &Bender3DParams, |
| 150 | shared_bounds: Option<[f32; 2]>, |
| 151 | ) { |
| 152 | if verts.is_empty() || !params.amount.is_finite() || params.amount.abs() < 1e-6 { |
| 153 | return; |
| 154 | } |
| 155 | let angle_deg = if params.angle_deg.is_finite() { params.angle_deg } else { 0.0 }; |
| 156 | let (u, v, w) = bender_basis(params.axis, angle_deg); |
| 157 | let Some([min_w, max_w]) = shared_bounds.or_else(|| axis_bounds_of(verts, w)) else { |
| 158 | return; |
| 159 | }; |
| 160 | let extent = max_w - min_w; |
| 161 | if !extent.is_finite() || extent <= 1e-6 { |
| 162 | return; |
| 163 | } |
| 164 | let raw_r_min = if params.range_min.is_finite() { params.range_min } else { 0.0 }; |
| 165 | let raw_r_max = if params.range_max.is_finite() { params.range_max } else { 1.0 }; |
| 166 | let r_min_frac = raw_r_min.clamp(0.0, 1.0); |
| 167 | let r_max_frac = raw_r_max.clamp(r_min_frac, 1.0); |
| 168 | if (r_max_frac - r_min_frac) <= 1e-6 { |
| 169 | return; |
| 170 | } |
| 171 | let center_frac = if params.center.is_finite() { |
| 172 | params.center.clamp(0.0, 1.0) |
| 173 | } else { |
| 174 | 0.5 |
| 175 | }; |
| 176 | let w0 = min_w + center_frac * extent; |
| 177 | let r_min = min_w + r_min_frac * extent; |
| 178 | let r_max = min_w + r_max_frac * extent; |
| 179 | let amount = params.amount; |
| 180 | let k = amount * std::f32::consts::TAU / extent; |
| 181 | // Deformation in bender coordinates `(u, v, w)`; outside the range the clamped end's frame |
| 182 | // carries the rest of the mesh rigidly. |
| 183 | let warp = |[pu, pv, pw]: [f32; 3]| -> [f32; 3] { |
| 184 | let wc = pw.clamp(r_min, r_max); |
| 185 | let w_ext = pw - wc; |
| 186 | let t = (wc - w0) / extent; |
| 187 | match params.mode { |
| 188 | // Amount = 1.0 bends the full extent into a closed circle. |
| 189 | BenderMode::Bend if k.abs() > 1e-6 => { |
| 190 | let (st, ct) = (k * (wc - w0)).sin_cos(); |
| 191 | let r = 1.0 / k; |
| 192 | [r - (r - pu) * ct + w_ext * st, pv, w0 + (r - pu) * st + w_ext * ct] |
| 193 | } |
| 194 | BenderMode::Bend => [pu, pv, pw], |
| 195 | BenderMode::Taper => { |
| 196 | let s = (1.0 + amount * 2.0 * t).max(0.0); |
| 197 | [pu * s, pv * s, pw] |
| 198 | } |
| 199 | BenderMode::Twist => { |
| 200 | let (st, ct) = (amount * std::f32::consts::TAU * t).sin_cos(); |
| 201 | [pu * ct - pv * st, pu * st + pv * ct, pw] |
| 202 | } |
| 203 | BenderMode::Shear => [pu + amount * (wc - w0), pv, pw], |
| 204 | } |
| 205 | }; |
| 206 | let to_world = |[a, b, c]: [f32; 3]| [0, 1, 2].map(|i| u[i] * a + v[i] * b + w[i] * c); |
| 207 | let eps = extent * 1e-4; |
| 208 | for vert in verts.iter_mut() { |
| 209 | let p = [vec3_dot(vert.pos, u), vec3_dot(vert.pos, v), vec3_dot(vert.pos, w)]; |
| 210 | let n = [vec3_dot(vert.normal, u), vec3_dot(vert.normal, v), vec3_dot(vert.normal, w)]; |
| 211 | // Fusion turns normals with the warp's local rotation and ignores its stretch: the |
| 212 | // cofactor of the Jacobian (central differences) with unit columns. |
| 213 | let [ja, jb, jc] = [0, 1, 2].map(|axis| { |
| 214 | let (mut lo, mut hi) = (p, p); |
| 215 | lo[axis] -= eps; |
| 216 | hi[axis] += eps; |
| 217 | vec3_norm(vec3_sub(warp(hi), warp(lo))).unwrap_or([0.0; 3]) |
| 218 | }); |
| 219 | let cof = [vec3_cross(jb, jc), vec3_cross(jc, ja), vec3_cross(ja, jb)]; |
| 220 | let n_def = [0, 1, 2].map(|i| cof[0][i] * n[0] + cof[1][i] * n[1] + cof[2][i] * n[2]); |
| 221 | vert.pos = to_world(warp(p)); |
| 222 | vert.normal = vec3_norm(to_world(n_def)).unwrap_or(vert.normal); |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | /// Applies `Bender3D` in the bender's own space to collected child meshes, each within its own |
| 227 | /// bounds or, with `group`, within their shared bounds. |
| 228 | pub fn apply_bender_to_meshes( |
| 229 | meshes: &mut [MeshInstance], |
| 230 | bender_world: Mat4, |
| 231 | params: &Bender3DParams, |
| 232 | image_plane_aspect: impl Fn(&MeshInstance) -> f32, |
| 233 | ) { |
| 234 | if meshes.is_empty() || !params.amount.is_finite() || params.amount.abs() < 1e-6 { |
| 235 | return; |
| 236 | } |
| 237 | let inv_bender = mat4_inverse(bender_world); |
| 238 | let angle_deg = if params.angle_deg.is_finite() { params.angle_deg } else { 0.0 }; |
| 239 | let (_, _, w_axis) = bender_basis(params.axis, angle_deg); |
| 240 | let baked: Vec<(Vec<Vertex3D>, Vec<u32>)> = meshes |
| 241 | .iter() |
| 242 | .map(|m| { |
| 243 | let rel = mat4_mul(inv_bender, m.world); |
| 244 | let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), image_plane_aspect(m)); |
| 245 | for vert in &mut verts { |
| 246 | vert.pos = xform_point(rel, vert.pos); |
| 247 | vert.normal = xform_normal(rel, vert.normal); |
| 248 | } |
| 249 | (verts, idx) |
| 250 | }) |
| 251 | .collect(); |
| 252 | let shared = params |
| 253 | .group |
| 254 | .then(|| { |
| 255 | baked.iter().filter_map(|(v, _)| axis_bounds_of(v, w_axis)).reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])]) |
| 256 | }) |
| 257 | .flatten(); |
| 258 | for (m, (mut verts, idx)) in meshes.iter_mut().zip(baked) { |
| 259 | if idx.is_empty() { |
| 260 | continue; |
| 261 | } |
| 262 | deform_mesh_vertices(&mut verts, params, shared); |
| 263 | let (_, fx) = m.shape.split_fx(); |
| 264 | m.shape = ShapeKind::WithMaterialFx { |
| 265 | inner: Box::new(ShapeKind::CustomMesh(Arc::new(triangle_soup((verts, idx))))), |
| 266 | fx, |
| 267 | }; |
| 268 | m.world = bender_world; |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | /// World-space destination point + orthonormal TBN frame extracted for `Replicate3D`. |
| 273 | #[derive(Clone, Copy, Debug)] |
| 274 | pub struct ReplicatePoint { |
| 275 | pub pos: [f32; 3], |
| 276 | pub normal: [f32; 3], |
| 277 | pub tangent: [f32; 3], |
| 278 | pub bitangent: [f32; 3], |
| 279 | } |
| 280 | |
| 281 | /// Extracts deduplicated world-space vertex frames from destination meshes for `Replicate3D`. |
| 282 | pub fn extract_replicate_points( |
| 283 | dest_meshes: &[MeshInstance], |
| 284 | step: usize, |
| 285 | max_points: usize, |
| 286 | ) -> Vec<ReplicatePoint> { |
| 287 | if dest_meshes.is_empty() || max_points == 0 { |
| 288 | return Vec::new(); |
| 289 | } |
| 290 | let stride = step.max(1); |
| 291 | let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64); |
| 292 | |
| 293 | struct Accum { |
| 294 | pos: [f32; 3], |
| 295 | normal: [f32; 3], |
| 296 | tangent: [f32; 3], |
| 297 | } |
| 298 | |
| 299 | let mut order: Vec<[i64; 3]> = Vec::new(); |
| 300 | let mut table: HashMap<[i64; 3], Accum> = HashMap::new(); |
| 301 | |
| 302 | for dm in dest_meshes { |
| 303 | let (verts, indices) = build_shape_mesh(dm.shape.base_shape(), 1.0); |
| 304 | if verts.is_empty() { |
| 305 | continue; |
| 306 | } |
| 307 | // Compute per-vertex tangents from triangles when available. |
| 308 | let mut tangents = vec![[0.0_f32; 3]; verts.len()]; |
| 309 | for tri in indices.chunks_exact(3) { |
| 310 | let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize); |
| 311 | if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() { |
| 312 | continue; |
| 313 | } |
| 314 | let e1 = vec3_sub(verts[i1].pos, verts[i0].pos); |
| 315 | let e2 = vec3_sub(verts[i2].pos, verts[i0].pos); |
| 316 | let du1 = verts[i1].uv[0] - verts[i0].uv[0]; |
| 317 | let dv1 = verts[i1].uv[1] - verts[i0].uv[1]; |
| 318 | let du2 = verts[i2].uv[0] - verts[i0].uv[0]; |
| 319 | let dv2 = verts[i2].uv[1] - verts[i0].uv[1]; |
| 320 | let det = du1 * dv2 - dv1 * du2; |
| 321 | let t_tri = if det.abs() > 1e-6 { |
| 322 | let inv = 1.0 / det; |
| 323 | [ |
| 324 | (e1[0] * dv2 - e2[0] * dv1) * inv, |
| 325 | (e1[1] * dv2 - e2[1] * dv1) * inv, |
| 326 | (e1[2] * dv2 - e2[2] * dv1) * inv, |
| 327 | ] |
| 328 | } else { |
| 329 | e1 |
| 330 | }; |
| 331 | for idx in [i0, i1, i2] { |
| 332 | tangents[idx][0] += t_tri[0]; |
| 333 | tangents[idx][1] += t_tri[1]; |
| 334 | tangents[idx][2] += t_tri[2]; |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | for (vi, v) in verts.iter().enumerate() { |
| 339 | let wp = xform_point(dm.world, v.pos); |
| 340 | let wn = xform_normal(dm.world, v.normal); |
| 341 | let wt = xform_vector(dm.world, tangents[vi]); |
| 342 | let k = key(wp); |
| 343 | if let Some(acc) = table.get_mut(&k) { |
| 344 | acc.normal[0] += wn[0]; |
| 345 | acc.normal[1] += wn[1]; |
| 346 | acc.normal[2] += wn[2]; |
| 347 | acc.tangent[0] += wt[0]; |
| 348 | acc.tangent[1] += wt[1]; |
| 349 | acc.tangent[2] += wt[2]; |
| 350 | } else { |
| 351 | order.push(k); |
| 352 | table.insert(k, Accum { pos: wp, normal: wn, tangent: wt }); |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | let mut out = Vec::with_capacity((order.len() / stride + 1).min(max_points)); |
| 358 | for (idx, k) in order.into_iter().enumerate() { |
| 359 | if idx % stride != 0 { |
| 360 | continue; |
| 361 | } |
| 362 | if out.len() >= max_points { |
| 363 | break; |
| 364 | } |
| 365 | let acc = &table[&k]; |
| 366 | let n = vec3_norm(acc.normal).unwrap_or([0.0, 0.0, 1.0]); |
| 367 | // Gram-Schmidt orthogonalize tangent against normal; fallback when degenerate. |
| 368 | let t_proj = [ |
| 369 | acc.tangent[0] - n[0] * vec3_dot(acc.tangent, n), |
| 370 | acc.tangent[1] - n[1] * vec3_dot(acc.tangent, n), |
| 371 | acc.tangent[2] - n[2] * vec3_dot(acc.tangent, n), |
| 372 | ]; |
| 373 | let t = vec3_norm(t_proj).unwrap_or_else(|| { |
| 374 | let up = if n[1].abs() > 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; |
| 375 | vec3_norm(vec3_cross(up, n)).unwrap_or([1.0, 0.0, 0.0]) |
| 376 | }); |
| 377 | let b = vec3_norm(vec3_cross(n, t)).unwrap_or([0.0, 1.0, 0.0]); |
| 378 | out.push(ReplicatePoint { pos: acc.pos, normal: n, tangent: t, bitangent: b }); |
| 379 | } |
| 380 | out |
| 381 | } |
| 382 | |
| 383 | /// Builds the placement matrix for a destination point according to `Replicate3D.Alignment`: |
| 384 | /// - `0`: Not aligned (translation only) |
| 385 | /// - `1`: Aligned (aligns local `+Z` to destination vertex normal) |
| 386 | /// - `2`: TBN Aligned (aligns local X/Y/Z to destination vertex T/B/N frame) |
| 387 | pub fn replicate_alignment_matrix(pt: &ReplicatePoint, alignment: i32) -> Mat4 { |
| 388 | match alignment { |
| 389 | 1 => { |
| 390 | let z = pt.normal; |
| 391 | let up = if z[1].abs() > 0.99 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; |
| 392 | let x = vec3_norm(vec3_cross(up, z)).unwrap_or([1.0, 0.0, 0.0]); |
| 393 | let y = vec3_cross(z, x); |
| 394 | [ |
| 395 | x[0], x[1], x[2], 0.0, |
| 396 | y[0], y[1], y[2], 0.0, |
| 397 | z[0], z[1], z[2], 0.0, |
| 398 | pt.pos[0], pt.pos[1], pt.pos[2], 1.0, |
| 399 | ] |
| 400 | } |
| 401 | 2 => { |
| 402 | let x = pt.tangent; |
| 403 | let y = pt.bitangent; |
| 404 | let z = pt.normal; |
| 405 | [ |
| 406 | x[0], x[1], x[2], 0.0, |
| 407 | y[0], y[1], y[2], 0.0, |
| 408 | z[0], z[1], z[2], 0.0, |
| 409 | pt.pos[0], pt.pos[1], pt.pos[2], 1.0, |
| 410 | ] |
| 411 | } |
| 412 | _ => mat4_translate(pt.pos[0], pt.pos[1], pt.pos[2]), |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | /// Evaluated parameters for a `Replicate3D` node. |
| 417 | #[derive(Clone, Debug)] |
| 418 | pub struct Replicate3DParams { |
| 419 | pub random_input: bool, |
| 420 | /// `0 = Not aligned`, `1 = Aligned`, `2 = TBN Aligned`. |
| 421 | pub alignment: i32, |
| 422 | pub base_xform: Mat4, |
| 423 | pub random_seed: u64, |
| 424 | pub jitter_prob: f32, |
| 425 | pub jitter_translate: [f32; 3], |
| 426 | pub jitter_rotate: [f32; 3], |
| 427 | pub jitter_pivot: [f32; 3], |
| 428 | pub jitter_scale: [f32; 3], |
| 429 | } |
| 430 | |
| 431 | fn splitmix64_signed(mut x: u64) -> f32 { |
| 432 | x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 433 | x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 434 | x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 435 | x ^= x >> 31; |
| 436 | ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5 |
| 437 | } |
| 438 | |
| 439 | fn splitmix64_u64(mut x: u64) -> u64 { |
| 440 | x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 441 | x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 442 | x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 443 | x ^ (x >> 31) |
| 444 | } |
| 445 | |
| 446 | /// Instantiates `source_templates` (`Input1..InputN`) onto `dest_points` while honoring |
| 447 | /// `MAX_SCENE_MESHES` so large destination meshes never exhaust memory. |
| 448 | pub fn replicate_meshes( |
| 449 | dest_points: &[ReplicatePoint], |
| 450 | source_templates: &[Vec<MeshInstance>], |
| 451 | node_world: Mat4, |
| 452 | params: &Replicate3DParams, |
| 453 | out_meshes: &mut Vec<MeshInstance>, |
| 454 | ) { |
| 455 | if dest_points.is_empty() || source_templates.is_empty() { |
| 456 | return; |
| 457 | } |
| 458 | let has_jitter = params.jitter_translate.iter().any(|v| v.abs() > 1e-5) |
| 459 | || params.jitter_rotate.iter().any(|v| v.abs() > 1e-5) |
| 460 | || params.jitter_pivot.iter().any(|v| v.abs() > 1e-5) |
| 461 | || params.jitter_scale.iter().any(|v| v.abs() > 1e-5); |
| 462 | |
| 463 | for (idx, pt) in dest_points.iter().enumerate() { |
| 464 | if out_meshes.len() >= MAX_SCENE_MESHES { |
| 465 | break; |
| 466 | } |
| 467 | let s = params |
| 468 | .random_seed |
| 469 | .wrapping_mul(6_364_136_223_846_793_005) |
| 470 | .wrapping_add((idx as u64).wrapping_mul(1_442_695_040_888_963_407)); |
| 471 | let tpl_idx = if params.random_input { |
| 472 | (splitmix64_u64(s ^ 17) as usize) % source_templates.len() |
| 473 | } else { |
| 474 | idx % source_templates.len() |
| 475 | }; |
| 476 | let template = &source_templates[tpl_idx]; |
| 477 | if template.is_empty() { |
| 478 | continue; |
| 479 | } |
| 480 | |
| 481 | let place = replicate_alignment_matrix(pt, params.alignment); |
| 482 | let mut inst_m = mat4_mul(node_world, mat4_mul(place, params.base_xform)); |
| 483 | if has_jitter && (params.jitter_prob >= 0.9999 || (splitmix64_signed(s ^ 13) + 0.5) <= params.jitter_prob) { |
| 484 | let tx = splitmix64_signed(s ^ 1) * params.jitter_translate[0]; |
| 485 | let ty = splitmix64_signed(s ^ 2) * params.jitter_translate[1]; |
| 486 | let tz = splitmix64_signed(s ^ 3) * params.jitter_translate[2]; |
| 487 | let rx = (splitmix64_signed(s ^ 4) * params.jitter_rotate[0]).to_radians(); |
| 488 | let ry = (splitmix64_signed(s ^ 5) * params.jitter_rotate[1]).to_radians(); |
| 489 | let rz = (splitmix64_signed(s ^ 6) * params.jitter_rotate[2]).to_radians(); |
| 490 | let sx = (1.0 + splitmix64_signed(s ^ 7) * params.jitter_scale[0]).max(1e-4); |
| 491 | let sy = (1.0 + splitmix64_signed(s ^ 8) * params.jitter_scale[1]).max(1e-4); |
| 492 | let sz = (1.0 + splitmix64_signed(s ^ 9) * params.jitter_scale[2]).max(1e-4); |
| 493 | let px = splitmix64_signed(s ^ 10) * params.jitter_pivot[0]; |
| 494 | let py = splitmix64_signed(s ^ 11) * params.jitter_pivot[1]; |
| 495 | let pz = splitmix64_signed(s ^ 12) * params.jitter_pivot[2]; |
| 496 | let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))); |
| 497 | let jm = mat4_mul( |
| 498 | mat4_translate(tx + px, ty + py, tz + pz), |
| 499 | mat4_mul(rot, mat4_mul(mat4_scale(sx, sy, sz), mat4_translate(-px, -py, -pz))), |
| 500 | ); |
| 501 | inst_m = mat4_mul(inst_m, jm); |
| 502 | } |
| 503 | |
| 504 | for src_m in template { |
| 505 | if out_meshes.len() >= MAX_SCENE_MESHES { |
| 506 | break; |
| 507 | } |
| 508 | let mut cloned = src_m.clone(); |
| 509 | cloned.world = mat4_mul(inst_m, src_m.world); |
| 510 | out_meshes.push(cloned); |
| 511 | } |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | #[cfg(test)] |
| 516 | mod tests { |
| 517 | use super::*; |
| 518 | use crate::scene3d::math::mat4_identity; |
| 519 | use crate::scene3d::MaterialFx; |
| 520 | |
| 521 | fn dummy_mesh(shape: ShapeKind, world: Mat4) -> MeshInstance { |
| 522 | MeshInstance { |
| 523 | world, |
| 524 | shape: ShapeKind::WithMaterialFx { |
| 525 | inner: Box::new(shape), |
| 526 | fx: MaterialFx::default(), |
| 527 | }, |
| 528 | material_node: None, |
| 529 | bump_node: None, |
| 530 | text3d: None, |
| 531 | diffuse_col: [1.0, 1.0, 1.0, 1.0], |
| 532 | specular_col: [1.0, 1.0, 1.0], |
| 533 | specular_intensity: 1.0, |
| 534 | specular_exponent: 50.0, |
| 535 | affected_by_lights: true, |
| 536 | casts_shadow: true, |
| 537 | receives_shadows: true, |
| 538 | flip_normals: false, |
| 539 | displace: None, |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | #[test] |
| 544 | fn bender_bend_follows_fusion_axes_and_turns_normals() { |
| 545 | let shape = ShapeKind::Plane { width: 1.0, height: 2.0, sub_w: 4, sub_h: 8 }; |
| 546 | let bend = |angle_deg: f32| { |
| 547 | let (mut verts, _) = build_shape_mesh(&shape, 1.0); |
| 548 | let params = Bender3DParams { mode: BenderMode::Bend, amount: 0.5, axis: 1, angle_deg, center: 0.5, range_min: 0.0, range_max: 1.0, group: false }; |
| 549 | deform_mesh_vertices(&mut verts, &params, None); |
| 550 | verts |
| 551 | }; |
| 552 | let mean = |verts: &[Vertex3D], top: bool, axis: usize| { |
| 553 | let edge: Vec<f32> = verts.iter().filter(|v| (v.uv[1] < 0.01) == top && (v.uv[1] > 0.99) != top).map(|v| v.pos[axis]).collect(); |
| 554 | edge.iter().sum::<f32>() / edge.len() as f32 |
| 555 | }; |
| 556 | // Amount 0.5 bends the height into a half circle of radius 2 / pi opening toward +Z. |
| 557 | let verts = bend(0.0); |
| 558 | let r = 2.0 / std::f32::consts::PI; |
| 559 | for (top, y) in [(true, r), (false, -r)] { |
| 560 | assert!((mean(&verts, top, 2) - r).abs() < 1e-3 && (mean(&verts, top, 1) - y).abs() < 1e-3); |
| 561 | } |
| 562 | let top_n = verts.iter().find(|v| v.uv[1] < 0.01).unwrap().normal; |
| 563 | assert!(top_n[1] < -0.99, "the top end's +Z normal turns toward the bend centre: {top_n:?}"); |
| 564 | // Angle 90 turns the bend toward +X. |
| 565 | assert!(mean(&bend(90.0), true, 0) > 0.6); |
| 566 | } |
| 567 | |
| 568 | #[test] |
| 569 | fn bender_taper_twist_shear_and_range_clamp() { |
| 570 | let shape = ShapeKind::Plane { width: 2.0, height: 2.0, sub_w: 4, sub_h: 4 }; |
| 571 | |
| 572 | // Taper: top (+Y) expands, bottom (-Y) shrinks. |
| 573 | let (mut v_taper, _) = build_shape_mesh(&shape, 1.0); |
| 574 | deform_mesh_vertices(&mut v_taper, &Bender3DParams { |
| 575 | mode: BenderMode::Taper, |
| 576 | amount: 0.5, |
| 577 | axis: 1, |
| 578 | center: 0.5, |
| 579 | ..Default::default() |
| 580 | }, None); |
| 581 | 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); |
| 582 | 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); |
| 583 | 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}"); |
| 584 | |
| 585 | // Twist: rotates corners out of z=0 plane. |
| 586 | let (mut v_twist, _) = build_shape_mesh(&shape, 1.0); |
| 587 | deform_mesh_vertices(&mut v_twist, &Bender3DParams { |
| 588 | mode: BenderMode::Twist, |
| 589 | amount: 0.5, |
| 590 | axis: 1, |
| 591 | center: 0.5, |
| 592 | ..Default::default() |
| 593 | }, None); |
| 594 | let max_z = v_twist.iter().map(|v| v.pos[2].abs()).fold(0.0_f32, f32::max); |
| 595 | assert!(max_z > 0.5, "twist should rotate vertices out of XY plane, max_z={max_z}"); |
| 596 | |
| 597 | // Shear with RangeMin=0.5 leaves bottom half unsheared (all at constant offset for wc=0) and shears top half. |
| 598 | let (mut v_shear, _) = build_shape_mesh(&shape, 1.0); |
| 599 | deform_mesh_vertices(&mut v_shear, &Bender3DParams { |
| 600 | mode: BenderMode::Shear, |
| 601 | amount: 1.0, |
| 602 | axis: 1, |
| 603 | center: 0.5, |
| 604 | range_min: 0.5, |
| 605 | range_max: 1.0, |
| 606 | ..Default::default() |
| 607 | }, None); |
| 608 | // Bending/shearing along the Y axis moves vertices toward +Z. |
| 609 | let top_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] < 0.01).unwrap().pos[2]; |
| 610 | let bot_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] > 0.99).unwrap().pos[2]; |
| 611 | assert!((top_shift - 1.0).abs() < 1e-4, "top center should shear by +1.0, got {top_shift}"); |
| 612 | assert!(bot_shift.abs() < 1e-4, "bottom below RangeMin should stay at 0, got {bot_shift}"); |
| 613 | } |
| 614 | |
| 615 | #[test] |
| 616 | fn bender_group_mode_deforms_multiple_meshes_in_shared_bounds() { |
| 617 | let mut meshes = vec![ |
| 618 | dummy_mesh(ShapeKind::Cube { width: 1.0, sub: 2, faces: 0b11_1111 }, mat4_translate(0.0, -1.0, 0.0)), |
| 619 | dummy_mesh(ShapeKind::Cube { width: 1.0, sub: 2, faces: 0b11_1111 }, mat4_translate(0.0, 1.0, 0.0)), |
| 620 | ]; |
| 621 | apply_bender_to_meshes( |
| 622 | &mut meshes, |
| 623 | mat4_identity(), |
| 624 | &Bender3DParams { |
| 625 | mode: BenderMode::Taper, |
| 626 | amount: 0.5, |
| 627 | axis: 1, |
| 628 | center: 0.5, |
| 629 | group: true, |
| 630 | ..Default::default() |
| 631 | }, |
| 632 | |_| 1.0, |
| 633 | ); |
| 634 | let ShapeKind::CustomMesh(v0) = meshes[0].shape.base_shape() else { panic!("expected custom mesh") }; |
| 635 | let ShapeKind::CustomMesh(v1) = meshes[1].shape.base_shape() else { panic!("expected custom mesh") }; |
| 636 | let bot_w = v0.iter().map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); |
| 637 | let top_w = v1.iter().map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); |
| 638 | assert!(top_w > bot_w * 1.4, "group taper should widen upper cube relative to lower cube: {top_w} vs {bot_w}"); |
| 639 | } |
| 640 | |
| 641 | #[test] |
| 642 | fn replicate_extracts_unique_vertices_aligns_normals_and_respects_cap() { |
| 643 | // 1x1 subdivided cube has 8 unique corner vertices (36 triangle-soup vertices across 6 faces). |
| 644 | let dest = vec![dummy_mesh(ShapeKind::Cube { width: 2.0, sub: 1, faces: 0b11_1111 }, mat4_identity())]; |
| 645 | let pts = extract_replicate_points(&dest, 1, MAX_SCENE_MESHES); |
| 646 | assert_eq!(pts.len(), 8, "cube with sub=1 should deduplicate to 8 corner points"); |
| 647 | for pt in &pts { |
| 648 | // Corner normal should point radially outward along pos. |
| 649 | assert!(vec3_dot(pt.pos, pt.normal) > 0.5, "corner normal should point outward: {pt:?}"); |
| 650 | } |
| 651 | |
| 652 | let src_tpl = vec![vec![dummy_mesh(ShapeKind::Plane { width: 0.2, height: 0.2, sub_w: 1, sub_h: 1 }, mat4_identity())]]; |
| 653 | let mut out = Vec::new(); |
| 654 | let params = Replicate3DParams { |
| 655 | random_input: false, |
| 656 | alignment: 1, |
| 657 | base_xform: mat4_identity(), |
| 658 | random_seed: 0, |
| 659 | jitter_prob: 1.0, |
| 660 | jitter_translate: [0.0; 3], |
| 661 | jitter_rotate: [0.0; 3], |
| 662 | jitter_pivot: [0.0; 3], |
| 663 | jitter_scale: [0.0; 3], |
| 664 | }; |
| 665 | replicate_meshes(&pts, &src_tpl, mat4_identity(), &params, &mut out); |
| 666 | assert_eq!(out.len(), 8); |
| 667 | // Aligned mode aligns local +Z (column 2 of world) with destination normal. |
| 668 | let z_col = [out[0].world[8], out[0].world[9], out[0].world[10]]; |
| 669 | assert!(vec3_dot(z_col, pts[0].normal) > 0.99, "aligned +Z should match vertex normal"); |
| 670 | |
| 671 | // Cap enforcement: pre-fill close to MAX_SCENE_MESHES and verify we never exceed it. |
| 672 | 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]; |
| 673 | replicate_meshes(&pts, &src_tpl, mat4_identity(), &params, &mut capped); |
| 674 | assert_eq!(capped.len(), MAX_SCENE_MESHES, "must strictly enforce MAX_SCENE_MESHES cap"); |
| 675 | } |
| 676 | } |