1use super::*;
2
3#[must_use]
13fn subdiv_vertex_from_mesh(v: &Vertex3D) -> SubdivVertex {
14 let col: [u8; 4] = v.get_color0();
15 SubdivVertex {
16 position: sanitize_vec3(v.get_position(), Vec3::zero()),
17 uv0: v.get_uv0(),
18 uv1: v.get_uv1(),
19 color: [col[0] as f32, col[1] as f32, col[2] as f32, col[3] as f32],
20 flags: v.get_flags(),
21 }
22}
23
24#[must_use]
34fn subdiv_vertex_to_mesh(sv: SubdivVertex) -> Vertex3D {
35 let col: [f32; 4] = sv.get_color();
36 Vertex3D::from_full(
37 sanitize_vec3(sv.get_position(), Vec3::zero()),
38 Vec3::new(0.0, 1.0, 0.0),
39 [1.0, 0.0, 0.0, 1.0],
40 sv.get_uv0(),
41 sv.get_uv1(),
42 [
43 col[0].round().clamp(0.0, 255.0) as u8,
44 col[1].round().clamp(0.0, 255.0) as u8,
45 col[2].round().clamp(0.0, 255.0) as u8,
46 col[3].round().clamp(0.0, 255.0) as u8,
47 ],
48 sv.get_flags(),
49 )
50}
51
52#[must_use]
62fn blend_subdiv_vertices(terms: &[(SubdivVertex, f32)]) -> SubdivVertex {
63 let mut pos: Vec3 = Vec3::zero();
64 let mut uv0: [f32; 2] = [0.0, 0.0];
65 let mut uv1: [f32; 2] = [0.0, 0.0];
66 let mut col: [f32; 4] = [0.0, 0.0, 0.0, 0.0];
67 let mut flags: u32 = 0;
68 for &(sv, w) in terms.iter() {
69 pos = pos.add(sv.get_position().scale(w));
70 let u0: [f32; 2] = sv.get_uv0();
71 let u1: [f32; 2] = sv.get_uv1();
72 let c: [f32; 4] = sv.get_color();
73 uv0[0] += u0[0] * w;
74 uv0[1] += u0[1] * w;
75 uv1[0] += u1[0] * w;
76 uv1[1] += u1[1] * w;
77 col[0] += c[0] * w;
78 col[1] += c[1] * w;
79 col[2] += c[2] * w;
80 col[3] += c[3] * w;
81 flags |= sv.get_flags();
82 }
83 SubdivVertex {
84 position: sanitize_vec3(pos, Vec3::zero()),
85 uv0,
86 uv1,
87 color: col,
88 flags,
89 }
90}
91
92#[must_use]
103fn average_subdiv_indices(verts: &[SubdivVertex], indices: &[u32]) -> SubdivVertex {
104 if indices.is_empty() {
105 return SubdivVertex::default();
106 }
107 let inv: f32 = 1.0 / (indices.len() as f32);
108 let mut pos: Vec3 = Vec3::zero();
109 let mut uv0: [f32; 2] = [0.0, 0.0];
110 let mut uv1: [f32; 2] = [0.0, 0.0];
111 let mut col: [f32; 4] = [0.0, 0.0, 0.0, 0.0];
112 let mut flags: u32 = 0;
113 for &idx in indices.iter() {
114 let sv: SubdivVertex = verts[idx as usize];
115 pos = pos.add(sv.get_position());
116 let u0: [f32; 2] = sv.get_uv0();
117 let u1: [f32; 2] = sv.get_uv1();
118 let c: [f32; 4] = sv.get_color();
119 uv0[0] += u0[0];
120 uv0[1] += u0[1];
121 uv1[0] += u1[0];
122 uv1[1] += u1[1];
123 col[0] += c[0];
124 col[1] += c[1];
125 col[2] += c[2];
126 col[3] += c[3];
127 flags |= sv.get_flags();
128 }
129 SubdivVertex {
130 position: pos.scale(inv),
131 uv0: [uv0[0] * inv, uv0[1] * inv],
132 uv1: [uv1[0] * inv, uv1[1] * inv],
133 color: [col[0] * inv, col[1] * inv, col[2] * inv, col[3] * inv],
134 flags,
135 }
136}
137
138#[must_use]
149fn edge_key(a: u32, b: u32) -> (u32, u32) {
150 if a < b { (a, b) } else { (b, a) }
151}
152
153#[must_use]
165fn is_convex_quad(verts: &[SubdivVertex], q: [u32; 4], face_normal: Vec3) -> bool {
166 for i in 0..4 {
167 let p_prev: Vec3 = verts[q[(i + 3) % 4] as usize].get_position();
168 let p_curr: Vec3 = verts[q[i] as usize].get_position();
169 let p_next: Vec3 = verts[q[(i + 1) % 4] as usize].get_position();
170 let e0: Vec3 = p_curr.sub(p_prev);
171 let e1: Vec3 = p_next.sub(p_curr);
172 if e0.cross(e1).dot(face_normal) <= 1e-7 {
173 return false;
174 }
175 }
176 true
177}
178
179#[must_use]
191fn build_quad_dominant_faces(
192 verts: &[SubdivVertex],
193 tris: &[[u32; 3]],
194 tri_mats: &[u16],
195) -> Vec<PolyFace> {
196 let mut normals: Vec<Vec3> = Vec::with_capacity(tris.len());
197 let mut half_edges: HashMap<(u32, u32), (usize, u32)> = HashMap::with_capacity(tris.len() * 3);
198 for (ti, tri) in tris.iter().enumerate() {
199 let p0: Vec3 = verts[tri[0] as usize].get_position();
200 let p1: Vec3 = verts[tri[1] as usize].get_position();
201 let p2: Vec3 = verts[tri[2] as usize].get_position();
202 normals.push(safe_unit_normal(p1.sub(p0).cross(p2.sub(p0))));
203 half_edges.insert((tri[0], tri[1]), (ti, tri[2]));
204 half_edges.insert((tri[1], tri[2]), (ti, tri[0]));
205 half_edges.insert((tri[2], tri[0]), (ti, tri[1]));
206 }
207 let mut used: Vec<bool> = vec![false; tris.len()];
208 let mut faces: Vec<PolyFace> = Vec::with_capacity(tris.len());
209 for (ti, tri) in tris.iter().enumerate() {
210 if used[ti] {
211 continue;
212 }
213 let mat_a: u16 = tri_mats.get(ti).copied().unwrap_or(0);
214 let na: Vec3 = normals[ti];
215 let mut best_pair: Option<(usize, [u32; 4], f32)> = None;
216 let edges: [(u32, u32, u32); 3] = [
217 (tri[0], tri[1], tri[2]),
218 (tri[1], tri[2], tri[0]),
219 (tri[2], tri[0], tri[1]),
220 ];
221 for (a, b, opp_a) in edges {
222 if let Some(&(tj, opp_b)) = half_edges.get(&(b, a)) {
223 if tj == ti || used[tj] {
224 continue;
225 }
226 let mat_b: u16 = tri_mats.get(tj).copied().unwrap_or(0);
227 if mat_a != mat_b || na.dot(normals[tj]) < SUBDIV_COPLANAR_COS {
228 continue;
229 }
230 let quad: [u32; 4] = [a, opp_b, b, opp_a];
231 if !is_convex_quad(verts, quad, na) {
232 continue;
233 }
234 let diag_len: f32 = verts[b as usize]
235 .get_position()
236 .sub(verts[a as usize].get_position())
237 .length_sq();
238 let should_take: bool = match best_pair {
239 None => true,
240 Some((_, _, prev_len)) => diag_len > prev_len,
241 };
242 if should_take {
243 best_pair = Some((tj, quad, diag_len));
244 }
245 }
246 }
247 if let Some((tj, quad, _)) = best_pair {
248 used[ti] = true;
249 used[tj] = true;
250 faces.push(PolyFace {
251 vertices: quad.to_vec(),
252 material_slot: mat_a,
253 });
254 } else {
255 used[ti] = true;
256 faces.push(PolyFace {
257 vertices: tri.to_vec(),
258 material_slot: mat_a,
259 });
260 }
261 }
262 faces
263}
264
265#[must_use]
276fn catmull_clark_step(
277 verts: &[SubdivVertex],
278 faces: &[PolyFace],
279) -> (Vec<SubdivVertex>, Vec<PolyFace>) {
280 let orig_v_count: usize = verts.len();
281 let face_count: usize = faces.len();
282 let mut face_pts: Vec<SubdivVertex> = Vec::with_capacity(face_count);
283 let mut edge_faces: HashMap<(u32, u32), Vec<usize>> = HashMap::with_capacity(face_count * 4);
284 let mut vert_faces: Vec<Vec<usize>> = vec![Vec::new(); orig_v_count];
285 let mut vert_edges: Vec<Vec<u32>> = vec![Vec::new(); orig_v_count];
286 for (fi, face) in faces.iter().enumerate() {
287 let fv: &[u32] = face.get_vertices();
288 face_pts.push(average_subdiv_indices(verts, fv));
289 let k: usize = fv.len();
290 for i in 0..k {
291 let a: u32 = fv[i];
292 let b: u32 = fv[(i + 1) % k];
293 vert_faces[a as usize].push(fi);
294 if !vert_edges[a as usize].contains(&b) {
295 vert_edges[a as usize].push(b);
296 }
297 if !vert_edges[b as usize].contains(&a) {
298 vert_edges[b as usize].push(a);
299 }
300 edge_faces.entry(edge_key(a, b)).or_default().push(fi);
301 }
302 }
303 let mut next_verts: Vec<SubdivVertex> =
304 Vec::with_capacity(orig_v_count + face_count + edge_faces.len());
305 for v_idx in 0..orig_v_count {
306 let orig: SubdivVertex = verts[v_idx];
307 let nbrs: &[u32] = &vert_edges[v_idx];
308 let mut bnd_nbrs: Vec<u32> = Vec::new();
309 for &nbr in nbrs.iter() {
310 let inc_count: usize = edge_faces
311 .get(&edge_key(v_idx as u32, nbr))
312 .map_or(0, |list: &Vec<usize>| list.len());
313 if inc_count == 1 {
314 bnd_nbrs.push(nbr);
315 }
316 }
317 let updated: SubdivVertex = if !bnd_nbrs.is_empty() {
318 if bnd_nbrs.len() == 2 {
319 blend_subdiv_vertices(&[
320 (orig, 0.75),
321 (verts[bnd_nbrs[0] as usize], 0.125),
322 (verts[bnd_nbrs[1] as usize], 0.125),
323 ])
324 } else {
325 orig
326 }
327 } else {
328 let n: usize = nbrs.len();
329 let inc_f: &[usize] = &vert_faces[v_idx];
330 if n >= 3 && !inc_f.is_empty() {
331 let inv_f: f32 = 1.0 / (inc_f.len() as f32);
332 let mut f_terms: Vec<(SubdivVertex, f32)> = Vec::with_capacity(inc_f.len());
333 for &fi in inc_f.iter() {
334 f_terms.push((face_pts[fi], inv_f));
335 }
336 let f_avg: SubdivVertex = blend_subdiv_vertices(&f_terms);
337 let inv_n: f32 = 1.0 / (n as f32);
338 let mut r_terms: Vec<(SubdivVertex, f32)> = Vec::with_capacity(n + 1);
339 r_terms.push((orig, 0.5));
340 for &nbr in nbrs.iter() {
341 r_terms.push((verts[nbr as usize], 0.5 * inv_n));
342 }
343 let r_avg: SubdivVertex = blend_subdiv_vertices(&r_terms);
344 let nf: f32 = n as f32;
345 blend_subdiv_vertices(&[
346 (f_avg, 1.0 / nf),
347 (r_avg, 2.0 / nf),
348 (orig, (nf - 3.0) / nf),
349 ])
350 } else {
351 orig
352 }
353 };
354 next_verts.push(updated);
355 }
356 let face_base: u32 = next_verts.len() as u32;
357 next_verts.extend_from_slice(&face_pts);
358 let mut edge_vert_map: HashMap<(u32, u32), u32> = HashMap::with_capacity(edge_faces.len());
359 for (&ek, inc_f) in edge_faces.iter() {
360 let va: SubdivVertex = verts[ek.0 as usize];
361 let vb: SubdivVertex = verts[ek.1 as usize];
362 let edge_pt: SubdivVertex = if inc_f.len() == 2 {
363 blend_subdiv_vertices(&[
364 (va, 0.25),
365 (vb, 0.25),
366 (face_pts[inc_f[0]], 0.25),
367 (face_pts[inc_f[1]], 0.25),
368 ])
369 } else {
370 blend_subdiv_vertices(&[(va, 0.5), (vb, 0.5)])
371 };
372 let e_idx: u32 = next_verts.len() as u32;
373 next_verts.push(edge_pt);
374 edge_vert_map.insert(ek, e_idx);
375 }
376 let mut next_faces: Vec<PolyFace> = Vec::with_capacity(face_count * 4);
377 for (fi, face) in faces.iter().enumerate() {
378 let fv: &[u32] = face.get_vertices();
379 let k: usize = fv.len();
380 let f_vid: u32 = face_base + (fi as u32);
381 let mat_slot: u16 = face.get_material_slot();
382 for i in 0..k {
383 let v_curr: u32 = fv[i];
384 let v_next: u32 = fv[(i + 1) % k];
385 let v_prev: u32 = fv[(i + k - 1) % k];
386 let e_next: u32 = edge_vert_map
387 .get(&edge_key(v_curr, v_next))
388 .copied()
389 .unwrap_or(v_curr);
390 let e_prev: u32 = edge_vert_map
391 .get(&edge_key(v_prev, v_curr))
392 .copied()
393 .unwrap_or(v_curr);
394 next_faces.push(PolyFace {
395 vertices: vec![v_curr, e_next, f_vid, e_prev],
396 material_slot: mat_slot,
397 });
398 }
399 }
400 (next_verts, next_faces)
401}
402
403#[must_use]
414pub fn subdivide_catmull_clark(mesh: &Mesh3D, levels: u32) -> Mesh3D {
415 let iters: u32 = levels.min(SUBDIV_MAX_LEVELS);
416 if iters == 0 || mesh.get_indices().is_empty() {
417 return mesh.clone();
418 }
419 let welded: Mesh3D = weld_vertices(mesh, SUBDIV_WELD_EPSILON);
420 let mut verts: Vec<SubdivVertex> = welded
421 .get_vertices()
422 .iter()
423 .map(subdiv_vertex_from_mesh)
424 .collect();
425 let mut faces: Vec<PolyFace> =
426 build_quad_dominant_faces(&verts, welded.get_indices(), welded.get_tri_materials());
427 for _ in 0..iters {
428 let (next_v, next_f): (Vec<SubdivVertex>, Vec<PolyFace>) =
429 catmull_clark_step(&verts, &faces);
430 verts = next_v;
431 faces = next_f;
432 }
433 let has_sub_mats: bool = !welded.get_sub_materials().is_empty();
434 let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(verts.len());
435 for sv in verts.into_iter() {
436 out_verts.push(subdiv_vertex_to_mesh(sv));
437 }
438 let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(faces.len() * 2);
439 let mut out_tri_mats: Vec<u16> =
440 Vec::with_capacity(if has_sub_mats { faces.len() * 2 } else { 0 });
441 for face in faces.iter() {
442 let fv: &[u32] = face.get_vertices();
443 let mat: u16 = face.get_material_slot();
444 if fv.len() == 3 {
445 out_tris.push([fv[0], fv[1], fv[2]]);
446 if has_sub_mats {
447 out_tri_mats.push(mat);
448 }
449 } else if fv.len() == 4 {
450 let d02: f32 = out_verts[fv[0] as usize]
451 .get_position()
452 .sub(out_verts[fv[2] as usize].get_position())
453 .length_sq();
454 let d13: f32 = out_verts[fv[1] as usize]
455 .get_position()
456 .sub(out_verts[fv[3] as usize].get_position())
457 .length_sq();
458 if d02 <= d13 {
459 out_tris.push([fv[0], fv[1], fv[2]]);
460 out_tris.push([fv[0], fv[2], fv[3]]);
461 } else {
462 out_tris.push([fv[0], fv[1], fv[3]]);
463 out_tris.push([fv[1], fv[2], fv[3]]);
464 }
465 if has_sub_mats {
466 out_tri_mats.push(mat);
467 out_tri_mats.push(mat);
468 }
469 } else if fv.len() > 4 {
470 for i in 1..(fv.len() - 1) {
471 out_tris.push([fv[0], fv[i], fv[i + 1]]);
472 if has_sub_mats {
473 out_tri_mats.push(mat);
474 }
475 }
476 }
477 }
478 let mut out_mesh: Mesh3D = Mesh3D::from_parts(
479 mesh.get_name().clone(),
480 out_verts,
481 out_tris,
482 mesh.get_material(),
483 );
484 out_mesh.set_is_closed(mesh.get_is_closed());
485 if has_sub_mats {
486 out_mesh.set_sub_materials(welded.get_sub_materials().clone());
487 out_mesh.set_tri_materials(out_tri_mats);
488 }
489 let smoothed: Mesh3D = recompute_smooth_normals(&out_mesh);
490 compute_tangents(&smoothed)
491}
492
493#[must_use]
505fn loop_subdiv_step(
506 verts: &[SubdivVertex],
507 tris: &[[u32; 3]],
508 tri_mats: &[u16],
509) -> (Vec<SubdivVertex>, Vec<[u32; 3]>, Vec<u16>) {
510 let orig_v_count: usize = verts.len();
511 let mut edge_opps: HashMap<(u32, u32), Vec<u32>> = HashMap::with_capacity(tris.len() * 2);
512 let mut vert_nbrs: Vec<Vec<u32>> = vec![Vec::new(); orig_v_count];
513 for tri in tris.iter() {
514 let (a, b, c): (u32, u32, u32) = (tri[0], tri[1], tri[2]);
515 edge_opps.entry(edge_key(a, b)).or_default().push(c);
516 edge_opps.entry(edge_key(b, c)).or_default().push(a);
517 edge_opps.entry(edge_key(c, a)).or_default().push(b);
518 for (u, v) in [(a, b), (b, c), (c, a)] {
519 if !vert_nbrs[u as usize].contains(&v) {
520 vert_nbrs[u as usize].push(v);
521 }
522 if !vert_nbrs[v as usize].contains(&u) {
523 vert_nbrs[v as usize].push(u);
524 }
525 }
526 }
527 let mut next_verts: Vec<SubdivVertex> = Vec::with_capacity(orig_v_count + edge_opps.len());
528 for v_idx in 0..orig_v_count {
529 let orig: SubdivVertex = verts[v_idx];
530 let nbrs: &[u32] = &vert_nbrs[v_idx];
531 let mut bnd_nbrs: Vec<u32> = Vec::new();
532 for &nbr in nbrs.iter() {
533 let opp_count: usize = edge_opps
534 .get(&edge_key(v_idx as u32, nbr))
535 .map_or(0, |list: &Vec<u32>| list.len());
536 if opp_count == 1 {
537 bnd_nbrs.push(nbr);
538 }
539 }
540 let updated: SubdivVertex = if !bnd_nbrs.is_empty() {
541 if bnd_nbrs.len() == 2 {
542 blend_subdiv_vertices(&[
543 (orig, 0.75),
544 (verts[bnd_nbrs[0] as usize], 0.125),
545 (verts[bnd_nbrs[1] as usize], 0.125),
546 ])
547 } else {
548 orig
549 }
550 } else {
551 let n: usize = nbrs.len();
552 if n >= 3 {
553 let nf: f32 = n as f32;
554 let term: f32 = 0.375 + 0.25 * (TAU / nf).cos();
555 let beta: f32 = (0.625 - term * term) / nf;
556 let mut blend_terms: Vec<(SubdivVertex, f32)> = Vec::with_capacity(n + 1);
557 blend_terms.push((orig, 1.0 - nf * beta));
558 for &nbr in nbrs.iter() {
559 blend_terms.push((verts[nbr as usize], beta));
560 }
561 blend_subdiv_vertices(&blend_terms)
562 } else {
563 orig
564 }
565 };
566 next_verts.push(updated);
567 }
568 let mut edge_vert_map: HashMap<(u32, u32), u32> = HashMap::with_capacity(edge_opps.len());
569 for (&ek, opps) in edge_opps.iter() {
570 let va: SubdivVertex = verts[ek.0 as usize];
571 let vb: SubdivVertex = verts[ek.1 as usize];
572 let odd_pt: SubdivVertex = if opps.len() == 2 {
573 blend_subdiv_vertices(&[
574 (va, 0.375),
575 (vb, 0.375),
576 (verts[opps[0] as usize], 0.125),
577 (verts[opps[1] as usize], 0.125),
578 ])
579 } else {
580 blend_subdiv_vertices(&[(va, 0.5), (vb, 0.5)])
581 };
582 let e_idx: u32 = next_verts.len() as u32;
583 next_verts.push(odd_pt);
584 edge_vert_map.insert(ek, e_idx);
585 }
586 let mut next_tris: Vec<[u32; 3]> = Vec::with_capacity(tris.len() * 4);
587 let has_mats: bool = !tri_mats.is_empty();
588 let mut next_mats: Vec<u16> = Vec::with_capacity(if has_mats { tris.len() * 4 } else { 0 });
589 for (ti, tri) in tris.iter().enumerate() {
590 let (a, b, c): (u32, u32, u32) = (tri[0], tri[1], tri[2]);
591 let ab: u32 = edge_vert_map.get(&edge_key(a, b)).copied().unwrap_or(a);
592 let bc: u32 = edge_vert_map.get(&edge_key(b, c)).copied().unwrap_or(b);
593 let ca: u32 = edge_vert_map.get(&edge_key(c, a)).copied().unwrap_or(c);
594 next_tris.push([a, ab, ca]);
595 next_tris.push([b, bc, ab]);
596 next_tris.push([c, ca, bc]);
597 next_tris.push([ab, bc, ca]);
598 if has_mats {
599 let slot: u16 = tri_mats.get(ti).copied().unwrap_or(0);
600 next_mats.push(slot);
601 next_mats.push(slot);
602 next_mats.push(slot);
603 next_mats.push(slot);
604 }
605 }
606 (next_verts, next_tris, next_mats)
607}
608
609#[must_use]
620pub fn subdivide_loop(mesh: &Mesh3D, levels: u32) -> Mesh3D {
621 let iters: u32 = levels.min(SUBDIV_MAX_LEVELS);
622 if iters == 0 || mesh.get_indices().is_empty() {
623 return mesh.clone();
624 }
625 let welded: Mesh3D = weld_vertices(mesh, SUBDIV_WELD_EPSILON);
626 let mut verts: Vec<SubdivVertex> = welded
627 .get_vertices()
628 .iter()
629 .map(subdiv_vertex_from_mesh)
630 .collect();
631 let mut tris: Vec<[u32; 3]> = welded.get_indices().to_vec();
632 let mut tri_mats: Vec<u16> = welded.get_tri_materials().to_vec();
633 for _ in 0..iters {
634 let (nv, nt, nm): (Vec<SubdivVertex>, Vec<[u32; 3]>, Vec<u16>) =
635 loop_subdiv_step(&verts, &tris, &tri_mats);
636 verts = nv;
637 tris = nt;
638 tri_mats = nm;
639 }
640 let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(verts.len());
641 for sv in verts.into_iter() {
642 out_verts.push(subdiv_vertex_to_mesh(sv));
643 }
644 let mut out_mesh: Mesh3D = Mesh3D::from_parts(
645 mesh.get_name().clone(),
646 out_verts,
647 tris,
648 mesh.get_material(),
649 );
650 out_mesh.set_is_closed(mesh.get_is_closed());
651 if !tri_mats.is_empty() {
652 out_mesh.set_sub_materials(welded.get_sub_materials().clone());
653 out_mesh.set_tri_materials(tri_mats);
654 }
655 let smoothed: Mesh3D = recompute_smooth_normals(&out_mesh);
656 compute_tangents(&smoothed)
657}