| 1 | //! Procedural 3D mesh builders and heightmap vertex displacement. |
| 2 | |
| 3 | use super::shader::Vertex3D; |
| 4 | use super::{DisplaceHeightmap, ShapeKind}; |
| 5 | |
| 6 | pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) { |
| 7 | match shape { |
| 8 | ShapeKind::ImagePlane => build_image_plane(tex_aspect), |
| 9 | ShapeKind::Plane { width, height, sub_w, sub_h } => build_plane(*width, *height, *sub_w, *sub_h), |
| 10 | ShapeKind::TextPlate { width, height, depth, slices } => { |
| 11 | build_text_plate(*width, *height, *depth, *slices) |
| 12 | } |
| 13 | ShapeKind::Sphere { radius, sub_base, sub_height } => { |
| 14 | build_sphere(*radius, *sub_base, *sub_height) |
| 15 | } |
| 16 | ShapeKind::Cylinder { |
| 17 | radius, |
| 18 | height, |
| 19 | start_sweep_deg, |
| 20 | end_sweep_deg, |
| 21 | sub_base, |
| 22 | sub_height, |
| 23 | top_cap, |
| 24 | bottom_cap, |
| 25 | } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, [*sub_base, *sub_height], [*top_cap, *bottom_cap]), |
| 26 | ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces), |
| 27 | ShapeKind::CustomMesh(verts) => { |
| 28 | let v = verts.as_ref().clone(); |
| 29 | let idx = (0..v.len() as u32).collect(); |
| 30 | (v, idx) |
| 31 | } |
| 32 | ShapeKind::WithMaterialFx { inner, .. } => build_shape_mesh(inner, tex_aspect), |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | fn build_image_plane(tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u32>) { |
| 37 | let hx = 0.5; |
| 38 | let hy = 0.5 / tex_aspect.max(1e-4); |
| 39 | let verts = vec![ |
| 40 | Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] }, |
| 41 | Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, |
| 42 | Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, |
| 43 | Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] }, |
| 44 | ]; |
| 45 | (verts, vec![0, 1, 2, 0, 2, 3]) |
| 46 | } |
| 47 | |
| 48 | /// Appends a `sub_w` x `sub_h` grid spanning the quad `tl`/`tr`/`bl` (UV `(0,0)` at `tl`, V down), |
| 49 | /// splitting each cell along its bottom-left to top-right diagonal. |
| 50 | fn push_quad_grid( |
| 51 | verts: &mut Vec<Vertex3D>, |
| 52 | idx: &mut Vec<u32>, |
| 53 | normal: [f32; 3], |
| 54 | [tl, tr, bl]: [[f32; 3]; 3], |
| 55 | sub_w: u32, |
| 56 | sub_h: u32, |
| 57 | ) { |
| 58 | let base = verts.len() as u32; |
| 59 | for iy in 0..=sub_h { |
| 60 | let v = iy as f32 / sub_h as f32; |
| 61 | for ix in 0..=sub_w { |
| 62 | let u = ix as f32 / sub_w as f32; |
| 63 | let pos = std::array::from_fn(|k| tl[k] + (tr[k] - tl[k]) * u + (bl[k] - tl[k]) * v); |
| 64 | verts.push(Vertex3D { pos, normal, uv: [u, v] }); |
| 65 | } |
| 66 | } |
| 67 | let row = sub_w + 1; |
| 68 | for iy in 0..sub_h { |
| 69 | for ix in 0..sub_w { |
| 70 | let a = base + iy * row + ix; |
| 71 | let (b, c, d) = (a + row, a + row + 1, a + 1); |
| 72 | idx.extend_from_slice(&[a, b, d, b, c, d]); |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | fn build_plane(width: f32, height: f32, sub_w: u32, sub_h: u32) -> (Vec<Vertex3D>, Vec<u32>) { |
| 78 | let (hx, hy) = (width * 0.5, height * 0.5); |
| 79 | let (mut verts, mut idx) = (Vec::new(), Vec::new()); |
| 80 | push_quad_grid( |
| 81 | &mut verts, |
| 82 | &mut idx, |
| 83 | [0.0, 0.0, 1.0], |
| 84 | [[-hx, hy, 0.0], [hx, hy, 0.0], [-hx, -hy, 0.0]], |
| 85 | sub_w.clamp(1, 64), |
| 86 | sub_h.clamp(1, 64), |
| 87 | ); |
| 88 | (verts, idx) |
| 89 | } |
| 90 | |
| 91 | fn build_text_plate(width: f32, height: f32, depth: f32, slices: u32) -> (Vec<Vertex3D>, Vec<u32>) { |
| 92 | let hx = width * 0.5; |
| 93 | let hy = height * 0.5; |
| 94 | let n_slices = if depth.abs() > 1e-4 { slices.clamp(2, 16) } else { 1 }; |
| 95 | let mut verts = Vec::with_capacity((n_slices * 4) as usize); |
| 96 | let mut idx = Vec::with_capacity((n_slices * 6) as usize); |
| 97 | for s in 0..n_slices { |
| 98 | let t = if n_slices == 1 { 0.0 } else { s as f32 / (n_slices - 1) as f32 }; |
| 99 | // Fusion Text3D extrudes backward along -Z from z=0 to z=-depth |
| 100 | let z = -t * depth; |
| 101 | let nz = if n_slices > 1 && s == n_slices - 1 { -1.0 } else { 1.0 }; |
| 102 | let base = verts.len() as u32; |
| 103 | verts.push(Vertex3D { pos: [-hx, hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 0.0] }); |
| 104 | verts.push(Vertex3D { pos: [-hx, -hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 1.0] }); |
| 105 | verts.push(Vertex3D { pos: [ hx, -hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 1.0] }); |
| 106 | verts.push(Vertex3D { pos: [ hx, hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 0.0] }); |
| 107 | idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); |
| 108 | } |
| 109 | (verts, idx) |
| 110 | } |
| 111 | |
| 112 | fn build_sphere(radius: f32, sub_base: u32, sub_height: u32) -> (Vec<Vertex3D>, Vec<u32>) { |
| 113 | let seg_u = sub_base.clamp(12, 96); |
| 114 | let seg_v = sub_height.clamp(8, 64); |
| 115 | let mut verts = Vec::with_capacity(((seg_u + 1) * (seg_v + 1)) as usize); |
| 116 | let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize); |
| 117 | for iv in 0..=seg_v { |
| 118 | let v = iv as f32 / seg_v as f32; |
| 119 | let phi = v * std::f32::consts::PI; // 0 (top +Y) -> PI (bottom -Y) |
| 120 | let (sp, cp) = phi.sin_cos(); |
| 121 | for iu in 0..=seg_u { |
| 122 | let u = iu as f32 / seg_u as f32; |
| 123 | // Fusion Shape3D Sphere places u=0.75 facing +Z (verified via probe_archive_3d f02) |
| 124 | let theta = (u - 0.75) * std::f32::consts::TAU; |
| 125 | let (st, ct) = theta.sin_cos(); |
| 126 | let nx = sp * st; |
| 127 | let ny = cp; |
| 128 | let nz = sp * ct; |
| 129 | verts.push(Vertex3D { |
| 130 | pos: [nx * radius, ny * radius, nz * radius], |
| 131 | normal: [nx, ny, nz], |
| 132 | uv: [u, v], |
| 133 | }); |
| 134 | } |
| 135 | } |
| 136 | let row = seg_u + 1; |
| 137 | // Rows draw top-down, each from +X through the front (+Z) to the back, Fusion's order. |
| 138 | for iv in 0..seg_v { |
| 139 | for iu in (0..seg_u).rev() { |
| 140 | let a = iv * row + iu; |
| 141 | let b = (iv + 1) * row + iu; |
| 142 | let c = (iv + 1) * row + iu + 1; |
| 143 | let d = iv * row + iu + 1; |
| 144 | idx.extend_from_slice(&[a, b, d, b, c, d]); |
| 145 | } |
| 146 | } |
| 147 | (verts, idx) |
| 148 | } |
| 149 | |
| 150 | fn build_cylinder( |
| 151 | radius: f32, |
| 152 | height: f32, |
| 153 | start_sweep_deg: f32, |
| 154 | end_sweep_deg: f32, |
| 155 | [sub_base, sub_height]: [u32; 2], |
| 156 | caps: [bool; 2], |
| 157 | ) -> (Vec<Vertex3D>, Vec<u32>) { |
| 158 | let seg_u = sub_base.clamp(16, 96); |
| 159 | let seg_v = sub_height.clamp(1, 256); |
| 160 | let half_h = height * 0.5; |
| 161 | let a0 = start_sweep_deg.to_radians(); |
| 162 | let a1 = end_sweep_deg.to_radians(); |
| 163 | let rows = seg_v + 1; |
| 164 | let mut verts = Vec::with_capacity(((seg_u + 1) * rows) as usize); |
| 165 | let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize); |
| 166 | for iu in 0..=seg_u { |
| 167 | let u = iu as f32 / seg_u as f32; |
| 168 | // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc |
| 169 | let theta = a0 + (a1 - a0) * u; |
| 170 | let (nz, nx) = theta.sin_cos(); |
| 171 | for iv in 0..rows { |
| 172 | let v = iv as f32 / seg_v as f32; |
| 173 | verts.push(Vertex3D { pos: [nx * radius, half_h - height * v, nz * radius], normal: [nx, 0.0, nz], uv: [1.0 - u, v] }); |
| 174 | } |
| 175 | } |
| 176 | for iu in 0..seg_u { |
| 177 | for iv in 0..seg_v { |
| 178 | let a = iu * rows + iv; |
| 179 | let (b, d) = (a + 1, a + rows); |
| 180 | idx.extend_from_slice(&[a, b, d, b, d + 1, d]); |
| 181 | } |
| 182 | } |
| 183 | for (cap, (y, ny)) in caps.into_iter().zip([(half_h, 1.0), (-half_h, -1.0)]) { |
| 184 | if !cap { |
| 185 | continue; |
| 186 | } |
| 187 | let base = verts.len() as u32; |
| 188 | verts.push(Vertex3D { pos: [0.0, y, 0.0], normal: [0.0, ny, 0.0], uv: [0.5, 0.5] }); |
| 189 | for iu in 0..=seg_u { |
| 190 | let (st, ct) = (a0 + (a1 - a0) * iu as f32 / seg_u as f32).sin_cos(); |
| 191 | verts.push(Vertex3D { pos: [ct * radius, y, st * radius], normal: [0.0, ny, 0.0], uv: [0.5 + 0.5 * ct, 0.5 + 0.5 * st] }); |
| 192 | } |
| 193 | for iu in 0..seg_u { |
| 194 | idx.extend_from_slice(&[base, base + 1 + iu, base + 2 + iu]); |
| 195 | } |
| 196 | } |
| 197 | (verts, idx) |
| 198 | } |
| 199 | |
| 200 | fn build_cube(width: f32, sub: u32, faces_mask: u8) -> (Vec<Vertex3D>, Vec<u32>) { |
| 201 | let h = width * 0.5; |
| 202 | // `[tl, tr, bl]` per face in `CUBE_FACES` order. |
| 203 | let faces: [([f32; 3], [[f32; 3]; 3]); 6] = [ |
| 204 | ([0.0, 0.0, 1.0], [[-h, h, h], [h, h, h], [-h, -h, h]]), |
| 205 | ([0.0, 0.0, -1.0], [[h, h, -h], [-h, h, -h], [h, -h, -h]]), |
| 206 | ([1.0, 0.0, 0.0], [[h, h, h], [h, h, -h], [h, -h, h]]), |
| 207 | ([-1.0, 0.0, 0.0], [[-h, h, -h], [-h, h, h], [-h, -h, -h]]), |
| 208 | ([0.0, 1.0, 0.0], [[-h, h, -h], [h, h, -h], [-h, h, h]]), |
| 209 | ([0.0, -1.0, 0.0], [[-h, -h, h], [h, -h, h], [-h, -h, -h]]), |
| 210 | ]; |
| 211 | let (mut verts, mut idx) = (Vec::new(), Vec::new()); |
| 212 | // Fusion's draw order (Front, Right, Left, Bottom, Top, Back) decides which translucent faces |
| 213 | // hide the ones behind them. |
| 214 | for i in [0, 2, 3, 5, 4, 1] { |
| 215 | if faces_mask & (1 << i) != 0 { |
| 216 | let (n, corners) = faces[i]; |
| 217 | push_quad_grid(&mut verts, &mut idx, n, corners, sub, sub); |
| 218 | } |
| 219 | } |
| 220 | (verts, idx) |
| 221 | } |
| 222 | |
| 223 | /// Expands an indexed mesh to the triangle list `ShapeKind::CustomMesh` carries. |
| 224 | pub(super) fn triangle_soup((verts, idx): (Vec<Vertex3D>, Vec<u32>)) -> Vec<Vertex3D> { |
| 225 | idx.into_iter().map(|i| verts[i as usize]).collect() |
| 226 | } |
| 227 | |
| 228 | /// Rings run from the apex (`+Y`) down to the base; sweep and angle convention match the cylinder. |
| 229 | pub(super) fn build_cone( |
| 230 | radius: f32, |
| 231 | height: f32, |
| 232 | sweep_deg: [f32; 2], |
| 233 | sub_base: u32, |
| 234 | sub_height: u32, |
| 235 | bottom_cap: bool, |
| 236 | ) -> (Vec<Vertex3D>, Vec<u32>) { |
| 237 | let (seg_u, seg_v) = (sub_base.clamp(3, 96), sub_height.clamp(1, 64)); |
| 238 | let [a0, a1] = sweep_deg.map(f32::to_radians); |
| 239 | let slant = (height * height + radius * radius).sqrt().max(1e-6); |
| 240 | let (mut verts, mut idx) = (Vec::new(), Vec::new()); |
| 241 | for iv in 0..=seg_v { |
| 242 | let t = iv as f32 / seg_v as f32; |
| 243 | for iu in 0..=seg_u { |
| 244 | let u = iu as f32 / seg_u as f32; |
| 245 | let (st, ct) = (a0 + (a1 - a0) * u).sin_cos(); |
| 246 | verts.push(Vertex3D { |
| 247 | pos: [ct * radius * t, height * (0.5 - t), st * radius * t], |
| 248 | normal: [ct * height / slant, radius / slant, st * height / slant], |
| 249 | uv: [1.0 - u, t], |
| 250 | }); |
| 251 | } |
| 252 | } |
| 253 | grid_indices(&mut idx, 0, seg_u, seg_v); |
| 254 | if bottom_cap { |
| 255 | let base = verts.len() as u32; |
| 256 | let center = Vertex3D { pos: [0.0, -height * 0.5, 0.0], normal: [0.0, -1.0, 0.0], uv: [0.5, 0.5] }; |
| 257 | verts.push(center); |
| 258 | for iu in 0..=seg_u { |
| 259 | let (st, ct) = (a0 + (a1 - a0) * iu as f32 / seg_u as f32).sin_cos(); |
| 260 | verts.push(Vertex3D { pos: [ct * radius, -height * 0.5, st * radius], normal: [0.0, -1.0, 0.0], uv: [0.5 + 0.5 * ct, 0.5 + 0.5 * st] }); |
| 261 | } |
| 262 | for iu in 0..seg_u { |
| 263 | idx.extend_from_slice(&[base, base + 1 + iu, base + 2 + iu]); |
| 264 | } |
| 265 | } |
| 266 | (verts, idx) |
| 267 | } |
| 268 | |
| 269 | /// Tube of radius `section` swept around the `Y` axis at distance `radius`. |
| 270 | pub(super) fn build_torus( |
| 271 | radius: f32, |
| 272 | section: f32, |
| 273 | sweep_deg: [f32; 2], |
| 274 | sub_base: u32, |
| 275 | sub_height: u32, |
| 276 | ) -> (Vec<Vertex3D>, Vec<u32>) { |
| 277 | let (seg_u, seg_v) = (sub_base.clamp(3, 128), sub_height.clamp(3, 128)); |
| 278 | let [a0, a1] = sweep_deg.map(f32::to_radians); |
| 279 | let (mut verts, mut idx) = (Vec::new(), Vec::new()); |
| 280 | for iv in 0..=seg_v { |
| 281 | let v = iv as f32 / seg_v as f32; |
| 282 | let (sp, cp) = (v * std::f32::consts::TAU).sin_cos(); |
| 283 | for iu in 0..=seg_u { |
| 284 | let u = iu as f32 / seg_u as f32; |
| 285 | let (st, ct) = (a0 + (a1 - a0) * u).sin_cos(); |
| 286 | verts.push(Vertex3D { |
| 287 | pos: [(radius + section * cp) * ct, section * sp, (radius + section * cp) * st], |
| 288 | normal: [cp * ct, sp, cp * st], |
| 289 | uv: [1.0 - u, v], |
| 290 | }); |
| 291 | } |
| 292 | } |
| 293 | grid_indices(&mut idx, 0, seg_u, seg_v); |
| 294 | (verts, idx) |
| 295 | } |
| 296 | |
| 297 | /// Icosahedron with a vertex on each `Y` pole, each triangle split in four per `level` and |
| 298 | /// projected onto the sphere of circumradius `size`. |
| 299 | pub(super) fn build_icosahedron(size: f32, level: u32) -> (Vec<Vertex3D>, Vec<u32>) { |
| 300 | let ring_y = 1.0 / 5.0_f32.sqrt(); |
| 301 | let ring_r = 2.0 * ring_y; |
| 302 | let ring = |k: u32, y: f32, offset_deg: f32| { |
| 303 | let (s, c) = ((k as f32 * 72.0 + offset_deg).to_radians()).sin_cos(); |
| 304 | [ring_r * c, y, ring_r * s] |
| 305 | }; |
| 306 | let mut pts: Vec<[f32; 3]> = vec![[0.0, 1.0, 0.0], [0.0, -1.0, 0.0]]; |
| 307 | pts.extend((0..5).map(|k| ring(k, ring_y, 54.0))); |
| 308 | pts.extend((0..5).map(|k| ring(k, -ring_y, 54.0 + 36.0))); |
| 309 | let (up, lo) = (|k: u32| 2 + k % 5, |k: u32| 7 + k % 5); |
| 310 | let mut tris: Vec<[[f32; 3]; 3]> = Vec::new(); |
| 311 | for k in 0..5 { |
| 312 | for t in [[0, up(k), up(k + 1)], [up(k), lo(k), up(k + 1)], [lo(k), lo(k + 1), up(k + 1)], [1, lo(k + 1), lo(k)]] { |
| 313 | tris.push(t.map(|i| pts[i as usize])); |
| 314 | } |
| 315 | } |
| 316 | let norm = |p: [f32; 3]| { |
| 317 | let l = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt().max(1e-6); |
| 318 | [p[0] / l, p[1] / l, p[2] / l] |
| 319 | }; |
| 320 | for _ in 0..level.min(4) { |
| 321 | tris = tris |
| 322 | .into_iter() |
| 323 | .flat_map(|[a, b, c]| { |
| 324 | let mid = |p: [f32; 3], q: [f32; 3]| norm([p[0] + q[0], p[1] + q[1], p[2] + q[2]]); |
| 325 | let (ab, bc, ca) = (mid(a, b), mid(b, c), mid(c, a)); |
| 326 | [[a, ab, ca], [ab, b, bc], [ca, bc, c], [ab, bc, ca]] |
| 327 | }) |
| 328 | .collect(); |
| 329 | } |
| 330 | let verts: Vec<Vertex3D> = tris |
| 331 | .into_iter() |
| 332 | .flatten() |
| 333 | .map(|p| { |
| 334 | let n = norm(p); |
| 335 | Vertex3D { pos: [n[0] * size, n[1] * size, n[2] * size], normal: n, uv: [0.5 + n[2].atan2(n[0]) / std::f32::consts::TAU, 0.5 - n[1].asin() / std::f32::consts::PI] } |
| 336 | }) |
| 337 | .collect(); |
| 338 | let idx = (0..verts.len() as u32).collect(); |
| 339 | (verts, idx) |
| 340 | } |
| 341 | |
| 342 | /// Fusion's `ReplaceNormals3D` recompute: each triangle corner averages (corner-angle weighted) |
| 343 | /// the face normals of every triangle sharing its position within `angle_deg` of its own face. |
| 344 | pub(super) fn smooth_normals((verts, idx): (Vec<Vertex3D>, Vec<u32>), angle_deg: f32) -> Vec<Vertex3D> { |
| 345 | let sub = |a: [f32; 3], b: [f32; 3]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; |
| 346 | let dot = |a: [f32; 3], b: [f32; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; |
| 347 | let unit = |a: [f32; 3]| { |
| 348 | let l = dot(a, a).sqrt(); |
| 349 | (l > 1e-12).then(|| [a[0] / l, a[1] / l, a[2] / l]) |
| 350 | }; |
| 351 | let cross = |a: [f32; 3], b: [f32; 3]| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; |
| 352 | let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64); |
| 353 | let tris: Vec<[u32; 3]> = idx.chunks_exact(3).map(|t| [t[0], t[1], t[2]]).collect(); |
| 354 | let face_n: Vec<Option<[f32; 3]>> = tris |
| 355 | .iter() |
| 356 | .map(|t| { |
| 357 | let p = t.map(|i| verts[i as usize].pos); |
| 358 | // Winding varies per builder; the authored vertex normals say which side is out. |
| 359 | let outward = t.iter().fold(0.0, |a, &i| a + dot(verts[i as usize].normal, cross(sub(p[1], p[0]), sub(p[2], p[0])))); |
| 360 | unit(cross(sub(p[1], p[0]), sub(p[2], p[0]))).map(|n| if outward < 0.0 { n.map(|c| -c) } else { n }) |
| 361 | }) |
| 362 | .collect(); |
| 363 | // Per welded position: (triangle, interior angle at that corner). |
| 364 | let mut at: std::collections::HashMap<[i64; 3], Vec<(usize, f32)>> = std::collections::HashMap::new(); |
| 365 | for (ti, t) in tris.iter().enumerate() { |
| 366 | if face_n[ti].is_none() { |
| 367 | continue; |
| 368 | } |
| 369 | let p = t.map(|i| verts[i as usize].pos); |
| 370 | for c in 0..3 { |
| 371 | let (e0, e1) = (unit(sub(p[(c + 1) % 3], p[c])), unit(sub(p[(c + 2) % 3], p[c]))); |
| 372 | let angle = e0.zip(e1).map_or(0.0, |(a, b)| dot(a, b).clamp(-1.0, 1.0).acos()); |
| 373 | at.entry(key(p[c])).or_default().push((ti, angle)); |
| 374 | } |
| 375 | } |
| 376 | let cos_limit = angle_deg.to_radians().cos() - 1e-4; |
| 377 | let mut out = Vec::with_capacity(tris.len() * 3); |
| 378 | for (ti, t) in tris.iter().enumerate() { |
| 379 | for &i in t { |
| 380 | let mut v = verts[i as usize]; |
| 381 | if let (Some(own), Some(group)) = (face_n[ti], at.get(&key(v.pos))) { |
| 382 | let sum = group.iter().filter_map(|&(fi, w)| face_n[fi].filter(|n| dot(*n, own) >= cos_limit).map(|n| n.map(|c| c * w))).fold([0.0; 3], |a, n| [a[0] + n[0], a[1] + n[1], a[2] + n[2]]); |
| 383 | v.normal = unit(sum).unwrap_or(own); |
| 384 | } |
| 385 | out.push(v); |
| 386 | } |
| 387 | } |
| 388 | out |
| 389 | } |
| 390 | |
| 391 | /// Quad-grid triangulation of `(seg_u + 1) * (seg_v + 1)` vertices starting at `base`. |
| 392 | fn grid_indices(idx: &mut Vec<u32>, base: u32, seg_u: u32, seg_v: u32) { |
| 393 | let row = seg_u + 1; |
| 394 | for iv in 0..seg_v { |
| 395 | for iu in 0..seg_u { |
| 396 | let a = base + iv * row + iu; |
| 397 | let (b, c, d) = (a + row, a + row + 1, a + 1); |
| 398 | idx.extend_from_slice(&[a, b, d, b, c, d]); |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | /// Unique triangle edges as a line-list index buffer. |
| 404 | pub(super) fn triangle_edges(indices: &[u32]) -> Vec<u32> { |
| 405 | let mut seen = std::collections::HashSet::new(); |
| 406 | let mut edges = Vec::new(); |
| 407 | for tri in indices.chunks_exact(3) { |
| 408 | for (a, b) in [(tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])] { |
| 409 | if seen.insert((a.min(b), a.max(b))) { |
| 410 | edges.extend_from_slice(&[a, b]); |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | edges |
| 415 | } |
| 416 | |
| 417 | pub(super) fn apply_heightmap_displace( |
| 418 | verts: &mut [Vertex3D], |
| 419 | indices: &[u32], |
| 420 | disp: &DisplaceHeightmap, |
| 421 | ) { |
| 422 | let w = disp.size[0].max(1) as usize; |
| 423 | let h = disp.size[1].max(1) as usize; |
| 424 | if disp.rgba.len() < w * h * 4 { |
| 425 | return; |
| 426 | } |
| 427 | for v in verts.iter_mut() { |
| 428 | let px = ((v.uv[0].clamp(0.0, 1.0)) * (w - 1) as f32).round() as usize; |
| 429 | let py = ((v.uv[1].clamp(0.0, 1.0)) * (h - 1) as f32).round() as usize; |
| 430 | let off = (py * w + px) * 4; |
| 431 | let r = disp.rgba[off] as f32 / 255.0; |
| 432 | let g = disp.rgba[off + 1] as f32 / 255.0; |
| 433 | let b = disp.rgba[off + 2] as f32 / 255.0; |
| 434 | let a = disp.rgba[off + 3] as f32 / 255.0; |
| 435 | let sample = match disp.channel { |
| 436 | 1 => r, |
| 437 | 2 => g, |
| 438 | 3 => b, |
| 439 | 4 => a, |
| 440 | _ => 0.299 * r + 0.587 * g + 0.114 * b, |
| 441 | }; |
| 442 | let d = (sample + disp.bias) * disp.scale; |
| 443 | v.pos[0] += v.normal[0] * d; |
| 444 | v.pos[1] += v.normal[1] * d; |
| 445 | v.pos[2] += v.normal[2] * d; |
| 446 | } |
| 447 | // Recompute smooth vertex normals from displaced triangles |
| 448 | let mut acc = vec![[0.0_f32; 3]; verts.len()]; |
| 449 | for tri in indices.chunks_exact(3) { |
| 450 | let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize); |
| 451 | if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() { |
| 452 | continue; |
| 453 | } |
| 454 | let p0 = verts[i0].pos; |
| 455 | let p1 = verts[i1].pos; |
| 456 | let p2 = verts[i2].pos; |
| 457 | let e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]]; |
| 458 | let e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]]; |
| 459 | let fn_v = [ |
| 460 | e1[1] * e2[2] - e1[2] * e2[1], |
| 461 | e1[2] * e2[0] - e1[0] * e2[2], |
| 462 | e1[0] * e2[1] - e1[1] * e2[0], |
| 463 | ]; |
| 464 | for &i in &[i0, i1, i2] { |
| 465 | acc[i][0] += fn_v[0]; |
| 466 | acc[i][1] += fn_v[1]; |
| 467 | acc[i][2] += fn_v[2]; |
| 468 | } |
| 469 | } |
| 470 | for (v, n) in verts.iter_mut().zip(acc.into_iter()) { |
| 471 | let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); |
| 472 | if len > 1e-6 { |
| 473 | v.normal = [n[0] / len, n[1] / len, n[2] / len]; |
| 474 | } |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | #[cfg(test)] |
| 479 | mod tests { |
| 480 | use super::*; |
| 481 | |
| 482 | #[test] |
| 483 | fn plane_grid_splits_cells_along_bottom_left_to_top_right() { |
| 484 | let (verts, idx) = build_plane(2.0, 2.0, 2, 2); |
| 485 | assert_eq!(verts.len(), 9); |
| 486 | assert_eq!(idx.len(), 2 * 2 * 6); |
| 487 | // First cell: a = top-left (0), b = bottom-left (3), c = bottom-right (4), d = top-right (1). |
| 488 | assert_eq!(&idx[..6], &[0, 3, 1, 3, 4, 1]); |
| 489 | } |
| 490 | |
| 491 | #[test] |
| 492 | fn sphere_rows_draw_top_down_with_the_front_before_the_back() { |
| 493 | let (verts, idx) = build_sphere(1.0, 20, 20); |
| 494 | let centroid = |t: &[u32]| [0, 1, 2].map(|k| t.iter().map(|&i| verts[i as usize].pos[k]).sum::<f32>() / 3.0); |
| 495 | let tris: Vec<[f32; 3]> = idx.chunks(3).map(centroid).collect(); |
| 496 | assert!(tris[0][1] > 0.9 && tris[tris.len() - 1][1] < -0.9); |
| 497 | let row = &tris[10 * 40..11 * 40]; |
| 498 | let front = row.iter().position(|c| c[2] > 0.9).expect("front quad"); |
| 499 | let back = row.iter().position(|c| c[2] < -0.9).expect("back quad"); |
| 500 | assert!(front < back); |
| 501 | } |
| 502 | |
| 503 | #[test] |
| 504 | fn cube_faces_draw_front_right_left_bottom_top_back() { |
| 505 | let (verts, idx) = build_cube(1.0, 1, 0b11_1111); |
| 506 | let normals: Vec<[f32; 3]> = idx.chunks(6).map(|q| verts[q[0] as usize].normal).collect(); |
| 507 | let z = |s| [0.0, 0.0, s]; |
| 508 | assert_eq!(normals, [z(1.0), [1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 1.0, 0.0], z(-1.0)]); |
| 509 | } |
| 510 | |
| 511 | #[test] |
| 512 | fn translucent_faces_hide_whatever_draws_after_them() { |
| 513 | // Above the equator the far side of a sphere's rows draws first and shows through; |
| 514 | // below it the near side draws first and hides it. |
| 515 | let src = r#"Composition { CurrentTime = 0, RenderRange = { 0, 1 }, GlobalRange = { 0, 1 }, Tools = ordered() { |
| 516 | Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, TopLeftAlpha = Input { Value = 0.5, }, }, }, |
| 517 | S = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, MaterialInput = Input { SourceOp = "Bg", Source = "Output", }, }, }, |
| 518 | Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, }, }, |
| 519 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, SceneInput2 = Input { SourceOp = "Cam", Source = "Output", }, }, }, |
| 520 | R = Renderer3D { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, SceneInput = Input { SourceOp = "M", Source = "Output", }, }, }, |
| 521 | } }"#; |
| 522 | let comp = model::Comp::from_fusion_str(src).expect("parse comp"); |
| 523 | let Ok(mut eng) = crate::Engine::new_headless() else { return }; |
| 524 | let (tex, _) = eng.evaluate(&comp, comp.find_node("R").expect("R"), 0.0); |
| 525 | let px = eng.readback_rgba(&tex).expect("readback"); |
| 526 | let alpha = |y: usize| px[(y * 64 + 32) * 4 + 3]; |
| 527 | assert!((alpha(4) as i32 - 191).abs() <= 3, "upper half shows the back: {}", alpha(4)); |
| 528 | assert!((alpha(50) as i32 - 128).abs() <= 3, "lower half hides it: {}", alpha(50)); |
| 529 | } |
| 530 | |
| 531 | #[test] |
| 532 | fn cube_face_mask_and_subdivision_counts() { |
| 533 | let (all, all_idx) = build_cube(1.0, 3, 0b11_1111); |
| 534 | assert_eq!(all.len(), 6 * 16); |
| 535 | assert_eq!(all_idx.len(), 6 * 3 * 3 * 6); |
| 536 | let (front, _) = build_cube(1.0, 1, 0b00_0001); |
| 537 | assert!(front.iter().all(|v| v.normal == [0.0, 0.0, 1.0])); |
| 538 | } |
| 539 | |
| 540 | #[test] |
| 541 | fn icosahedron_has_twenty_faces_on_the_circumsphere() { |
| 542 | let (verts, idx) = build_icosahedron(2.0, 0); |
| 543 | assert_eq!(idx.len(), 20 * 3); |
| 544 | assert!(verts.iter().all(|v| (v.pos.iter().map(|c| c * c).sum::<f32>().sqrt() - 2.0).abs() < 1e-4)); |
| 545 | assert_eq!(build_icosahedron(1.0, 1).1.len(), 80 * 3); |
| 546 | } |
| 547 | |
| 548 | #[test] |
| 549 | fn cone_apex_is_up_and_cap_is_optional() { |
| 550 | let (open, _) = build_cone(1.0, 2.0, [0.0, 360.0], 8, 1, false); |
| 551 | let (capped, _) = build_cone(1.0, 2.0, [0.0, 360.0], 8, 1, true); |
| 552 | assert!(open.iter().take(9).all(|v| v.pos[1] == 1.0 && v.pos[0] == 0.0)); |
| 553 | assert_eq!(capped.len(), open.len() + 1 + 9); |
| 554 | } |
| 555 | |
| 556 | #[test] |
| 557 | fn cylinder_height_subdivision_adds_rings() { |
| 558 | let rings = |sub_height| { |
| 559 | let (v, _) = build_cylinder(1.0, 2.0, 0.0, 360.0, [8, sub_height], [false, false]); |
| 560 | let mut ys: Vec<i32> = v.iter().map(|p| (p.pos[1] * 1000.0).round() as i32).collect(); |
| 561 | ys.sort_unstable(); |
| 562 | ys.dedup(); |
| 563 | ys.len() |
| 564 | }; |
| 565 | assert_eq!((rings(1), rings(4)), (2, 5)); |
| 566 | } |
| 567 | |
| 568 | #[test] |
| 569 | fn torus_tube_stays_within_radius_plus_section() { |
| 570 | let (verts, _) = build_torus(1.0, 0.5, [0.0, 360.0], 16, 8); |
| 571 | assert!(verts.iter().all(|v| v.pos[1].abs() <= 0.5 + 1e-5 && (v.pos[0].hypot(v.pos[2]) - 1.0).abs() <= 0.5 + 1e-5)); |
| 572 | } |
| 573 | |
| 574 | #[test] |
| 575 | fn triangle_edges_are_deduplicated() { |
| 576 | // Two triangles sharing edge 1-2. |
| 577 | let edges = triangle_edges(&[0, 1, 2, 1, 3, 2]); |
| 578 | assert_eq!(edges.len(), 5 * 2); |
| 579 | } |
| 580 | |
| 581 | #[test] |
| 582 | fn displace_channel_zero_is_luma_and_one_is_red() { |
| 583 | let displace = |channel| { |
| 584 | let (mut verts, idx) = build_plane(1.0, 1.0, 1, 1); |
| 585 | let disp = DisplaceHeightmap { size: [1, 1], rgba: vec![255, 0, 0, 255], scale: 1.0, bias: 0.0, channel }; |
| 586 | apply_heightmap_displace(&mut verts, &idx, &disp); |
| 587 | verts[0].pos[2] |
| 588 | }; |
| 589 | assert!((displace(1) - 1.0).abs() < 1e-4, "red channel"); |
| 590 | assert!((displace(0) - 0.299).abs() < 1e-3, "luma"); |
| 591 | } |
| 592 | } |