euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use super::*;

/// Extracts an owned `SubdivVertex` attribute bundle from a `Vertex3D`.
///
/// # Arguments
///
/// - `&Vertex3D` - Source mesh vertex.
///
/// # Returns
///
/// - `SubdivVertex` - Subdivision attribute bundle.
#[must_use]
fn subdiv_vertex_from_mesh(v: &Vertex3D) -> SubdivVertex {
    let col: [u8; 4] = v.get_color0();
    SubdivVertex {
        position: sanitize_vec3(v.get_position(), Vec3::zero()),
        uv0: v.get_uv0(),
        uv1: v.get_uv1(),
        color: [col[0] as f32, col[1] as f32, col[2] as f32, col[3] as f32],
        flags: v.get_flags(),
    }
}

/// Converts a `SubdivVertex` back into a `Vertex3D` with temporary `+Y` normal.
///
/// # Arguments
///
/// - `SubdivVertex` - Subdivided vertex attributes.
///
/// # Returns
///
/// - `Vertex3D` - Ready 64-byte mesh vertex.
#[must_use]
fn subdiv_vertex_to_mesh(sv: SubdivVertex) -> Vertex3D {
    let col: [f32; 4] = sv.get_color();
    Vertex3D::from_full(
        sanitize_vec3(sv.get_position(), Vec3::zero()),
        Vec3::new(0.0, 1.0, 0.0),
        [1.0, 0.0, 0.0, 1.0],
        sv.get_uv0(),
        sv.get_uv1(),
        [
            col[0].round().clamp(0.0, 255.0) as u8,
            col[1].round().clamp(0.0, 255.0) as u8,
            col[2].round().clamp(0.0, 255.0) as u8,
            col[3].round().clamp(0.0, 255.0) as u8,
        ],
        sv.get_flags(),
    )
}

/// Computes a weighted linear combination of `SubdivVertex` values.
///
/// # Arguments
///
/// - `&[(SubdivVertex, f32)]` - Slice of `(vertex, weight)` pairs whose weights sum to `1.0`.
///
/// # Returns
///
/// - `SubdivVertex` - Blended vertex attributes.
#[must_use]
fn blend_subdiv_vertices(terms: &[(SubdivVertex, f32)]) -> SubdivVertex {
    let mut pos: Vec3 = Vec3::zero();
    let mut uv0: [f32; 2] = [0.0, 0.0];
    let mut uv1: [f32; 2] = [0.0, 0.0];
    let mut col: [f32; 4] = [0.0, 0.0, 0.0, 0.0];
    let mut flags: u32 = 0;
    for &(sv, w) in terms.iter() {
        pos = pos.add(sv.get_position().scale(w));
        let u0: [f32; 2] = sv.get_uv0();
        let u1: [f32; 2] = sv.get_uv1();
        let c: [f32; 4] = sv.get_color();
        uv0[0] += u0[0] * w;
        uv0[1] += u0[1] * w;
        uv1[0] += u1[0] * w;
        uv1[1] += u1[1] * w;
        col[0] += c[0] * w;
        col[1] += c[1] * w;
        col[2] += c[2] * w;
        col[3] += c[3] * w;
        flags |= sv.get_flags();
    }
    SubdivVertex {
        position: sanitize_vec3(pos, Vec3::zero()),
        uv0,
        uv1,
        color: col,
        flags,
    }
}

/// Averages a slice of `SubdivVertex` indices into a single centroid vertex.
///
/// # Arguments
///
/// - `&[SubdivVertex]` - Vertex attribute table.
/// - `&[u32]` - Vertex indices to average.
///
/// # Returns
///
/// - `SubdivVertex` - Uniformly averaged vertex attributes.
#[must_use]
fn average_subdiv_indices(verts: &[SubdivVertex], indices: &[u32]) -> SubdivVertex {
    if indices.is_empty() {
        return SubdivVertex::default();
    }
    let inv: f32 = 1.0 / (indices.len() as f32);
    let mut pos: Vec3 = Vec3::zero();
    let mut uv0: [f32; 2] = [0.0, 0.0];
    let mut uv1: [f32; 2] = [0.0, 0.0];
    let mut col: [f32; 4] = [0.0, 0.0, 0.0, 0.0];
    let mut flags: u32 = 0;
    for &idx in indices.iter() {
        let sv: SubdivVertex = verts[idx as usize];
        pos = pos.add(sv.get_position());
        let u0: [f32; 2] = sv.get_uv0();
        let u1: [f32; 2] = sv.get_uv1();
        let c: [f32; 4] = sv.get_color();
        uv0[0] += u0[0];
        uv0[1] += u0[1];
        uv1[0] += u1[0];
        uv1[1] += u1[1];
        col[0] += c[0];
        col[1] += c[1];
        col[2] += c[2];
        col[3] += c[3];
        flags |= sv.get_flags();
    }
    SubdivVertex {
        position: pos.scale(inv),
        uv0: [uv0[0] * inv, uv0[1] * inv],
        uv1: [uv1[0] * inv, uv1[1] * inv],
        color: [col[0] * inv, col[1] * inv, col[2] * inv, col[3] * inv],
        flags,
    }
}

/// Builds a canonical undirected edge key `(min, max)`.
///
/// # Arguments
///
/// - `u32` - First vertex index.
/// - `u32` - Second vertex index.
///
/// # Returns
///
/// - `(u32, u32)` - Ordered undirected edge key.
#[must_use]
fn edge_key(a: u32, b: u32) -> (u32, u32) {
    if a < b { (a, b) } else { (b, a) }
}

/// Returns `true` if four coplanar vertices form a strictly convex quad oriented along `face_normal`.
///
/// # Arguments
///
/// - `&[SubdivVertex]` - Vertex attribute table.
/// - `[u32; 4]` - Candidate CCW quad vertex indices.
/// - `Vec3` - Unit reference face normal.
///
/// # Returns
///
/// - `bool` - Whether all four corners turn strictly positively around `face_normal`.
#[must_use]
fn is_convex_quad(verts: &[SubdivVertex], q: [u32; 4], face_normal: Vec3) -> bool {
    for i in 0..4 {
        let p_prev: Vec3 = verts[q[(i + 3) % 4] as usize].get_position();
        let p_curr: Vec3 = verts[q[i] as usize].get_position();
        let p_next: Vec3 = verts[q[(i + 1) % 4] as usize].get_position();
        let e0: Vec3 = p_curr.sub(p_prev);
        let e1: Vec3 = p_next.sub(p_curr);
        if e0.cross(e1).dot(face_normal) <= 1e-7 {
            return false;
        }
    }
    true
}

/// Pairs coplanar adjacent triangles into convex quads before Catmull-Clark subdivision.
///
/// # Arguments
///
/// - `&[SubdivVertex]` - Welded vertex table.
/// - `&[[u32; 3]]` - Source triangle indices.
/// - `&[u16]` - Optional per-triangle material slots.
///
/// # Returns
///
/// - `Vec<PolyFace>` - Quad-dominant polygonal face list preserving original winding.
#[must_use]
fn build_quad_dominant_faces(
    verts: &[SubdivVertex],
    tris: &[[u32; 3]],
    tri_mats: &[u16],
) -> Vec<PolyFace> {
    let mut normals: Vec<Vec3> = Vec::with_capacity(tris.len());
    let mut half_edges: HashMap<(u32, u32), (usize, u32)> = HashMap::with_capacity(tris.len() * 3);
    for (ti, tri) in tris.iter().enumerate() {
        let p0: Vec3 = verts[tri[0] as usize].get_position();
        let p1: Vec3 = verts[tri[1] as usize].get_position();
        let p2: Vec3 = verts[tri[2] as usize].get_position();
        normals.push(safe_unit_normal(p1.sub(p0).cross(p2.sub(p0))));
        half_edges.insert((tri[0], tri[1]), (ti, tri[2]));
        half_edges.insert((tri[1], tri[2]), (ti, tri[0]));
        half_edges.insert((tri[2], tri[0]), (ti, tri[1]));
    }
    let mut used: Vec<bool> = vec![false; tris.len()];
    let mut faces: Vec<PolyFace> = Vec::with_capacity(tris.len());
    for (ti, tri) in tris.iter().enumerate() {
        if used[ti] {
            continue;
        }
        let mat_a: u16 = tri_mats.get(ti).copied().unwrap_or(0);
        let na: Vec3 = normals[ti];
        let mut best_pair: Option<(usize, [u32; 4], f32)> = None;
        let edges: [(u32, u32, u32); 3] = [
            (tri[0], tri[1], tri[2]),
            (tri[1], tri[2], tri[0]),
            (tri[2], tri[0], tri[1]),
        ];
        for (a, b, opp_a) in edges {
            if let Some(&(tj, opp_b)) = half_edges.get(&(b, a)) {
                if tj == ti || used[tj] {
                    continue;
                }
                let mat_b: u16 = tri_mats.get(tj).copied().unwrap_or(0);
                if mat_a != mat_b || na.dot(normals[tj]) < SUBDIV_COPLANAR_COS {
                    continue;
                }
                let quad: [u32; 4] = [a, opp_b, b, opp_a];
                if !is_convex_quad(verts, quad, na) {
                    continue;
                }
                let diag_len: f32 = verts[b as usize]
                    .get_position()
                    .sub(verts[a as usize].get_position())
                    .length_sq();
                let should_take: bool = match best_pair {
                    None => true,
                    Some((_, _, prev_len)) => diag_len > prev_len,
                };
                if should_take {
                    best_pair = Some((tj, quad, diag_len));
                }
            }
        }
        if let Some((tj, quad, _)) = best_pair {
            used[ti] = true;
            used[tj] = true;
            faces.push(PolyFace {
                vertices: quad.to_vec(),
                material_slot: mat_a,
            });
        } else {
            used[ti] = true;
            faces.push(PolyFace {
                vertices: tri.to_vec(),
                material_slot: mat_a,
            });
        }
    }
    faces
}

/// Performs one full topological Catmull-Clark subdivision step with boundary crease preservation.
///
/// # Arguments
///
/// - `&[SubdivVertex]` - Current control vertex array.
/// - `&[PolyFace]` - Current quad-dominant polygonal faces.
///
/// # Returns
///
/// - `(Vec<SubdivVertex>, Vec<PolyFace>)` - Refined control vertices and subdivided quad faces.
#[must_use]
fn catmull_clark_step(
    verts: &[SubdivVertex],
    faces: &[PolyFace],
) -> (Vec<SubdivVertex>, Vec<PolyFace>) {
    let orig_v_count: usize = verts.len();
    let face_count: usize = faces.len();
    let mut face_pts: Vec<SubdivVertex> = Vec::with_capacity(face_count);
    let mut edge_faces: HashMap<(u32, u32), Vec<usize>> = HashMap::with_capacity(face_count * 4);
    let mut vert_faces: Vec<Vec<usize>> = vec![Vec::new(); orig_v_count];
    let mut vert_edges: Vec<Vec<u32>> = vec![Vec::new(); orig_v_count];
    for (fi, face) in faces.iter().enumerate() {
        let fv: &[u32] = face.get_vertices();
        face_pts.push(average_subdiv_indices(verts, fv));
        let k: usize = fv.len();
        for i in 0..k {
            let a: u32 = fv[i];
            let b: u32 = fv[(i + 1) % k];
            vert_faces[a as usize].push(fi);
            if !vert_edges[a as usize].contains(&b) {
                vert_edges[a as usize].push(b);
            }
            if !vert_edges[b as usize].contains(&a) {
                vert_edges[b as usize].push(a);
            }
            edge_faces.entry(edge_key(a, b)).or_default().push(fi);
        }
    }
    let mut next_verts: Vec<SubdivVertex> =
        Vec::with_capacity(orig_v_count + face_count + edge_faces.len());
    for v_idx in 0..orig_v_count {
        let orig: SubdivVertex = verts[v_idx];
        let nbrs: &[u32] = &vert_edges[v_idx];
        let mut bnd_nbrs: Vec<u32> = Vec::new();
        for &nbr in nbrs.iter() {
            let inc_count: usize = edge_faces
                .get(&edge_key(v_idx as u32, nbr))
                .map_or(0, |list: &Vec<usize>| list.len());
            if inc_count == 1 {
                bnd_nbrs.push(nbr);
            }
        }
        let updated: SubdivVertex = if !bnd_nbrs.is_empty() {
            if bnd_nbrs.len() == 2 {
                blend_subdiv_vertices(&[
                    (orig, 0.75),
                    (verts[bnd_nbrs[0] as usize], 0.125),
                    (verts[bnd_nbrs[1] as usize], 0.125),
                ])
            } else {
                orig
            }
        } else {
            let n: usize = nbrs.len();
            let inc_f: &[usize] = &vert_faces[v_idx];
            if n >= 3 && !inc_f.is_empty() {
                let inv_f: f32 = 1.0 / (inc_f.len() as f32);
                let mut f_terms: Vec<(SubdivVertex, f32)> = Vec::with_capacity(inc_f.len());
                for &fi in inc_f.iter() {
                    f_terms.push((face_pts[fi], inv_f));
                }
                let f_avg: SubdivVertex = blend_subdiv_vertices(&f_terms);
                let inv_n: f32 = 1.0 / (n as f32);
                let mut r_terms: Vec<(SubdivVertex, f32)> = Vec::with_capacity(n + 1);
                r_terms.push((orig, 0.5));
                for &nbr in nbrs.iter() {
                    r_terms.push((verts[nbr as usize], 0.5 * inv_n));
                }
                let r_avg: SubdivVertex = blend_subdiv_vertices(&r_terms);
                let nf: f32 = n as f32;
                blend_subdiv_vertices(&[
                    (f_avg, 1.0 / nf),
                    (r_avg, 2.0 / nf),
                    (orig, (nf - 3.0) / nf),
                ])
            } else {
                orig
            }
        };
        next_verts.push(updated);
    }
    let face_base: u32 = next_verts.len() as u32;
    next_verts.extend_from_slice(&face_pts);
    let mut edge_vert_map: HashMap<(u32, u32), u32> = HashMap::with_capacity(edge_faces.len());
    for (&ek, inc_f) in edge_faces.iter() {
        let va: SubdivVertex = verts[ek.0 as usize];
        let vb: SubdivVertex = verts[ek.1 as usize];
        let edge_pt: SubdivVertex = if inc_f.len() == 2 {
            blend_subdiv_vertices(&[
                (va, 0.25),
                (vb, 0.25),
                (face_pts[inc_f[0]], 0.25),
                (face_pts[inc_f[1]], 0.25),
            ])
        } else {
            blend_subdiv_vertices(&[(va, 0.5), (vb, 0.5)])
        };
        let e_idx: u32 = next_verts.len() as u32;
        next_verts.push(edge_pt);
        edge_vert_map.insert(ek, e_idx);
    }
    let mut next_faces: Vec<PolyFace> = Vec::with_capacity(face_count * 4);
    for (fi, face) in faces.iter().enumerate() {
        let fv: &[u32] = face.get_vertices();
        let k: usize = fv.len();
        let f_vid: u32 = face_base + (fi as u32);
        let mat_slot: u16 = face.get_material_slot();
        for i in 0..k {
            let v_curr: u32 = fv[i];
            let v_next: u32 = fv[(i + 1) % k];
            let v_prev: u32 = fv[(i + k - 1) % k];
            let e_next: u32 = edge_vert_map
                .get(&edge_key(v_curr, v_next))
                .copied()
                .unwrap_or(v_curr);
            let e_prev: u32 = edge_vert_map
                .get(&edge_key(v_prev, v_curr))
                .copied()
                .unwrap_or(v_curr);
            next_faces.push(PolyFace {
                vertices: vec![v_curr, e_next, f_vid, e_prev],
                material_slot: mat_slot,
            });
        }
    }
    (next_verts, next_faces)
}

/// Performs quad-dominant Catmull-Clark smooth surface subdivision with boundary crease preservation.
///
/// # Arguments
///
/// - `&Mesh3D` - Source mesh to subdivide.
/// - `u32` - Number of subdivision levels (clamped to `0..=5`).
///
/// # Returns
///
/// - `Mesh3D` - Smoothly subdivided mesh with recomputed unit normals, tangents, and meshlets.
#[must_use]
pub fn subdivide_catmull_clark(mesh: &Mesh3D, levels: u32) -> Mesh3D {
    let iters: u32 = levels.min(SUBDIV_MAX_LEVELS);
    if iters == 0 || mesh.get_indices().is_empty() {
        return mesh.clone();
    }
    let welded: Mesh3D = weld_vertices(mesh, SUBDIV_WELD_EPSILON);
    let mut verts: Vec<SubdivVertex> = welded
        .get_vertices()
        .iter()
        .map(subdiv_vertex_from_mesh)
        .collect();
    let mut faces: Vec<PolyFace> =
        build_quad_dominant_faces(&verts, welded.get_indices(), welded.get_tri_materials());
    for _ in 0..iters {
        let (next_v, next_f): (Vec<SubdivVertex>, Vec<PolyFace>) =
            catmull_clark_step(&verts, &faces);
        verts = next_v;
        faces = next_f;
    }
    let has_sub_mats: bool = !welded.get_sub_materials().is_empty();
    let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(verts.len());
    for sv in verts.into_iter() {
        out_verts.push(subdiv_vertex_to_mesh(sv));
    }
    let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(faces.len() * 2);
    let mut out_tri_mats: Vec<u16> =
        Vec::with_capacity(if has_sub_mats { faces.len() * 2 } else { 0 });
    for face in faces.iter() {
        let fv: &[u32] = face.get_vertices();
        let mat: u16 = face.get_material_slot();
        if fv.len() == 3 {
            out_tris.push([fv[0], fv[1], fv[2]]);
            if has_sub_mats {
                out_tri_mats.push(mat);
            }
        } else if fv.len() == 4 {
            let d02: f32 = out_verts[fv[0] as usize]
                .get_position()
                .sub(out_verts[fv[2] as usize].get_position())
                .length_sq();
            let d13: f32 = out_verts[fv[1] as usize]
                .get_position()
                .sub(out_verts[fv[3] as usize].get_position())
                .length_sq();
            if d02 <= d13 {
                out_tris.push([fv[0], fv[1], fv[2]]);
                out_tris.push([fv[0], fv[2], fv[3]]);
            } else {
                out_tris.push([fv[0], fv[1], fv[3]]);
                out_tris.push([fv[1], fv[2], fv[3]]);
            }
            if has_sub_mats {
                out_tri_mats.push(mat);
                out_tri_mats.push(mat);
            }
        } else if fv.len() > 4 {
            for i in 1..(fv.len() - 1) {
                out_tris.push([fv[0], fv[i], fv[i + 1]]);
                if has_sub_mats {
                    out_tri_mats.push(mat);
                }
            }
        }
    }
    let mut out_mesh: Mesh3D = Mesh3D::from_parts(
        mesh.get_name().clone(),
        out_verts,
        out_tris,
        mesh.get_material(),
    );
    out_mesh.set_is_closed(mesh.get_is_closed());
    if has_sub_mats {
        out_mesh.set_sub_materials(welded.get_sub_materials().clone());
        out_mesh.set_tri_materials(out_tri_mats);
    }
    let smoothed: Mesh3D = recompute_smooth_normals(&out_mesh);
    compute_tangents(&smoothed)
}

/// Performs one full topological Loop triangle subdivision step with boundary crease preservation.
///
/// # Arguments
///
/// - `&[SubdivVertex]` - Current control vertex array.
/// - `&[[u32; 3]]` - Current triangle indices.
/// - `&[u16]` - Current per-triangle material slots.
///
/// # Returns
///
/// - `(Vec<SubdivVertex>, Vec<[u32; 3]>, Vec<u16>)` - Refined vertices, 4x triangle indices, and material slots.
#[must_use]
fn loop_subdiv_step(
    verts: &[SubdivVertex],
    tris: &[[u32; 3]],
    tri_mats: &[u16],
) -> (Vec<SubdivVertex>, Vec<[u32; 3]>, Vec<u16>) {
    let orig_v_count: usize = verts.len();
    let mut edge_opps: HashMap<(u32, u32), Vec<u32>> = HashMap::with_capacity(tris.len() * 2);
    let mut vert_nbrs: Vec<Vec<u32>> = vec![Vec::new(); orig_v_count];
    for tri in tris.iter() {
        let (a, b, c): (u32, u32, u32) = (tri[0], tri[1], tri[2]);
        edge_opps.entry(edge_key(a, b)).or_default().push(c);
        edge_opps.entry(edge_key(b, c)).or_default().push(a);
        edge_opps.entry(edge_key(c, a)).or_default().push(b);
        for (u, v) in [(a, b), (b, c), (c, a)] {
            if !vert_nbrs[u as usize].contains(&v) {
                vert_nbrs[u as usize].push(v);
            }
            if !vert_nbrs[v as usize].contains(&u) {
                vert_nbrs[v as usize].push(u);
            }
        }
    }
    let mut next_verts: Vec<SubdivVertex> = Vec::with_capacity(orig_v_count + edge_opps.len());
    for v_idx in 0..orig_v_count {
        let orig: SubdivVertex = verts[v_idx];
        let nbrs: &[u32] = &vert_nbrs[v_idx];
        let mut bnd_nbrs: Vec<u32> = Vec::new();
        for &nbr in nbrs.iter() {
            let opp_count: usize = edge_opps
                .get(&edge_key(v_idx as u32, nbr))
                .map_or(0, |list: &Vec<u32>| list.len());
            if opp_count == 1 {
                bnd_nbrs.push(nbr);
            }
        }
        let updated: SubdivVertex = if !bnd_nbrs.is_empty() {
            if bnd_nbrs.len() == 2 {
                blend_subdiv_vertices(&[
                    (orig, 0.75),
                    (verts[bnd_nbrs[0] as usize], 0.125),
                    (verts[bnd_nbrs[1] as usize], 0.125),
                ])
            } else {
                orig
            }
        } else {
            let n: usize = nbrs.len();
            if n >= 3 {
                let nf: f32 = n as f32;
                let term: f32 = 0.375 + 0.25 * (TAU / nf).cos();
                let beta: f32 = (0.625 - term * term) / nf;
                let mut blend_terms: Vec<(SubdivVertex, f32)> = Vec::with_capacity(n + 1);
                blend_terms.push((orig, 1.0 - nf * beta));
                for &nbr in nbrs.iter() {
                    blend_terms.push((verts[nbr as usize], beta));
                }
                blend_subdiv_vertices(&blend_terms)
            } else {
                orig
            }
        };
        next_verts.push(updated);
    }
    let mut edge_vert_map: HashMap<(u32, u32), u32> = HashMap::with_capacity(edge_opps.len());
    for (&ek, opps) in edge_opps.iter() {
        let va: SubdivVertex = verts[ek.0 as usize];
        let vb: SubdivVertex = verts[ek.1 as usize];
        let odd_pt: SubdivVertex = if opps.len() == 2 {
            blend_subdiv_vertices(&[
                (va, 0.375),
                (vb, 0.375),
                (verts[opps[0] as usize], 0.125),
                (verts[opps[1] as usize], 0.125),
            ])
        } else {
            blend_subdiv_vertices(&[(va, 0.5), (vb, 0.5)])
        };
        let e_idx: u32 = next_verts.len() as u32;
        next_verts.push(odd_pt);
        edge_vert_map.insert(ek, e_idx);
    }
    let mut next_tris: Vec<[u32; 3]> = Vec::with_capacity(tris.len() * 4);
    let has_mats: bool = !tri_mats.is_empty();
    let mut next_mats: Vec<u16> = Vec::with_capacity(if has_mats { tris.len() * 4 } else { 0 });
    for (ti, tri) in tris.iter().enumerate() {
        let (a, b, c): (u32, u32, u32) = (tri[0], tri[1], tri[2]);
        let ab: u32 = edge_vert_map.get(&edge_key(a, b)).copied().unwrap_or(a);
        let bc: u32 = edge_vert_map.get(&edge_key(b, c)).copied().unwrap_or(b);
        let ca: u32 = edge_vert_map.get(&edge_key(c, a)).copied().unwrap_or(c);
        next_tris.push([a, ab, ca]);
        next_tris.push([b, bc, ab]);
        next_tris.push([c, ca, bc]);
        next_tris.push([ab, bc, ca]);
        if has_mats {
            let slot: u16 = tri_mats.get(ti).copied().unwrap_or(0);
            next_mats.push(slot);
            next_mats.push(slot);
            next_mats.push(slot);
            next_mats.push(slot);
        }
    }
    (next_verts, next_tris, next_mats)
}

/// Performs Loop smooth triangle subdivision with exact `4x` per-level triangle growth and boundary crease preservation.
///
/// # Arguments
///
/// - `&Mesh3D` - Source triangle mesh to subdivide.
/// - `u32` - Number of subdivision levels (clamped to `0..=5`).
///
/// # Returns
///
/// - `Mesh3D` - Smoothly subdivided triangle mesh with recomputed unit normals, tangents, and meshlets.
#[must_use]
pub fn subdivide_loop(mesh: &Mesh3D, levels: u32) -> Mesh3D {
    let iters: u32 = levels.min(SUBDIV_MAX_LEVELS);
    if iters == 0 || mesh.get_indices().is_empty() {
        return mesh.clone();
    }
    let welded: Mesh3D = weld_vertices(mesh, SUBDIV_WELD_EPSILON);
    let mut verts: Vec<SubdivVertex> = welded
        .get_vertices()
        .iter()
        .map(subdiv_vertex_from_mesh)
        .collect();
    let mut tris: Vec<[u32; 3]> = welded.get_indices().to_vec();
    let mut tri_mats: Vec<u16> = welded.get_tri_materials().to_vec();
    for _ in 0..iters {
        let (nv, nt, nm): (Vec<SubdivVertex>, Vec<[u32; 3]>, Vec<u16>) =
            loop_subdiv_step(&verts, &tris, &tri_mats);
        verts = nv;
        tris = nt;
        tri_mats = nm;
    }
    let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(verts.len());
    for sv in verts.into_iter() {
        out_verts.push(subdiv_vertex_to_mesh(sv));
    }
    let mut out_mesh: Mesh3D = Mesh3D::from_parts(
        mesh.get_name().clone(),
        out_verts,
        tris,
        mesh.get_material(),
    );
    out_mesh.set_is_closed(mesh.get_is_closed());
    if !tri_mats.is_empty() {
        out_mesh.set_sub_materials(welded.get_sub_materials().clone());
        out_mesh.set_tri_materials(tri_mats);
    }
    let smoothed: Mesh3D = recompute_smooth_normals(&out_mesh);
    compute_tangents(&smoothed)
}