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