euv-core 0.56.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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
use super::*;

/// Computes the signed 2D shoelace area of polygon `profile` (positive for CCW winding).
///
/// # Arguments
///
/// - `&[Vec2]` - Ordered 2D polygon vertices.
///
/// # Returns
///
/// - `f32` - Signed polygon area (`> 0` for counter-clockwise).
#[must_use]
fn polygon_signed_area_2d(profile: &[Vec2]) -> f32 {
    if profile.len() < 3 {
        return 0.0;
    }
    let mut area2: f32 = 0.0;
    let n: usize = profile.len();
    for i in 0..n {
        let a: Vec2 = profile[i];
        let b: Vec2 = profile[(i + 1) % n];
        area2 += a.get_x() * b.get_y() - b.get_x() * a.get_y();
    }
    area2 * 0.5
}

/// Computes the 2D cross product `(b - a) x (c - a)`.
///
/// # Arguments
///
/// - `Vec2` - First vertex `a`.
/// - `Vec2` - Second vertex `b`.
/// - `Vec2` - Third vertex `c`.
///
/// # Returns
///
/// - `f32` - Signed twice-triangle-area scalar.
#[must_use]
fn cross_2d(a: Vec2, b: Vec2, c: Vec2) -> f32 {
    (b.get_x() - a.get_x()) * (c.get_y() - a.get_y())
        - (b.get_y() - a.get_y()) * (c.get_x() - a.get_x())
}

/// Returns `true` when 2D point `pt` lies inside or on the boundary of CCW triangle `(a, b, c)`.
///
/// # Arguments
///
/// - `Vec2` - Query point.
/// - `Vec2` - Triangle corner `a`.
/// - `Vec2` - Triangle corner `b`.
/// - `Vec2` - Triangle corner `c`.
///
/// # Returns
///
/// - `bool` - Whether `pt` falls inside or on the edges of `(a, b, c)`.
#[must_use]
fn point_in_triangle_2d(pt: Vec2, a: Vec2, b: Vec2, c: Vec2) -> bool {
    let c0: f32 = cross_2d(a, b, pt);
    let c1: f32 = cross_2d(b, c, pt);
    let c2: f32 = cross_2d(c, a, pt);
    c0 >= -1e-7 && c1 >= -1e-7 && c2 >= -1e-7
}

/// Removes consecutive duplicate or non-finite vertices from a 2D polygon and ensures CCW winding.
///
/// # Arguments
///
/// - `&[Vec2]` - Input 2D profile vertices.
///
/// # Returns
///
/// - `Vec<Vec2>` - Cleaned counter-clockwise simple polygon vertices.
#[must_use]
fn sanitize_ccw_profile(profile_2d: &[Vec2]) -> Vec<Vec2> {
    let mut clean: Vec<Vec2> = Vec::with_capacity(profile_2d.len());
    for pt in profile_2d.iter() {
        let p: Vec2 = Vec2::new(
            sanitize_scalar(pt.get_x(), 0.0),
            sanitize_scalar(pt.get_y(), 0.0),
        );
        if let Some(&last) = clean.last() {
            let dx: f32 = p.get_x() - last.get_x();
            let dy: f32 = p.get_y() - last.get_y();
            if dx * dx + dy * dy <= 1e-10 {
                continue;
            }
        }
        clean.push(p);
    }
    if clean.len() >= 2 {
        let first: Vec2 = clean[0];
        let last: Vec2 = clean[clean.len() - 1];
        let dx: f32 = first.get_x() - last.get_x();
        let dy: f32 = first.get_y() - last.get_y();
        if dx * dx + dy * dy <= 1e-10 {
            clean.pop();
        }
    }
    if polygon_signed_area_2d(&clean) < 0.0 {
        clean.reverse();
    }
    clean
}

/// Triangulates a simple 2D polygon (convex or concave) using robust ear-clipping.
///
/// # Arguments
///
/// - `&[Vec2]` - Simple 2D polygon vertices in either CW or CCW order.
///
/// # Returns
///
/// - `Vec<[usize; 3]>` - Counter-clockwise triangle index triplets referencing `profile_2d`.
#[must_use]
pub fn triangulate_polygon_2d(profile_2d: &[Vec2]) -> Vec<[usize; 3]> {
    let n: usize = profile_2d.len();
    if n < 3 {
        return Vec::new();
    }
    let mut ring: Vec<usize> = (0..n).collect();
    if polygon_signed_area_2d(profile_2d) < 0.0 {
        ring.reverse();
    }
    let mut tris: Vec<[usize; 3]> = Vec::with_capacity(n - 2);
    let mut guard: usize = n * n + 4;
    while ring.len() > 3 && guard > 0 {
        guard -= 1;
        let len: usize = ring.len();
        let mut clipped: bool = false;
        for i in 0..len {
            let prev: usize = ring[(i + len - 1) % len];
            let curr: usize = ring[i];
            let next: usize = ring[(i + 1) % len];
            let a: Vec2 = profile_2d[prev];
            let b: Vec2 = profile_2d[curr];
            let c: Vec2 = profile_2d[next];
            if cross_2d(a, b, c) <= 1e-8 {
                continue;
            }
            let mut has_inside: bool = false;
            for (k, &test_idx) in ring.iter().enumerate() {
                if k == i || k == (i + len - 1) % len || k == (i + 1) % len {
                    continue;
                }
                if point_in_triangle_2d(profile_2d[test_idx], a, b, c) {
                    has_inside = true;
                    break;
                }
            }
            if !has_inside {
                tris.push([prev, curr, next]);
                ring.remove(i);
                clipped = true;
                break;
            }
        }
        if !clipped {
            let mut best_i: usize = 0;
            let mut best_area: f32 = f32::NEG_INFINITY;
            for i in 0..len {
                let prev: usize = ring[(i + len - 1) % len];
                let curr: usize = ring[i];
                let next: usize = ring[(i + 1) % len];
                let area: f32 = cross_2d(profile_2d[prev], profile_2d[curr], profile_2d[next]);
                if area > best_area {
                    best_area = area;
                    best_i = i;
                }
            }
            let prev: usize = ring[(best_i + len - 1) % len];
            let curr: usize = ring[best_i];
            let next: usize = ring[(best_i + 1) % len];
            tris.push([prev, curr, next]);
            ring.remove(best_i);
        }
    }
    if ring.len() == 3 {
        tris.push([ring[0], ring[1], ring[2]]);
    }
    tris
}

/// Computes bounded inward miter offset vectors for each vertex of a CCW 2D polygon.
///
/// # Arguments
///
/// - `&[Vec2]` - Cleaned CCW 2D polygon vertices.
///
/// # Returns
///
/// - `Vec<Vec2>` - Per-vertex inward miter offset vectors (clamped to prevent miter spikes).
#[must_use]
fn compute_inward_miters(profile: &[Vec2]) -> Vec<Vec2> {
    let n: usize = profile.len();
    let mut miters: Vec<Vec2> = Vec::with_capacity(n);
    for i in 0..n {
        let prev: Vec2 = profile[(i + n - 1) % n];
        let curr: Vec2 = profile[i];
        let next: Vec2 = profile[(i + 1) % n];
        let e0x: f32 = curr.get_x() - prev.get_x();
        let e0y: f32 = curr.get_y() - prev.get_y();
        let e1x: f32 = next.get_x() - curr.get_x();
        let e1y: f32 = next.get_y() - curr.get_y();
        let l0: f32 = (e0x * e0x + e0y * e0y).sqrt().max(SPLINE_EPSILON);
        let l1: f32 = (e1x * e1x + e1y * e1y).sqrt().max(SPLINE_EPSILON);
        let n0x: f32 = -e0y / l0;
        let n0y: f32 = e0x / l0;
        let n1x: f32 = -e1y / l1;
        let n1y: f32 = e1x / l1;
        let bx: f32 = n0x + n1x;
        let by: f32 = n0y + n1y;
        let blen: f32 = (bx * bx + by * by).sqrt();
        if blen > SPLINE_EPSILON {
            let ux: f32 = bx / blen;
            let uy: f32 = by / blen;
            let denom: f32 = (ux * n0x + uy * n0y).max(0.35);
            let scale: f32 = (1.0 / denom).min(2.5);
            miters.push(Vec2::new(ux * scale, uy * scale));
        } else {
            miters.push(Vec2::new(n0x, n0y));
        }
    }
    miters
}

/// Evaluates a piecewise-linear scale curve at normalized parameter `t` in `[0, 1]`.
///
/// # Arguments
///
/// - `&[f32]` - Scale curve samples along the spline (defaults to `1.0` when empty).
/// - `f32` - Normalized parameter in `[0, 1]`.
///
/// # Returns
///
/// - `f32` - Clamped positive finite scale multiplier.
#[must_use]
fn sample_scale_curve(scale_curve: &[f32], t: f32) -> f32 {
    if scale_curve.is_empty() {
        return 1.0;
    }
    if scale_curve.len() == 1 {
        return sanitize_scalar(scale_curve[0], 1.0).abs().max(1e-4);
    }
    let scaled: f32 = t.clamp(0.0, 1.0) * ((scale_curve.len() - 1) as f32);
    let idx0: usize = (scaled.floor() as usize).min(scale_curve.len() - 2);
    let frac: f32 = scaled - (idx0 as f32);
    let s0: f32 = sanitize_scalar(scale_curve[idx0], 1.0);
    let s1: f32 = sanitize_scalar(scale_curve[idx0 + 1], 1.0);
    (s0 + (s1 - s0) * frac).abs().max(1e-4)
}

/// Extrudes a 2D polygon along the Z axis with optional rounded front and back bevel caps.
///
/// # Arguments
///
/// - `&[Vec2]` - Simple 2D polygon cross-section vertices.
/// - `f32` - Total extrusion depth along Z.
/// - `f32` - Corner bevel radius (`0.0` produces sharp flat caps).
/// - `u32` - Bevel arc segment count per cap (`0` produces sharp flat caps).
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound extruded 3D mesh with ear-clipped end caps.
#[must_use]
pub fn extrude_profile(
    profile_2d: &[Vec2],
    depth: f32,
    bevel_size: f32,
    bevel_segs: u32,
) -> Mesh3D {
    let profile: Vec<Vec2> = sanitize_ccw_profile(profile_2d);
    let n: usize = profile.len();
    if n < 3 {
        return Mesh3D::from_parts(
            SPLINE_NAME_EXTRUDE.to_string(),
            Vec::new(),
            Vec::new(),
            PbrMaterial::default(),
        );
    }
    let d: f32 = sanitize_scalar(depth, 1.0).abs().max(1e-4);
    let half_d: f32 = d * 0.5;
    let mut min_x: f32 = f32::INFINITY;
    let mut max_x: f32 = f32::NEG_INFINITY;
    let mut min_y: f32 = f32::INFINITY;
    let mut max_y: f32 = f32::NEG_INFINITY;
    let mut min_edge: f32 = f32::INFINITY;
    for i in 0..n {
        let p: Vec2 = profile[i];
        let q: Vec2 = profile[(i + 1) % n];
        min_x = min_x.min(p.get_x());
        max_x = max_x.max(p.get_x());
        min_y = min_y.min(p.get_y());
        max_y = max_y.max(p.get_y());
        let edge_len: f32 =
            ((q.get_x() - p.get_x()).powi(2) + (q.get_y() - p.get_y()).powi(2)).sqrt();
        min_edge = min_edge.min(edge_len);
    }
    let span_x: f32 = (max_x - min_x).max(1e-4);
    let span_y: f32 = (max_y - min_y).max(1e-4);
    let max_bevel: f32 = (half_d * 0.45)
        .min(min_edge * 0.35)
        .min(span_x.min(span_y) * 0.2);
    let bevel: f32 = if bevel_segs == 0 {
        0.0
    } else {
        sanitize_scalar(bevel_size, 0.0).clamp(0.0, max_bevel)
    };
    let bsegs: usize = if bevel > 1e-5 {
        bevel_segs.clamp(1, 12) as usize
    } else {
        0
    };
    let miters: Vec<Vec2> = compute_inward_miters(&profile);
    let mut ring_specs: Vec<(f32, f32, f32)> = Vec::with_capacity(bsegs * 2 + 2);
    if bsegs == 0 {
        ring_specs.push((-half_d, 0.0, 0.0));
        ring_specs.push((half_d, 0.0, 1.0));
    } else {
        for i in 0..=bsegs {
            let angle: f32 = ((i as f32) / (bsegs as f32)) * FRAC_PI_2;
            let z: f32 = -half_d + bevel * (1.0 - angle.cos());
            let inset: f32 = bevel * (1.0 - angle.sin());
            ring_specs.push((z, inset, (z + half_d) / d));
        }
        for i in 0..=bsegs {
            let angle: f32 = ((i as f32) / (bsegs as f32)) * FRAC_PI_2;
            let z: f32 = (half_d - bevel) + bevel * angle.sin();
            let inset: f32 = bevel * (1.0 - angle.cos());
            ring_specs.push((z, inset, (z + half_d) / d));
        }
    }
    let ring_count: usize = ring_specs.len();
    let mut perim: Vec<f32> = Vec::with_capacity(n + 1);
    perim.push(0.0);
    let mut total_perim: f32 = 0.0;
    for i in 0..n {
        let p: Vec2 = profile[i];
        let q: Vec2 = profile[(i + 1) % n];
        total_perim += ((q.get_x() - p.get_x()).powi(2) + (q.get_y() - p.get_y()).powi(2)).sqrt();
        perim.push(total_perim);
    }
    let inv_perim: f32 = 1.0 / total_perim.max(1e-4);
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(ring_count * (n + 1) + n * 2);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity((ring_count - 1) * n * 2 + (n - 2) * 2);
    let stride: usize = n + 1;
    for &(z_val, inset_val, v_uv) in ring_specs.iter() {
        for (i, &p_dist) in perim.iter().enumerate() {
            let pi: usize = i % n;
            let p: Vec2 = profile[pi];
            let m: Vec2 = miters[pi];
            let pos: Vec3 = Vec3::new(
                p.get_x() + m.get_x() * inset_val,
                p.get_y() + m.get_y() * inset_val,
                z_val,
            );
            let out_n: Vec3 = safe_unit_normal(Vec3::new(-m.get_x(), -m.get_y(), 0.0));
            vertices.push(make_textured_vertex(pos, out_n, [p_dist * inv_perim, v_uv]));
        }
    }
    for r in 0..(ring_count - 1) {
        let row0: u32 = (r * stride) as u32;
        let row1: u32 = ((r + 1) * stride) as u32;
        for i in 0..n {
            let iu: u32 = i as u32;
            let v00: u32 = row0 + iu;
            let v10: u32 = row0 + iu + 1;
            let v01: u32 = row1 + iu;
            let v11: u32 = row1 + iu + 1;
            indices.push([v00, v10, v11]);
            indices.push([v00, v11, v01]);
        }
    }
    let cap_inset: f32 = ring_specs[0].1;
    let mut cap_poly: Vec<Vec2> = Vec::with_capacity(n);
    for i in 0..n {
        cap_poly.push(Vec2::new(
            profile[i].get_x() + miters[i].get_x() * cap_inset,
            profile[i].get_y() + miters[i].get_y() * cap_inset,
        ));
    }
    let cap_tris: Vec<[usize; 3]> = triangulate_polygon_2d(&cap_poly);
    let front_base: u32 = vertices.len() as u32;
    let front_n: Vec3 = Vec3::new(0.0, 0.0, 1.0);
    for p in cap_poly.iter() {
        vertices.push(make_textured_vertex(
            Vec3::new(p.get_x(), p.get_y(), half_d),
            front_n,
            [(p.get_x() - min_x) / span_x, (p.get_y() - min_y) / span_y],
        ));
    }
    for tri in cap_tris.iter() {
        indices.push([
            front_base + (tri[0] as u32),
            front_base + (tri[1] as u32),
            front_base + (tri[2] as u32),
        ]);
    }
    let back_base: u32 = vertices.len() as u32;
    let back_n: Vec3 = Vec3::new(0.0, 0.0, -1.0);
    for p in cap_poly.iter() {
        vertices.push(make_textured_vertex(
            Vec3::new(p.get_x(), p.get_y(), -half_d),
            back_n,
            [
                1.0 - (p.get_x() - min_x) / span_x,
                (p.get_y() - min_y) / span_y,
            ],
        ));
    }
    for tri in cap_tris.iter() {
        indices.push([
            back_base + (tri[0] as u32),
            back_base + (tri[2] as u32),
            back_base + (tri[1] as u32),
        ]);
    }
    let mut mesh: Mesh3D = Mesh3D::from_parts(
        SPLINE_NAME_EXTRUDE.to_string(),
        vertices,
        indices,
        PbrMaterial::default(),
    );
    mesh.set_is_closed(true);
    let smoothed: Mesh3D = recompute_smooth_normals(&mesh);
    compute_tangents(&smoothed)
}

/// Revolves a 2D profile `(radius = x, height = y)` around the Y axis to form a rotational surface or solid.
///
/// # Arguments
///
/// - `&[Vec2]` - 2D profile points `(radius, height)` revolved about the Y axis.
/// - `u32` - Angular segment count around the revolution sweep (clamped to `>= 3`).
/// - `f32` - Revolution angle in radians (clamped to `(0, TAU]`).
///
/// # Returns
///
/// - `Mesh3D` - Outward-wound revolved surface or closed solid mesh.
#[must_use]
pub fn lathe_revolve(profile_2d: &[Vec2], segments: u32, sweep_angle: f32) -> Mesh3D {
    if profile_2d.len() < 2 {
        return Mesh3D::from_parts(
            SPLINE_NAME_LATHE.to_string(),
            Vec::new(),
            Vec::new(),
            PbrMaterial::default(),
        );
    }
    let mut profile: Vec<Vec2> = Vec::with_capacity(profile_2d.len());
    for pt in profile_2d.iter() {
        profile.push(Vec2::new(
            sanitize_scalar(pt.get_x(), 0.0).max(0.0),
            sanitize_scalar(pt.get_y(), 0.0),
        ));
    }
    let mut vol_hint: f32 = 0.0;
    for i in 0..(profile.len() - 1) {
        let a: Vec2 = profile[i];
        let b: Vec2 = profile[i + 1];
        vol_hint += (a.get_x() * a.get_x() + a.get_x() * b.get_x() + b.get_x() * b.get_x())
            * (b.get_y() - a.get_y());
    }
    if vol_hint < 0.0 {
        profile.reverse();
    }
    let segs: usize = segments.max(3) as usize;
    let sweep: f32 = sanitize_scalar(sweep_angle, TAU).clamp(1e-3, TAU);
    let full_turn: bool = (TAU - sweep).abs() < 1e-4;
    let plen: usize = profile.len();
    let mut prof_norms: Vec<(f32, f32)> = Vec::with_capacity(plen);
    let mut arc_v: Vec<f32> = Vec::with_capacity(plen);
    let mut total_v: f32 = 0.0;
    arc_v.push(0.0);
    for i in 0..plen {
        if i > 0 {
            let dr: f32 = profile[i].get_x() - profile[i - 1].get_x();
            let dy: f32 = profile[i].get_y() - profile[i - 1].get_y();
            total_v += (dr * dr + dy * dy).sqrt();
            arc_v.push(total_v);
        }
        let prev_i: usize = i.saturating_sub(1);
        let next_i: usize = (i + 1).min(plen - 1);
        let dr: f32 = profile[next_i].get_x() - profile[prev_i].get_x();
        let dy: f32 = profile[next_i].get_y() - profile[prev_i].get_y();
        let len: f32 = (dr * dr + dy * dy).sqrt().max(SPLINE_EPSILON);
        prof_norms.push((dy / len, -dr / len));
    }
    let inv_v: f32 = 1.0 / total_v.max(1e-4);
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * plen);
    let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * (plen - 1) * 2);
    for s in 0..=segs {
        let u_frac: f32 = (s as f32) / (segs as f32);
        let theta: f32 = if full_turn && s == segs {
            0.0
        } else {
            u_frac * sweep
        };
        let ct: f32 = theta.cos();
        let st: f32 = theta.sin();
        for p in 0..plen {
            let r: f32 = profile[p].get_x();
            let y: f32 = profile[p].get_y();
            let (nr, ny): (f32, f32) = prof_norms[p];
            let pos: Vec3 = Vec3::new(r * ct, y, r * st);
            let normal: Vec3 = safe_unit_normal(Vec3::new(nr * ct, ny, nr * st));
            vertices.push(make_textured_vertex(
                pos,
                normal,
                [u_frac, arc_v[p] * inv_v],
            ));
        }
    }
    for s in 0..segs {
        let row0: u32 = (s * plen) as u32;
        let row1: u32 = ((s + 1) * plen) as u32;
        for p in 0..(plen - 1) {
            let pu: u32 = p as u32;
            let r0: f32 = profile[p].get_x();
            let r1: f32 = profile[p + 1].get_x();
            let i00: u32 = row0 + pu;
            let i10: u32 = row1 + pu;
            let i01: u32 = row0 + pu + 1;
            let i11: u32 = row1 + pu + 1;
            if r0 > 1e-6 {
                indices.push([i00, i01, i10]);
            }
            if r1 > 1e-6 {
                indices.push([i01, i11, i10]);
            }
        }
    }
    let first_pt: Vec2 = profile[0];
    let last_pt: Vec2 = profile[plen - 1];
    let ends_meet: bool = (first_pt.get_x() - last_pt.get_x()).abs() < 1e-4
        && (first_pt.get_y() - last_pt.get_y()).abs() < 1e-4;
    let ends_on_axis: bool = first_pt.get_x() <= 1e-4 && last_pt.get_x() <= 1e-4;
    let is_closed: bool = full_turn && (ends_meet || ends_on_axis);
    let mut mesh: Mesh3D = Mesh3D::from_parts(
        SPLINE_NAME_LATHE.to_string(),
        vertices,
        indices,
        PbrMaterial::default(),
    );
    mesh.set_is_closed(is_closed);
    compute_tangents(&mesh)
}

/// Sweeps a 2D closed profile along a `Spline3D` using twist-free Bishop frames and an optional scale curve.
///
/// # Arguments
///
/// - `&[Vec2]` - Simple 2D closed profile cross-section.
/// - `&Spline3D` - Spine trajectory curve.
/// - `u32` - Number of cross-section rings sampled along the spline (clamped to `>= 2`).
/// - `&[f32]` - Optional scale multipliers interpolated along the spline length.
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound swept tube mesh with end caps when the spline is open.
#[must_use]
pub fn sweep_along_spline(
    profile_2d: &[Vec2],
    spline: &Spline3D,
    samples: u32,
    scale_curve: &[f32],
) -> Mesh3D {
    let profile: Vec<Vec2> = sanitize_ccw_profile(profile_2d);
    let plen: usize = profile.len();
    if plen < 3 || spline.get_control_points().len() < 2 {
        return Mesh3D::from_parts(
            SPLINE_NAME_SWEEP.to_string(),
            Vec::new(),
            Vec::new(),
            PbrMaterial::default(),
        );
    }
    let ring_count: usize = samples.max(2) as usize;
    let frames: Vec<SplineFrame3D> = spline.sample_bishop_frames(ring_count);
    let is_closed: bool = spline.get_closed();
    let stride: usize = plen + 1;
    let total_rings: usize = if is_closed {
        ring_count + 1
    } else {
        ring_count
    };
    let mut perim: Vec<f32> = Vec::with_capacity(plen + 1);
    perim.push(0.0);
    let mut total_perim: f32 = 0.0;
    for i in 0..plen {
        let a: Vec2 = profile[i];
        let b: Vec2 = profile[(i + 1) % plen];
        total_perim += ((b.get_x() - a.get_x()).powi(2) + (b.get_y() - a.get_y()).powi(2)).sqrt();
        perim.push(total_perim);
    }
    let inv_perim: f32 = 1.0 / total_perim.max(1e-4);
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(total_rings * stride + plen * 2);
    let mut indices: Vec<[u32; 3]> =
        Vec::with_capacity((total_rings - 1) * plen * 2 + (plen - 2) * 2);
    for r in 0..total_rings {
        let frame_idx: usize = r % ring_count;
        let frame: SplineFrame3D = frames[frame_idx];
        let v_frac: f32 = (r as f32) / ((total_rings - 1).max(1) as f32);
        let sc: f32 = sample_scale_curve(scale_curve, v_frac);
        let origin: Vec3 = frame.get_position();
        let n_axis: Vec3 = frame.get_normal();
        let b_axis: Vec3 = frame.get_binormal();
        for (i, &p_dist) in perim.iter().enumerate() {
            let pi: usize = i % plen;
            let p2: Vec2 = profile[pi];
            let offset: Vec3 = n_axis
                .scale(p2.get_x() * sc)
                .add(b_axis.scale(p2.get_y() * sc));
            let pos: Vec3 = origin.add(offset);
            let normal: Vec3 = safe_unit_normal(offset);
            vertices.push(make_textured_vertex(
                pos,
                normal,
                [p_dist * inv_perim, v_frac],
            ));
        }
    }
    for r in 0..(total_rings - 1) {
        let row0: u32 = (r * stride) as u32;
        let row1: u32 = ((r + 1) * stride) as u32;
        for i in 0..plen {
            let iu: u32 = i as u32;
            let v00: u32 = row0 + iu;
            let v10: u32 = row0 + iu + 1;
            let v01: u32 = row1 + iu;
            let v11: u32 = row1 + iu + 1;
            indices.push([v00, v10, v11]);
            indices.push([v00, v11, v01]);
        }
    }
    if !is_closed {
        let cap_tris: Vec<[usize; 3]> = triangulate_polygon_2d(&profile);
        let start_frame: SplineFrame3D = frames[0];
        let start_sc: f32 = sample_scale_curve(scale_curve, 0.0);
        let start_n: Vec3 = start_frame.get_tangent().scale(-1.0);
        let start_base: u32 = vertices.len() as u32;
        for p2 in profile.iter() {
            let pos: Vec3 = start_frame
                .get_position()
                .add(start_frame.get_normal().scale(p2.get_x() * start_sc))
                .add(start_frame.get_binormal().scale(p2.get_y() * start_sc));
            vertices.push(make_textured_vertex(pos, start_n, [p2.get_x(), p2.get_y()]));
        }
        for tri in cap_tris.iter() {
            indices.push([
                start_base + (tri[0] as u32),
                start_base + (tri[2] as u32),
                start_base + (tri[1] as u32),
            ]);
        }
        let end_frame: SplineFrame3D = frames[ring_count - 1];
        let end_sc: f32 = sample_scale_curve(scale_curve, 1.0);
        let end_n: Vec3 = end_frame.get_tangent();
        let end_base: u32 = vertices.len() as u32;
        for p2 in profile.iter() {
            let pos: Vec3 = end_frame
                .get_position()
                .add(end_frame.get_normal().scale(p2.get_x() * end_sc))
                .add(end_frame.get_binormal().scale(p2.get_y() * end_sc));
            vertices.push(make_textured_vertex(pos, end_n, [p2.get_x(), p2.get_y()]));
        }
        for tri in cap_tris.iter() {
            indices.push([
                end_base + (tri[0] as u32),
                end_base + (tri[1] as u32),
                end_base + (tri[2] as u32),
            ]);
        }
    }
    let mut mesh: Mesh3D = Mesh3D::from_parts(
        SPLINE_NAME_SWEEP.to_string(),
        vertices,
        indices,
        PbrMaterial::default(),
    );
    mesh.set_is_closed(true);
    let smoothed: Mesh3D = recompute_smooth_normals(&mesh);
    compute_tangents(&smoothed)
}

/// Resamples a closed 3D ring to `target_count` points uniformly distributed along its perimeter.
///
/// # Arguments
///
/// - `&[Vec3]` - Source 3D ring vertices.
/// - `usize` - Target resampled vertex count.
///
/// # Returns
///
/// - `Vec<Vec3>` - Uniformly resampled 3D ring.
#[must_use]
fn resample_ring_3d(ring: &[Vec3], target_count: usize) -> Vec<Vec3> {
    let n: usize = ring.len();
    if n == 0 {
        return Vec::new();
    }
    if n == target_count {
        return ring
            .iter()
            .map(|p: &Vec3| sanitize_vec3(*p, Vec3::zero()))
            .collect();
    }
    let mut cum: Vec<f32> = Vec::with_capacity(n + 1);
    cum.push(0.0);
    let mut total: f32 = 0.0;
    for i in 0..n {
        let a: Vec3 = sanitize_vec3(ring[i], Vec3::zero());
        let b: Vec3 = sanitize_vec3(ring[(i + 1) % n], Vec3::zero());
        total += b.sub(a).length();
        cum.push(total);
    }
    let mut out: Vec<Vec3> = Vec::with_capacity(target_count);
    for k in 0..target_count {
        let target_d: f32 = total * ((k as f32) / (target_count as f32));
        let mut seg: usize = 0;
        while seg + 1 < n && cum[seg + 1] < target_d {
            seg += 1;
        }
        let span: f32 = cum[seg + 1] - cum[seg];
        let alpha: f32 = if span > SPLINE_EPSILON {
            ((target_d - cum[seg]) / span).clamp(0.0, 1.0)
        } else {
            0.0
        };
        let a: Vec3 = sanitize_vec3(ring[seg], Vec3::zero());
        let b: Vec3 = sanitize_vec3(ring[(seg + 1) % n], Vec3::zero());
        out.push(a.lerp(b, alpha));
    }
    out
}

/// Computes the centroid and Newell polygon normal of a 3D ring.
///
/// # Arguments
///
/// - `&[Vec3]` - Ordered 3D ring vertices.
///
/// # Returns
///
/// - `(Vec3, Vec3)` - Ring centroid and unit Newell normal.
#[must_use]
fn ring_centroid_and_normal(ring: &[Vec3]) -> (Vec3, Vec3) {
    let n: usize = ring.len();
    if n == 0 {
        return (Vec3::zero(), Vec3::new(0.0, 1.0, 0.0));
    }
    let mut sum: Vec3 = Vec3::zero();
    let mut newell: Vec3 = Vec3::zero();
    for i in 0..n {
        let a: Vec3 = ring[i];
        let b: Vec3 = ring[(i + 1) % n];
        sum = sum.add(a);
        newell = newell.add(Vec3::new(
            (a.get_y() - b.get_y()) * (a.get_z() + b.get_z()),
            (a.get_z() - b.get_z()) * (a.get_x() + b.get_x()),
            (a.get_x() - b.get_x()) * (a.get_y() + b.get_y()),
        ));
    }
    (sum.scale(1.0 / (n as f32)), safe_unit_normal(newell))
}

/// Caps a 3D ring onto `vertices`/`indices` with outward normal `cap_normal` using plane projection + ear-clipping.
///
/// # Arguments
///
/// - `&[Vec3]` - Ordered 3D ring vertices.
/// - `Vec3` - Desired outward cap unit normal.
/// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
/// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
fn append_ring_cap_3d(
    ring: &[Vec3],
    cap_normal: Vec3,
    vertices: &mut Vec<Vertex3D>,
    indices: &mut Vec<[u32; 3]>,
) {
    let (center, _): (Vec3, Vec3) = ring_centroid_and_normal(ring);
    let n: Vec3 = safe_unit_normal(cap_normal);
    let seed: Vec3 = if n.get_y().abs() < 0.9 {
        Vec3::new(0.0, 1.0, 0.0)
    } else {
        Vec3::new(1.0, 0.0, 0.0)
    };
    let u_axis: Vec3 = safe_unit_normal(seed.cross(n));
    let v_axis: Vec3 = safe_unit_normal(n.cross(u_axis));
    let mut projected: Vec<Vec2> = Vec::with_capacity(ring.len());
    for pt in ring.iter() {
        let rel: Vec3 = pt.sub(center);
        projected.push(Vec2::new(rel.dot(u_axis), rel.dot(v_axis)));
    }
    let tris: Vec<[usize; 3]> = triangulate_polygon_2d(&projected);
    let base: u32 = vertices.len() as u32;
    for (idx, pt) in ring.iter().enumerate() {
        let uv2: Vec2 = projected[idx];
        vertices.push(make_textured_vertex(*pt, n, [uv2.get_x(), uv2.get_y()]));
    }
    for tri in tris.iter() {
        let p0: Vec3 = ring[tri[0]];
        let p1: Vec3 = ring[tri[1]];
        let p2: Vec3 = ring[tri[2]];
        if p1.sub(p0).cross(p2.sub(p0)).dot(n) >= 0.0 {
            indices.push([
                base + (tri[0] as u32),
                base + (tri[1] as u32),
                base + (tri[2] as u32),
            ]);
        } else {
            indices.push([
                base + (tri[0] as u32),
                base + (tri[2] as u32),
                base + (tri[1] as u32),
            ]);
        }
    }
}

/// Lofts a watertight 3D surface through an ordered sequence of 3D cross-section profiles.
///
/// # Arguments
///
/// - `&[Vec<Vec3>]` - Ordered sequence of 3D cross-section rings (at least 2 rings of `>= 3` vertices).
/// - `bool` - Whether the loft wraps seamlessly from the final ring back to the first ring.
///
/// # Returns
///
/// - `Mesh3D` - Watertight outward-wound lofted 3D mesh with end caps when `closed` is `false`.
#[must_use]
pub fn loft_profiles(profiles_3d: &[Vec<Vec3>], closed: bool) -> Mesh3D {
    let valid_rings: Vec<&Vec<Vec3>> = profiles_3d
        .iter()
        .filter(|r: &&Vec<Vec3>| r.len() >= 3)
        .collect();
    if valid_rings.len() < 2 {
        return Mesh3D::from_parts(
            SPLINE_NAME_LOFT.to_string(),
            Vec::new(),
            Vec::new(),
            PbrMaterial::default(),
        );
    }
    let max_ring_len: usize = valid_rings
        .iter()
        .map(|r: &&Vec<Vec3>| r.len())
        .max()
        .unwrap_or(3)
        .max(3);
    let mut rings: Vec<Vec<Vec3>> = Vec::with_capacity(valid_rings.len());
    for ring in valid_rings.iter() {
        rings.push(resample_ring_3d(ring.as_slice(), max_ring_len));
    }
    let (c0, n0): (Vec3, Vec3) = ring_centroid_and_normal(&rings[0]);
    let (c1, _): (Vec3, Vec3) = ring_centroid_and_normal(&rings[1]);
    let dir01: Vec3 = c1.sub(c0);
    if n0.dot(dir01) < 0.0 {
        rings[0].reverse();
    }
    for r_idx in 1..rings.len() {
        let prev_ring: &[Vec3] = &rings[r_idx - 1];
        let mut best_ring: Vec<Vec3> = rings[r_idx].clone();
        let mut best_dist: f32 = f32::INFINITY;
        for rev in [false, true] {
            let mut candidate: Vec<Vec3> = rings[r_idx].clone();
            if rev {
                candidate.reverse();
            }
            for shift in 0..max_ring_len {
                let mut dist_sum: f32 = 0.0;
                for k in 0..max_ring_len {
                    dist_sum += prev_ring[k]
                        .sub(candidate[(k + shift) % max_ring_len])
                        .length_sq();
                }
                if dist_sum < best_dist {
                    best_dist = dist_sum;
                    best_ring = (0..max_ring_len)
                        .map(|k: usize| candidate[(k + shift) % max_ring_len])
                        .collect();
                }
            }
        }
        rings[r_idx] = best_ring;
    }
    let ring_count: usize = rings.len();
    let is_closed: bool = closed && ring_count >= 3;
    let total_rings: usize = if is_closed {
        ring_count + 1
    } else {
        ring_count
    };
    let stride: usize = max_ring_len + 1;
    let mut vertices: Vec<Vertex3D> = Vec::with_capacity(total_rings * stride + max_ring_len * 2);
    let mut indices: Vec<[u32; 3]> =
        Vec::with_capacity((total_rings - 1) * max_ring_len * 2 + (max_ring_len - 2) * 2);
    for r in 0..total_rings {
        let ring: &[Vec3] = &rings[r % ring_count];
        let (centroid, _): (Vec3, Vec3) = ring_centroid_and_normal(ring);
        let v_uv: f32 = (r as f32) / ((total_rings - 1).max(1) as f32);
        for i in 0..=max_ring_len {
            let pt: Vec3 = ring[i % max_ring_len];
            let normal: Vec3 = safe_unit_normal(pt.sub(centroid));
            let u_uv: f32 = (i as f32) / (max_ring_len as f32);
            vertices.push(make_textured_vertex(pt, normal, [u_uv, v_uv]));
        }
    }
    for r in 0..(total_rings - 1) {
        let row0: u32 = (r * stride) as u32;
        let row1: u32 = ((r + 1) * stride) as u32;
        for i in 0..max_ring_len {
            let iu: u32 = i as u32;
            let v00: u32 = row0 + iu;
            let v10: u32 = row0 + iu + 1;
            let v01: u32 = row1 + iu;
            let v11: u32 = row1 + iu + 1;
            indices.push([v00, v10, v11]);
            indices.push([v00, v11, v01]);
        }
    }
    if !is_closed {
        let (c_first, n_first): (Vec3, Vec3) = ring_centroid_and_normal(&rings[0]);
        let (c_second, _): (Vec3, Vec3) = ring_centroid_and_normal(&rings[1]);
        let start_out: Vec3 = if n_first.dot(c_second.sub(c_first)) >= 0.0 {
            n_first.scale(-1.0)
        } else {
            n_first
        };
        append_ring_cap_3d(&rings[0], start_out, &mut vertices, &mut indices);
        let last_idx: usize = ring_count - 1;
        let (c_last, n_last): (Vec3, Vec3) = ring_centroid_and_normal(&rings[last_idx]);
        let (c_prev, _): (Vec3, Vec3) = ring_centroid_and_normal(&rings[last_idx - 1]);
        let end_out: Vec3 = if n_last.dot(c_last.sub(c_prev)) >= 0.0 {
            n_last
        } else {
            n_last.scale(-1.0)
        };
        append_ring_cap_3d(&rings[last_idx], end_out, &mut vertices, &mut indices);
    }
    let mut mesh: Mesh3D = Mesh3D::from_parts(
        SPLINE_NAME_LOFT.to_string(),
        vertices,
        indices,
        PbrMaterial::default(),
    );
    mesh.set_is_closed(true);
    let smoothed: Mesh3D = recompute_smooth_normals(&mesh);
    compute_tangents(&smoothed)
}