bevy_symbios_shape 0.7.0

Bevy integration for Symbios Shape.
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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
//! Procedural mesh generation for CGA shape terminals.
//!
//! Two entry points:
//!
//! - [`build_profiled_mesh`] dispatches on a terminal's [`FaceProfile`] and is
//!   what [`crate::spawner::SpawnShapeExt::spawn_shape`] calls when a terminal
//!   has no registered scene in [`crate::registry::ShapeRegistry`].
//! - [`build_tapered_cuboid`] is the lower-level 3-D builder used for the
//!   `Rectangle` and `Taper` profiles; the flat-face builders for
//!   `Triangle`, `Trapezoid` and `Polygon` are private but exercised through
//!   `build_profiled_mesh`.
//!
//! All meshes are emitted in *unit-mesh space* (`[-0.5, 0.5]` on each axis
//! with non-zero extents) and rely on the caller's `Transform::scale` —
//! provided by [`crate::transform::scope_to_transform`] — to stretch them to
//! the actual scope extents.

use bevy::asset::RenderAssetUsages;
use bevy::math::{DVec2, Vec2, Vec3};
use bevy::mesh::{Indices, Mesh, PrimitiveTopology, VertexAttributeValues};
use symbios_shape::FaceProfile;

/// Builds a tapered prism mesh from a unit cube that fits in a `(1, 1, 1)` bounding box.
///
/// The mesh is centered at the origin so that it can be placed via [`scope_to_transform`].
/// The caller's `Transform::scale` (from `scope_to_transform`) stretches the unit
/// geometry to fill the actual scope extents.
///
/// `taper` ∈ `[0.0, 1.0]`:
/// - `0.0`: box (all 4 top vertices at full width).
/// - `1.0`: pyramid (top 4 vertices collapse to a single apex).
/// - Intermediate: a frustum / tapered prism.
///
/// `size` is the world-space extent of the scope (`scope.size` cast to `f32`).
/// It is used **only** to scale UV coordinates so that one UV unit equals one world unit,
/// enabling texture tiling at a consistent texel density regardless of face dimensions.
///
/// Uses 24 vertices (4 per face) to allow per-face flat normals, with 36 indices.
///
/// ## UV layout
///
/// U always runs from the viewer's left edge (U=0) to the viewer's right edge (U=size),
/// where "viewer" means the camera looking at each face from outside.
///
/// | Face | U axis (viewer-left → viewer-right) | V axis |
/// |---|---|---|
/// | Bottom / Top | +X (0 … `size.x`) | +Z (0 … `size.z`) |
/// | Front (−Z) | +X→−X  (0 … `size.x`) | −Y (0=top … `size.y`=bottom) |
/// | Back (+Z) | −X→+X  (0 … `size.x`) | −Y (0=top … `size.y`=bottom) |
/// | Left (−X) | −Z→+Z  (0 … `size.z`) | −Y (0=top … `size.y`=bottom) |
/// | Right (+X) | +Z→−Z  (0 … `size.z`) | −Y (0=top … `size.y`=bottom) |
///
/// For tapered side faces the top-edge U range narrows proportionally to the taper factor.
///
/// [`scope_to_transform`]: crate::transform::scope_to_transform
pub fn build_tapered_cuboid(taper: f32, size: Vec3, stretch_uvs: bool) -> Mesh {
    let taper = taper.clamp(0.0, 1.0);

    // Unit box corners: X ∈ [-0.5, 0.5], Y ∈ [-0.5, 0.5], Z ∈ [-0.5, 0.5].
    // Taper shrinks the top four corners toward the Y-axis center (x=0, z=0).
    let shrink = taper * 0.5; // how much each top corner moves inward on X and Z

    // Bottom corners (y = -0.5), full width
    let b0 = Vec3::new(-0.5, -0.5, -0.5); // front-left
    let b1 = Vec3::new(0.5, -0.5, -0.5); // front-right
    let b2 = Vec3::new(0.5, -0.5, 0.5); // back-right
    let b3 = Vec3::new(-0.5, -0.5, 0.5); // back-left

    // Top corners (y = 0.5), tapered inward
    let t0 = Vec3::new(-0.5 + shrink, 0.5, -0.5 + shrink); // front-left
    let t1 = Vec3::new(0.5 - shrink, 0.5, -0.5 + shrink); // front-right
    let t2 = Vec3::new(0.5 - shrink, 0.5, 0.5 - shrink); // back-right
    let t3 = Vec3::new(-0.5 + shrink, 0.5, 0.5 - shrink); // back-left

    // Face normals (computed from face geometry, approximated as flat directions).
    // For a tapered prism the side normals tilt inward at the top; we compute them
    // from the actual face geometry using the cross product of two edge vectors.
    let normal_bottom = Vec3::NEG_Y;
    let normal_top = Vec3::Y;

    // Side face normals: computed from CCW vertex order (first triangle of each face).
    // face_normal(a, b, c, _) = (b-a) × (c-a), which points outward for CCW winding.
    let front_n = face_normal(b1, b0, t0, t1); // −Z (face at z = −0.5)
    let back_n = face_normal(b3, b2, t2, t3); // +Z (face at z = +0.5)
    let left_n = face_normal(b0, b3, t3, t0); // −X (face at x = −0.5)
    let right_n = face_normal(b2, b1, t1, t2); // +X (face at x = +0.5)

    // 24 vertices: 4 per face, 6 faces, CCW winding from outside.
    // Indices always use pattern [b, b+1, b+2, b, b+2, b+3] (two CCW triangles per quad).
    // Vertex order verified via cross product: (v1−v0) × (v2−v0) points outward for all faces.
    //   Bottom: (b1−b0)×(b2−b0) = (1,0,0)×(1,0,1) = (0,−1,0) = −Y ✓
    //   Top:    (t3−t0)×(t2−t0) = (0,0,1)×(1,0,1) = (0,+1,0) = +Y ✓
    //   Front:  (b0−b1)×(t0−b1) = (−1,0,0)×(−1,1,0) = (0,0,−1) = −Z ✓
    //   Back:   (b2−b3)×(t2−b3) = (1,0,0)×(1,1,0) = (0,0,+1) = +Z ✓
    //   Left:   (b3−b0)×(t3−b0) = (0,0,1)×(0,1,1) = (−1,0,0) = −X ✓
    //   Right:  (b1−b2)×(t1−b2) = (0,0,−1)×(0,1,−1) = (+1,0,0) = +X ✓
    #[rustfmt::skip]
    let positions: Vec<[f32; 3]> = vec![
        // Bottom (normal = −Y): CCW from below
        b0.to_array(), b1.to_array(), b2.to_array(), b3.to_array(),
        // Top (normal = +Y): CCW from above
        t0.to_array(), t3.to_array(), t2.to_array(), t1.to_array(),
        // Front (normal = −Z): CCW from outside (−Z side)
        b1.to_array(), b0.to_array(), t0.to_array(), t1.to_array(),
        // Back (normal = +Z): CCW from outside (+Z side)
        b3.to_array(), b2.to_array(), t2.to_array(), t3.to_array(),
        // Left (normal = −X): CCW from outside (−X side)
        b0.to_array(), b3.to_array(), t3.to_array(), t0.to_array(),
        // Right (normal = +X): CCW from outside (+X side)
        b2.to_array(), b1.to_array(), t1.to_array(), t2.to_array(),
    ];

    #[rustfmt::skip]
    let normals: Vec<[f32; 3]> = vec![
        // Bottom
        normal_bottom.to_array(), normal_bottom.to_array(),
        normal_bottom.to_array(), normal_bottom.to_array(),
        // Top
        normal_top.to_array(), normal_top.to_array(),
        normal_top.to_array(), normal_top.to_array(),
        // Front
        front_n.to_array(), front_n.to_array(), front_n.to_array(), front_n.to_array(),
        // Back
        back_n.to_array(), back_n.to_array(), back_n.to_array(), back_n.to_array(),
        // Left
        left_n.to_array(), left_n.to_array(), left_n.to_array(), left_n.to_array(),
        // Right
        right_n.to_array(), right_n.to_array(), right_n.to_array(), right_n.to_array(),
    ];

    // UV mapping: world-space texel density so 1 UV unit = 1 world unit.
    // U always runs viewer-left (U=0) → viewer-right (U=size) for each face.
    //   Bottom / Top  → U: +X (0…w),  V: +Z (0…d)
    //   Front (−Z)    → U: +X→−X (0…w), V: −Y (0=top … h=bottom)
    //   Back  (+Z)    → U: −X→+X (0…w), V: −Y (0=top … h=bottom)
    //   Left  (−X)    → U: −Z→+Z (0…d), V: −Y (0=top … h=bottom)
    //   Right (+X)    → U: +Z→−Z (0…d), V: −Y (0=top … h=bottom)
    // Tapered side faces: the top-edge U range narrows proportionally (by factor s).
    // UV mapping logic:
    let (w, h, d) = if stretch_uvs {
        (1.0, 1.0, 1.0)
    } else {
        (size.x, size.y, size.z)
    };
    let s = shrink;

    #[rustfmt::skip]
    let uvs: Vec<[f32; 2]> = vec![
        // Bottom  (b0, b1, b2, b3): U→X, V→Z
        [0.0, 0.0], [w,   0.0], [w,   d  ], [0.0, d  ],
        // Top     (t0, t3, t2, t1): U→X, V→Z
        [0.0, 0.0], [0.0, d  ], [w,   d  ], [w,   0.0],
        // Front   (b1, b0, t0, t1): U→viewer-left(+X)…viewer-right(−X); top narrows with taper
        // b1 is at +X (viewer-left), b0 at −X (viewer-right): U runs 0…w left-to-right.
        [0.0, h  ], [w,   h  ], [(1.0-s)*w, 0.0], [s*w, 0.0],
        // Back    (b3, b2, t2, t3): U→viewer-left(−X)…viewer-right(+X)
        // b3 at −X (viewer-left), b2 at +X (viewer-right): already correct, U runs 0…w.
        [0.0, h  ], [w,   h  ], [(1.0-s)*w, 0.0], [s*w, 0.0],
        // Left    (b0, b3, t3, t0): U→viewer-left(−Z)…viewer-right(+Z)
        // b0 at −Z (viewer-left), b3 at +Z (viewer-right): correct, U runs 0…d.
        [0.0, h  ], [d,   h  ], [(1.0-s)*d, 0.0], [s*d, 0.0],
        // Right   (b2, b1, t1, t2): U→viewer-left(+Z)…viewer-right(−Z)
        // b2 at +Z (viewer-left), b1 at −Z (viewer-right): U runs 0…d left-to-right.
        [0.0, h  ], [d,   h  ], [(1.0-s)*d, 0.0], [s*d, 0.0],
    ];

    // Build indices, omitting degenerate triangles for the fully-tapered (pyramid) case.
    //
    // At taper ≈ 1.0 the four top corners all collapse to a single apex point:
    //   - Top face (face 1): all four verts are identical → skip all 6 indices.
    //   - Side faces (2–5): verts 2 and 3 are both the apex → the second triangle
    //     [b, b+2, b+3] is degenerate (zero area). Emitting it causes mikktspace to
    //     produce NaN tangents on the *valid* triangle's shared apex vertex, which
    //     makes those faces invisible in the PBR shader. Skip the degenerate half.
    let is_pyramid = taper >= 1.0 - 1e-5;
    let mut indices: Vec<u32> = Vec::with_capacity(if is_pyramid { 18 } else { 36 });
    for face in 0u32..6 {
        let b = face * 4;
        match (is_pyramid, face) {
            (true, 1) => {}                                     // top face: completely degenerate
            (true, 2..=5) => indices.extend([b, b + 1, b + 2]), // side: only valid triangle
            _ => indices.extend([b, b + 1, b + 2, b, b + 2, b + 3]), // normal quad
        }
    }

    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    );
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
    mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
    mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
    mesh.insert_indices(Indices::U32(indices));
    // Generate tangents; fall back to a default if the generator fails or produces
    // NaN values (which can occur if any remaining triangle is near-degenerate).
    let tangents_ok = mesh.generate_tangents().is_ok_and(|_| {
        !matches!(
            mesh.attribute(Mesh::ATTRIBUTE_TANGENT),
            Some(VertexAttributeValues::Float32x4(t))
                if t.iter().any(|v| v.iter().any(|f| f.is_nan()))
        )
    });
    if !tangents_ok {
        mesh.insert_attribute(Mesh::ATTRIBUTE_TANGENT, vec![[1.0_f32, 0.0, 0.0, 1.0]; 24]);
    }
    mesh
}

/// Computes the outward-facing normal for a quad with vertices in CCW order
/// (when viewed from outside). Uses the cross product of two diagonals.
fn face_normal(a: Vec3, b: Vec3, c: Vec3, d: Vec3) -> Vec3 {
    let _ = d; // fourth vertex unused; normal from first triangle suffices
    (b - a).cross(c - a).normalize()
}

// ── Profiled-face builders ────────────────────────────────────────────────────

/// Selects between `build_tapered_cuboid` and the flat-face builders based on
/// the [`FaceProfile`] carried by a [`Terminal`].
///
/// Roof panel scopes have `size.z ≈ 0`; [`crate::transform::scope_to_transform`]
/// clamps Z scale to `1e-3`, so the "depth" of the generated mesh is negligible.
/// The meaningful geometry is the XY cross-section described by the profile.
///
/// [`Terminal`]: symbios_shape::Terminal
pub fn build_profiled_mesh(profile: &FaceProfile, size: Vec3, stretch_uvs: bool) -> Mesh {
    build_profiled_mesh_with(profile, size, stretch_uvs, 0)
}

/// [`build_profiled_mesh`] with an explicit cross-section mode.
///
/// `round_segments` selects how the *volume* profiles (`Rectangle` and
/// `Taper`) are realised:
///
/// - `0` — the default — emits the box / tapered-cuboid geometry.
/// - `>= 3` — emits an **elliptical prism** with that many radial segments,
///   inscribed in the scope's footprint: a cylinder for `Rectangle`, a
///   frustum for `Taper(t)`, and a cone at `Taper(1.0)`. A square footprint
///   gives a circular section; a rectangular one gives an ellipse.
///
/// Flat profiles (`Triangle`, `Trapezoid`, `Polygon` — roof panels and
/// stamped shapes) have no cross-section to round and ignore the parameter.
///
/// Roundness is a *rendering* choice, opted into per asset ID via
/// [`ShapeRegistry::register_round_mesh`] / [`register_round_material`]:
/// the grammar's scopes stay axis-aligned boxes, so splits, occlusion, and
/// mass properties are unaffected.
///
/// [`ShapeRegistry::register_round_mesh`]: crate::registry::ShapeRegistry::register_round_mesh
/// [`register_round_material`]: crate::registry::ShapeRegistry::register_round_material
pub fn build_profiled_mesh_with(
    profile: &FaceProfile,
    size: Vec3,
    stretch_uvs: bool,
    round_segments: u32,
) -> Mesh {
    if round_segments >= 3 {
        match profile {
            FaceProfile::Rectangle => {
                return build_round_prism(0.0, size, stretch_uvs, round_segments);
            }
            FaceProfile::Taper(t) => {
                return build_round_prism(*t as f32, size, stretch_uvs, round_segments);
            }
            // Flat profiles have no cross-section to round.
            _ => {}
        }
    }
    match profile {
        FaceProfile::Rectangle => build_tapered_cuboid(0.0, size, stretch_uvs),
        FaceProfile::Taper(t) => build_tapered_cuboid(*t as f32, size, stretch_uvs),
        FaceProfile::Triangle { peak_offset } => {
            build_triangle_face(*peak_offset as f32, size, stretch_uvs)
        }
        FaceProfile::Trapezoid {
            top_width,
            offset_x,
        } => build_trapezoid_face(*top_width as f32, *offset_x as f32, size, stretch_uvs),
        FaceProfile::Polygon(pts) => build_polygon_face(pts, size, stretch_uvs),
    }
}

/// Builds an elliptical prism (cylinder / frustum / cone) inscribed in the
/// scope's box, in unit-mesh space `[-0.5, 0.5]`.
///
/// `taper` ∈ `[0, 1]` shrinks the top ring toward the axis: `0.0` is a
/// straight cylinder, `1.0` collapses it to an apex (a cone). `segments` is
/// the radial tessellation, clamped to `[3, 256]`.
///
/// ## UV layout
///
/// Matching the cuboid convention, one UV unit is one world unit unless
/// `stretch_uvs` is set:
/// - Side: `U` runs around the circumference (arc length in metres, using
///   Ramanujan's ellipse-perimeter approximation), `V` runs `0` at the top
///   to `size.y` at the bottom.
/// - Caps: planar `(x, z)` in metres, centred on the axis.
///
/// The seam vertex is duplicated so `U` can reach the full perimeter
/// without wrapping to zero mid-triangle.
fn build_round_prism(taper: f32, size: Vec3, stretch_uvs: bool, segments: u32) -> Mesh {
    use std::f32::consts::TAU;

    let taper = taper.clamp(0.0, 1.0);
    let segments = segments.clamp(3, 256);
    let top_scale = 1.0 - taper;
    let apex = top_scale <= 1e-6;

    // Radii in unit space; world extents arrive via Transform::scale.
    let r = 0.5_f32;
    let (rx_world, rz_world) = (size.x.abs() * 0.5, size.z.abs() * 0.5);

    // Ramanujan's approximation of an ellipse perimeter — the U span that
    // keeps texel density matching flat walls.
    let perimeter = {
        let (a, b) = (rx_world, rz_world);
        if a <= 0.0 && b <= 0.0 {
            0.0
        } else {
            let h = ((a - b) * (a - b)) / ((a + b) * (a + b)).max(1e-12);
            std::f32::consts::PI * (a + b) * (1.0 + (3.0 * h) / (10.0 + (4.0 - 3.0 * h).sqrt()))
        }
    };
    let (u_span, v_span) = if stretch_uvs {
        (1.0, 1.0)
    } else {
        (perimeter, size.y.abs())
    };

    let mut positions: Vec<[f32; 3]> = Vec::new();
    let mut normals: Vec<[f32; 3]> = Vec::new();
    let mut uvs: Vec<[f32; 2]> = Vec::new();
    let mut tangents: Vec<[f32; 4]> = Vec::new();
    let mut indices: Vec<u32> = Vec::new();

    // ── Side wall ────────────────────────────────────────────────────────
    // Slope of the silhouette in unit space, used to tilt the normals up.
    let slope_y = r * taper; // horizontal run from bottom ring to top ring
    let side_base = 0;
    for i in 0..=segments {
        let f = i as f32 / segments as f32;
        let ang = f * TAU;
        let (sin_a, cos_a) = ang.sin_cos();

        let bx = r * cos_a;
        let bz = r * sin_a;
        let tx = bx * top_scale;
        let tz = bz * top_scale;

        // Outward normal: perpendicular to the circumferential tangent and
        // to the slope direction. For a cone this tilts upward by the taper.
        let n = Vec3::new(cos_a, slope_y, sin_a).normalize_or_zero();
        let n = if n.length_squared() < 1e-12 {
            Vec3::new(cos_a, 0.0, sin_a)
        } else {
            n
        };
        // Circumferential tangent (direction of increasing U).
        let t = Vec3::new(-sin_a, 0.0, cos_a);

        // Bottom then top, so quads index in pairs.
        positions.push([bx, -0.5, bz]);
        normals.push(n.into());
        uvs.push([f * u_span, v_span]);
        tangents.push([t.x, t.y, t.z, 1.0]);

        positions.push([tx, 0.5, tz]);
        normals.push(n.into());
        uvs.push([f * u_span, 0.0]);
        tangents.push([t.x, t.y, t.z, 1.0]);
    }
    for i in 0..segments {
        let b0 = side_base + i * 2;
        let t0 = b0 + 1;
        let b1 = b0 + 2;
        let t1 = b0 + 3;
        // Counter-clockwise seen from OUTSIDE the shell, so the winding
        // agrees with the outward normals above. Reversing these two lines
        // renders the prism inside-out under backface culling.
        if apex {
            // Degenerate top ring — one triangle per segment.
            indices.extend_from_slice(&[b0, t0, b1]);
        } else {
            indices.extend_from_slice(&[b0, t1, b1, b0, t0, t1]);
        }
    }

    // ── Caps ─────────────────────────────────────────────────────────────
    let mut push_cap = |y: f32, scale: f32, up: bool| {
        if scale <= 1e-6 {
            return;
        }
        let base = positions.len() as u32;
        let n = if up { 1.0_f32 } else { -1.0 };
        // Centre vertex, then the ring.
        positions.push([0.0, y, 0.0]);
        normals.push([0.0, n, 0.0]);
        uvs.push([0.0, 0.0]);
        tangents.push([1.0, 0.0, 0.0, 1.0]);
        for i in 0..=segments {
            let ang = (i as f32 / segments as f32) * TAU;
            let (sin_a, cos_a) = ang.sin_cos();
            let (x, z) = (r * cos_a * scale, r * sin_a * scale);
            positions.push([x, y, z]);
            normals.push([0.0, n, 0.0]);
            uvs.push(if stretch_uvs {
                [0.5 + cos_a * 0.5 * scale, 0.5 + sin_a * 0.5 * scale]
            } else {
                [cos_a * rx_world * scale, sin_a * rz_world * scale]
            });
            tangents.push([1.0, 0.0, 0.0, 1.0]);
        }
        for i in 0..segments {
            let a = base + 1 + i;
            let b = base + 2 + i;
            // Wind counter-clockwise as seen from the side the cap faces:
            // from above for the top, from below for the bottom.
            if up {
                indices.extend_from_slice(&[base, b, a]);
            } else {
                indices.extend_from_slice(&[base, a, b]);
            }
        }
    };
    push_cap(-0.5, 1.0, false);
    push_cap(0.5, top_scale, true);

    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    );
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
    mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
    mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
    mesh.insert_attribute(Mesh::ATTRIBUTE_TANGENT, tangents);
    mesh.insert_indices(Indices::U32(indices));
    mesh
}

/// Builds a flat triangular face for a scope lying in the XY plane (`size.z ≈ 0`).
///
/// ## Coordinate convention
///
/// Unit-mesh space `[-0.5, 0.5]²`, matching `build_tapered_cuboid`:
/// - V0 = (−0.5, −0.5) — left eave corner
/// - V1 = (+0.5, −0.5) — right eave corner
/// - V2 = (`peak_offset` − 0.5, +0.5) — apex
///
/// ## UV mapping
///
/// Consistent with `build_tapered_cuboid` side faces:
/// U = 0…`size.x` left-to-right, V = 0 at the apex, V = `size.y` at the eave.
///
/// Both a front (+Z normal) and back (−Z normal) face are emitted.
fn build_triangle_face(peak_offset: f32, size: Vec3, stretch_uvs: bool) -> Mesh {
    let peak_offset = peak_offset.clamp(0.0, 1.0);
    let (w, h) = if stretch_uvs {
        (1.0, 1.0)
    } else {
        (size.x, size.y)
    };

    let v0 = [-0.5_f32, -0.5, 0.0];
    let v1 = [0.5_f32, -0.5, 0.0];
    let v2 = [peak_offset - 0.5, 0.5, 0.0];

    // Front (CCW from +Z, normal = +Z), Back (CCW from −Z, normal = −Z)
    let positions: Vec<[f32; 3]> = vec![v0, v1, v2, v0, v1, v2];

    let nf = [0.0_f32, 0.0, 1.0];
    let nb = [0.0_f32, 0.0, -1.0];
    let normals: Vec<[f32; 3]> = vec![nf, nf, nf, nb, nb, nb];

    let u0 = [0.0, h];
    let u1 = [w, h];
    let u2 = [peak_offset * w, 0.0_f32];
    let uvs: Vec<[f32; 2]> = vec![u0, u1, u2, u0, u1, u2];

    // Front: 0→1→2 (CCW from +Z).  Back: 3→5→4 (CCW from −Z).
    let indices: Vec<u32> = vec![0, 1, 2, 3, 5, 4];

    // For a flat XY face with U→+X and V decreasing toward +Y:
    //   front tangent (N=+Z): T=(1,0,0), B=cross(N,T)=(0,1,0), sign=+1 so B=(0,-1,0)
    //   handedness sign: dot(cross(N,T), B_tex) = dot((0,1,0),(0,-1,0)) = -1 → w=-1
    //   back  tangent  (N=−Z): cross(N,T)=(0,-1,0), B_tex=(0,-1,0) → w=+1
    let tangents: Vec<[f32; 4]> = vec![
        [1.0, 0.0, 0.0, -1.0],
        [1.0, 0.0, 0.0, -1.0],
        [1.0, 0.0, 0.0, -1.0],
        [1.0, 0.0, 0.0, 1.0],
        [1.0, 0.0, 0.0, 1.0],
        [1.0, 0.0, 0.0, 1.0],
    ];

    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    );
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
    mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
    mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
    mesh.insert_attribute(Mesh::ATTRIBUTE_TANGENT, tangents);
    mesh.insert_indices(Indices::U32(indices));
    mesh
}

/// Builds a flat trapezoidal face for a scope lying in the XY plane (`size.z ≈ 0`).
///
/// Used for Hip-roof front/back slopes where the ridge is shorter than the eave.
///
/// ## Parameters (normalised to `[0, 1]` of scope width)
///
/// - `top_width`: fraction of the bottom edge width occupied by the top edge.
/// - `offset_x`: left-side indent of the top edge (0 = flush-left).
///
/// ## Vertex layout in unit `[-0.5, 0.5]²` space
///
/// ```text
///  V3─────────────V2          ← Y = +0.5 (ridge)
///  V0─────────────────────V1  ← Y = −0.5 (eave)
/// ```
fn build_trapezoid_face(top_width: f32, offset_x: f32, size: Vec3, stretch_uvs: bool) -> Mesh {
    let top_width = top_width.clamp(0.0, 1.0);
    let offset_x = offset_x.clamp(0.0, (1.0 - top_width).max(0.0));

    let (w, h) = if stretch_uvs {
        (1.0, 1.0)
    } else {
        (size.x, size.y)
    };

    let v0 = [-0.5_f32, -0.5, 0.0]; // bottom-left eave
    let v1 = [0.5_f32, -0.5, 0.0]; // bottom-right eave
    let v2 = [offset_x + top_width - 0.5, 0.5, 0.0]; // top-right ridge
    let v3 = [offset_x - 0.5, 0.5, 0.0]; // top-left ridge

    let positions: Vec<[f32; 3]> = vec![v0, v1, v2, v3, v0, v1, v2, v3];

    let nf = [0.0_f32, 0.0, 1.0];
    let nb = [0.0_f32, 0.0, -1.0];
    let normals: Vec<[f32; 3]> = vec![nf, nf, nf, nf, nb, nb, nb, nb];

    let uv0 = [0.0, h];
    let uv1 = [w, h];
    let uv2 = [(offset_x + top_width) * w, 0.0_f32];
    let uv3 = [offset_x * w, 0.0_f32];
    let uvs: Vec<[f32; 2]> = vec![uv0, uv1, uv2, uv3, uv0, uv1, uv2, uv3];

    // Front: [0,1,2, 0,2,3]  Back (reversed): [4,6,5, 4,7,6]
    let indices: Vec<u32> = vec![0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6];

    let tangents: Vec<[f32; 4]> = vec![[1.0, 0.0, 0.0, -1.0]; 4]
        .into_iter()
        .chain(vec![[1.0_f32, 0.0, 0.0, 1.0]; 4])
        .collect();

    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    );
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
    mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
    mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
    mesh.insert_attribute(Mesh::ATTRIBUTE_TANGENT, tangents);
    mesh.insert_indices(Indices::U32(indices));
    mesh
}

/// Builds a flat polygon face from a list of 2-D points in normalised scope
/// coordinates (`[0,1]²`) using ear-clipping triangulation.
///
/// Input `pts` uses double-precision scope coordinates:
/// - X: 0 = left eave edge, 1 = right eave edge
/// - Y: 0 = bottom (eave), 1 = top (ridge)
///
/// The polygon must be simple (no self-intersections). Both a front (+Z) and
/// back (−Z) face are generated. Falls back to `build_tapered_cuboid(0.0, …)`
/// if the polygon has fewer than 3 points or ear-clipping produces no triangles.
fn build_polygon_face(pts: &[DVec2], size: Vec3, stretch_uvs: bool) -> Mesh {
    if pts.len() < 3 {
        return build_tapered_cuboid(0.0, size, stretch_uvs);
    }

    let (w, h) = if stretch_uvs {
        (1.0, 1.0)
    } else {
        (size.x, size.y)
    };

    // Convert to f32 scope coords and unit-mesh coords.
    let scope_pts: Vec<Vec2> = pts
        .iter()
        .map(|p| Vec2::new(p.x as f32, p.y as f32))
        .collect();

    // Ensure CCW winding (required by ear-clipper).
    let area: f32 = (0..scope_pts.len())
        .map(|i| {
            let j = (i + 1) % scope_pts.len();
            scope_pts[i].x * scope_pts[j].y - scope_pts[j].x * scope_pts[i].y
        })
        .sum::<f32>()
        * 0.5;

    let pts_ccw: Vec<Vec2> = if area < 0.0 {
        scope_pts.iter().rev().cloned().collect()
    } else {
        scope_pts.clone()
    };

    let tris = ear_clip(&pts_ccw);
    if tris.is_empty() {
        return build_tapered_cuboid(0.0, size, stretch_uvs);
    }

    let n = pts_ccw.len() as u32;

    // Front positions (Z=0, normal=+Z) then back (same XY, normal=−Z).
    let positions: Vec<[f32; 3]> = pts_ccw
        .iter()
        .chain(pts_ccw.iter())
        .map(|p| [p.x - 0.5, p.y - 0.5, 0.0])
        .collect();

    let nf = [0.0_f32, 0.0, 1.0];
    let nb = [0.0_f32, 0.0, -1.0];
    let normals: Vec<[f32; 3]> = (0..n as usize)
        .map(|_| nf)
        .chain((0..n as usize).map(|_| nb))
        .collect();

    // UV: U = scope_x * w, V = (1 - scope_y) * h  (V=0 at ridge, V=h at eave)
    let uvs: Vec<[f32; 2]> = pts_ccw
        .iter()
        .chain(pts_ccw.iter())
        .map(|p| [p.x * w, (1.0 - p.y) * h])
        .collect();

    let tangents: Vec<[f32; 4]> = (0..n as usize)
        .map(|_| [1.0_f32, 0.0, 0.0, -1.0])
        .chain((0..n as usize).map(|_| [1.0_f32, 0.0, 0.0, 1.0]))
        .collect();

    // Front indices, then back indices (vertices offset by n, winding reversed).
    let indices: Vec<u32> = tris
        .iter()
        .flat_map(|&[a, b, c]| [a, b, c])
        .chain(tris.iter().flat_map(|&[a, b, c]| [a + n, c + n, b + n]))
        .collect();

    let mut mesh = Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    );
    mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
    mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
    mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
    mesh.insert_attribute(Mesh::ATTRIBUTE_TANGENT, tangents);
    mesh.insert_indices(Indices::U32(indices));
    mesh
}

// ── Ear-clipping triangulator ─────────────────────────────────────────────────

/// O(n²) ear-clipping triangulator for simple (non-self-intersecting) polygons.
///
/// Expects vertices in **CCW** winding order. Returns triangles as `[i0, i1, i2]`
/// index triples into the original vertex slice, in CCW order.
fn ear_clip(verts: &[Vec2]) -> Vec<[u32; 3]> {
    let n = verts.len();
    if n < 3 {
        return vec![];
    }
    if n == 3 {
        return vec![[0, 1, 2]];
    }

    let mut active: Vec<usize> = (0..n).collect();
    let mut tris: Vec<[u32; 3]> = Vec::with_capacity(n - 2);
    let mut safety = n * n + n; // prevent infinite loop on degenerate input

    while active.len() > 3 && safety > 0 {
        safety -= 1;
        let m = active.len();
        let mut clipped = false;
        for i in 0..m {
            let (ia, ib, ic) = (active[(i + m - 1) % m], active[i], active[(i + 1) % m]);
            let (a, b, c) = (verts[ia], verts[ib], verts[ic]);
            // Skip reflex (right-turning) vertices — they cannot be ears.
            if cross2(b - a, c - b) <= 0.0 {
                continue;
            }
            // An ear is valid only if no other active vertex lies strictly inside abc.
            let is_ear = !active
                .iter()
                .any(|&j| j != ia && j != ib && j != ic && point_in_tri(verts[j], a, b, c));
            if !is_ear {
                continue;
            }
            tris.push([ia as u32, ib as u32, ic as u32]);
            active.remove(i);
            clipped = true;
            break;
        }
        if !clipped {
            break; // degenerate polygon — stop rather than loop forever
        }
    }

    if active.len() == 3 {
        tris.push([active[0] as u32, active[1] as u32, active[2] as u32]);
    }
    tris
}

/// 2-D cross product (signed area of parallelogram).
#[inline]
fn cross2(a: Vec2, b: Vec2) -> f32 {
    a.x * b.y - a.y * b.x
}

/// Returns `true` if `p` is strictly inside triangle `(a, b, c)` (CCW winding).
#[inline]
fn point_in_tri(p: Vec2, a: Vec2, b: Vec2, c: Vec2) -> bool {
    cross2(b - a, p - a) > 0.0 && cross2(c - b, p - b) > 0.0 && cross2(a - c, p - c) > 0.0
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── Round cross-sections (0.6) ───────────────────────────────────────

    fn positions_of(mesh: &Mesh) -> Vec<[f32; 3]> {
        match mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap() {
            VertexAttributeValues::Float32x3(v) => v.clone(),
            _ => panic!("expected Float32x3 positions"),
        }
    }

    fn uvs_of(mesh: &Mesh) -> Vec<[f32; 2]> {
        match mesh.attribute(Mesh::ATTRIBUTE_UV_0).unwrap() {
            VertexAttributeValues::Float32x2(v) => v.clone(),
            _ => panic!("expected Float32x2 uvs"),
        }
    }

    /// Every triangle's winding must agree with the vertex normals it
    /// carries: `cross(v1 - v0, v2 - v0)` has to point the same way as the
    /// face's normal. When it doesn't, backface culling hides the near
    /// wall and the solid renders inside-out — the failure that shipped in
    /// 0.6.0 with all four face groups (side, apex, both caps) reversed.
    fn assert_winding_matches_normals(mesh: &Mesh, what: &str) {
        let pos = positions_of(mesh);
        let normals = match mesh.attribute(Mesh::ATTRIBUTE_NORMAL).unwrap() {
            VertexAttributeValues::Float32x3(v) => v.clone(),
            _ => panic!("expected Float32x3 normals"),
        };
        let Some(Indices::U32(idx)) = mesh.indices() else {
            panic!("expected U32 indices");
        };
        for tri in idx.chunks_exact(3) {
            let (a, b, c) = (
                Vec3::from(pos[tri[0] as usize]),
                Vec3::from(pos[tri[1] as usize]),
                Vec3::from(pos[tri[2] as usize]),
            );
            let geometric = (b - a).cross(c - a);
            if geometric.length_squared() < 1e-12 {
                continue; // degenerate sliver (e.g. at a cone apex)
            }
            // Average the three vertex normals — on a curved wall they
            // differ slightly, but never by enough to flip the sign.
            let shaded = (Vec3::from(normals[tri[0] as usize])
                + Vec3::from(normals[tri[1] as usize])
                + Vec3::from(normals[tri[2] as usize]))
                / 3.0;
            assert!(
                geometric.normalize().dot(shaded.normalize()) > 0.0,
                "{what}: triangle {tri:?} is wound against its normal \
                 (geometric {geometric:?}, shaded {shaded:?}) — the solid \
                 will render inside-out",
            );
        }
    }

    #[test]
    fn round_prism_winding_faces_outward() {
        for (taper, what) in [(0.0_f32, "cylinder"), (0.35, "frustum"), (1.0, "cone")] {
            let mesh = build_round_prism(taper, Vec3::new(2.0, 5.0, 1.2), false, 16);
            assert_winding_matches_normals(&mesh, what);
        }
    }

    #[test]
    fn cuboid_winding_faces_outward() {
        // The pre-existing builders share the invariant; pinning them here
        // means the check guards every solid the mesher can emit.
        for taper in [0.0_f32, 0.5, 1.0] {
            let mesh = build_tapered_cuboid(taper, Vec3::new(2.0, 3.0, 1.0), false);
            assert_winding_matches_normals(&mesh, "cuboid");
        }
    }

    #[test]
    fn round_prism_fits_the_unit_footprint() {
        let mesh = build_round_prism(0.0, Vec3::new(2.0, 5.0, 2.0), false, 24);
        for p in positions_of(&mesh) {
            // Inscribed in the unit box, and the ring is a true circle in
            // unit space (the transform's scale makes it an ellipse).
            assert!(p[0].abs() <= 0.5 + 1e-5 && p[2].abs() <= 0.5 + 1e-5);
            assert!(p[1].abs() <= 0.5 + 1e-5);
            let r = (p[0] * p[0] + p[2] * p[2]).sqrt();
            assert!(r <= 0.5 + 1e-5, "vertex outside the inscribed circle: {r}");
        }
    }

    #[test]
    fn round_prism_segment_count_drives_tessellation() {
        let coarse = positions_of(&build_round_prism(0.0, Vec3::ONE, false, 8));
        let fine = positions_of(&build_round_prism(0.0, Vec3::ONE, false, 64));
        assert!(
            fine.len() > coarse.len() * 4,
            "more segments must mean more vertices ({} vs {})",
            fine.len(),
            coarse.len()
        );
        // Side ring is (segments + 1) seam-duplicated pairs, plus two caps
        // of (1 centre + segments + 1 ring) each.
        let seg = 8_usize;
        assert_eq!(coarse.len(), (seg + 1) * 2 + 2 * (seg + 2));
    }

    #[test]
    fn cone_collapses_the_top_ring_and_drops_the_top_cap() {
        let cyl = positions_of(&build_round_prism(0.0, Vec3::ONE, false, 16));
        let cone = positions_of(&build_round_prism(1.0, Vec3::ONE, false, 16));
        // The apex has no top cap, so a cone has fewer vertices.
        assert!(cone.len() < cyl.len());
        // Every top-ring vertex sits on the axis.
        for p in cone.iter().filter(|p| p[1] > 0.49) {
            let r = (p[0] * p[0] + p[2] * p[2]).sqrt();
            assert!(r < 1e-5, "cone apex is not on the axis: r={r}");
        }
    }

    #[test]
    fn frustum_top_radius_follows_taper() {
        let mesh = build_round_prism(0.5, Vec3::ONE, false, 16);
        let top_r = positions_of(&mesh)
            .iter()
            .filter(|p| p[1] > 0.49)
            .map(|p| (p[0] * p[0] + p[2] * p[2]).sqrt())
            .fold(0.0_f32, f32::max);
        // taper 0.5 → top scale 0.5 → radius 0.25 in unit space.
        assert!((top_r - 0.25).abs() < 1e-5, "top radius {top_r} != 0.25");
    }

    #[test]
    fn round_uvs_tile_in_world_space_and_stretch_on_demand() {
        // A 2 x 5 x 2 scope: circumference of a radius-1 circle is TAU.
        let tiled = uvs_of(&build_round_prism(0.0, Vec3::new(2.0, 5.0, 2.0), false, 32));
        let max_u = tiled.iter().map(|uv| uv[0]).fold(0.0_f32, f32::max);
        let max_v = tiled.iter().map(|uv| uv[1]).fold(0.0_f32, f32::max);
        assert!(
            (max_u - std::f32::consts::TAU).abs() < 0.05,
            "U should span the circumference in metres, got {max_u}"
        );
        assert!(
            (max_v - 5.0).abs() < 1e-4,
            "V should span the height in metres, got {max_v}"
        );

        let stretched = uvs_of(&build_round_prism(0.0, Vec3::new(2.0, 5.0, 2.0), true, 32));
        let s_max_u = stretched.iter().map(|uv| uv[0]).fold(0.0_f32, f32::max);
        let s_max_v = stretched.iter().map(|uv| uv[1]).fold(0.0_f32, f32::max);
        assert!((s_max_u - 1.0).abs() < 1e-5, "stretched U spans 0..1");
        assert!((s_max_v - 1.0).abs() < 1e-5, "stretched V spans 0..1");
    }

    #[test]
    fn round_prism_indices_reference_real_vertices() {
        for taper in [0.0_f32, 0.5, 1.0] {
            let mesh = build_round_prism(taper, Vec3::ONE, false, 12);
            let n = positions_of(&mesh).len() as u32;
            let Some(Indices::U32(idx)) = mesh.indices() else {
                panic!("expected U32 indices");
            };
            assert!(!idx.is_empty());
            assert_eq!(idx.len() % 3, 0, "index count must be a multiple of 3");
            assert!(
                idx.iter().all(|i| *i < n),
                "taper {taper}: index out of range (n={n})"
            );
        }
    }

    #[test]
    fn build_profiled_mesh_with_routes_round_only_for_volume_profiles() {
        let boxed = positions_of(&build_profiled_mesh_with(
            &FaceProfile::Rectangle,
            Vec3::ONE,
            false,
            0,
        ));
        let round = positions_of(&build_profiled_mesh_with(
            &FaceProfile::Rectangle,
            Vec3::ONE,
            false,
            24,
        ));
        assert_eq!(boxed.len(), 24, "0 segments keeps the cuboid");
        assert!(round.len() > 24, "round path must tessellate");

        // Flat profiles ignore roundness — a roof panel stays a panel.
        let flat_boxed = positions_of(&build_profiled_mesh_with(
            &FaceProfile::Triangle { peak_offset: 0.5 },
            Vec3::ONE,
            false,
            0,
        ));
        let flat_round = positions_of(&build_profiled_mesh_with(
            &FaceProfile::Triangle { peak_offset: 0.5 },
            Vec3::ONE,
            false,
            24,
        ));
        assert_eq!(flat_boxed, flat_round);

        // Segment counts below 3 degrade to the box path.
        let degenerate = positions_of(&build_profiled_mesh_with(
            &FaceProfile::Rectangle,
            Vec3::ONE,
            false,
            2,
        ));
        assert_eq!(degenerate.len(), 24);
    }

    #[test]
    fn box_has_correct_vertex_count() {
        let mesh = build_tapered_cuboid(0.0, Vec3::ONE, false);
        let positions = mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap();
        assert_eq!(positions.len(), 24);
    }

    #[test]
    fn box_has_correct_index_count() {
        let mesh = build_tapered_cuboid(0.0, Vec3::ONE, false);
        if let Some(Indices::U32(idx)) = mesh.indices() {
            assert_eq!(idx.len(), 36);
        } else {
            panic!("expected U32 indices");
        }
    }

    #[test]
    fn pyramid_has_same_structure() {
        let mesh = build_tapered_cuboid(1.0, Vec3::ONE, false);
        let positions = mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap();
        assert_eq!(positions.len(), 24);
    }

    /// Verify every triangle's winding produces an outward-facing normal by checking
    /// the sign of its dot product with the stored per-face normal attribute.
    #[test]
    fn winding_is_ccw_from_outside() {
        for taper in [0.0f32, 0.5, 1.0] {
            let mesh = build_tapered_cuboid(taper, Vec3::ONE, false);

            let positions = match mesh.attribute(Mesh::ATTRIBUTE_POSITION) {
                Some(bevy::mesh::VertexAttributeValues::Float32x3(p)) => p,
                _ => panic!("expected Float32x3 positions"),
            };
            let normals = match mesh.attribute(Mesh::ATTRIBUTE_NORMAL) {
                Some(bevy::mesh::VertexAttributeValues::Float32x3(n)) => n,
                _ => panic!("expected Float32x3 normals"),
            };
            let indices = match mesh.indices() {
                Some(Indices::U32(idx)) => idx.clone(),
                _ => panic!("expected U32 indices"),
            };

            for tri in indices.chunks(3) {
                let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize);
                let p0 = Vec3::from(positions[i0]);
                let p1 = Vec3::from(positions[i1]);
                let p2 = Vec3::from(positions[i2]);
                let face_n = Vec3::from(normals[i0]); // all 4 verts of a face share the same normal
                let computed = (p1 - p0).cross(p2 - p0);
                // Skip degenerate triangles (e.g. taper=1 collapses the top face to a point).
                if computed.length_squared() < 1e-10 {
                    continue;
                }
                assert!(
                    computed.dot(face_n) > 0.0,
                    "CW winding at taper={taper}: tri ({i0},{i1},{i2}), \
                     computed={computed:?}, stored={face_n:?}"
                );
            }
        }
    }

    /// Verify that side-face UVs use U=0 at one edge and U=size at the other,
    /// and that V=0 is at the top and V=size.y at the bottom.
    /// Also checks that the top face maps U→X and V→Z (not the old rotated mapping).
    #[test]
    fn uvs_have_correct_orientation_and_scale() {
        let size = Vec3::new(4.0, 3.0, 2.0); // w=4, h=3, d=2
        let mesh = build_tapered_cuboid(0.0, size, false);

        let uvs = match mesh.attribute(Mesh::ATTRIBUTE_UV_0) {
            Some(bevy::mesh::VertexAttributeValues::Float32x2(u)) => u.clone(),
            _ => panic!("expected Float32x2 UVs"),
        };

        // Face vertex layout (4 verts per face, 6 faces):
        //   0..4  bottom, 4..8 top, 8..12 front, 12..16 back, 16..20 left, 20..24 right

        // Bottom face (b0,b1,b2,b3): U→X (0…w), V→Z (0…d)
        assert_eq!(uvs[0], [0.0, 0.0], "bottom b0");
        assert_eq!(uvs[1], [4.0, 0.0], "bottom b1");
        assert_eq!(uvs[2], [4.0, 2.0], "bottom b2");
        assert_eq!(uvs[3], [0.0, 2.0], "bottom b3");

        // Top face (t0,t3,t2,t1): U→X (0…w), V→Z (0…d)
        assert_eq!(uvs[4], [0.0, 0.0], "top t0 front-left");
        assert_eq!(uvs[5], [0.0, 2.0], "top t3 back-left");
        assert_eq!(uvs[6], [4.0, 2.0], "top t2 back-right");
        assert_eq!(uvs[7], [4.0, 0.0], "top t1 front-right");

        // Front face (b1,b0,t0,t1): camera looks in +Z so right=−X.
        // Viewer-left=b1(+X), viewer-right=b0(−X): U runs 0…w left-to-right.
        assert_eq!(uvs[8], [0.0, 3.0], "front b1 viewer-left-bottom");
        assert_eq!(uvs[9], [4.0, 3.0], "front b0 viewer-right-bottom");
        assert_eq!(uvs[10], [4.0, 0.0], "front t0 viewer-right-top (taper=0)");
        assert_eq!(uvs[11], [0.0, 0.0], "front t1 viewer-left-top (taper=0)");

        // Left face (b0,b3,t3,t0): U→Z, V: h=bottom, 0=top
        assert_eq!(uvs[16], [0.0, 3.0], "left b0 front-bottom");
        assert_eq!(uvs[17], [2.0, 3.0], "left b3 back-bottom");
        assert_eq!(uvs[18], [2.0, 0.0], "left t3 back-top (taper=0)");
        assert_eq!(uvs[19], [0.0, 0.0], "left t0 front-top (taper=0)");
    }

    #[test]
    fn tapered_side_face_uvs_narrow_at_top() {
        let size = Vec3::new(4.0, 3.0, 2.0);
        let mesh = build_tapered_cuboid(1.0, size, false); // full pyramid: shrink=0.5

        let uvs = match mesh.attribute(Mesh::ATTRIBUTE_UV_0) {
            Some(bevy::mesh::VertexAttributeValues::Float32x2(u)) => u.clone(),
            _ => panic!("expected Float32x2 UVs"),
        };

        // Front face top verts collapse to centre (s=0.5): U ∈ [s*w, (1-s)*w] = [2, 2]
        let front_t0_u = uvs[10][0];
        let front_t1_u = uvs[11][0];
        assert!(
            (front_t0_u - 2.0).abs() < 1e-5,
            "front top-left U should be 2.0, got {front_t0_u}"
        );
        assert!(
            (front_t1_u - 2.0).abs() < 1e-5,
            "front top-right U should be 2.0, got {front_t1_u}"
        );
    }

    #[test]
    fn normals_are_unit_length() {
        let mesh = build_tapered_cuboid(0.5, Vec3::ONE, false);
        if let Some(bevy::mesh::VertexAttributeValues::Float32x3(normals)) =
            mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
        {
            for n in normals {
                let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
                assert!((len - 1.0).abs() < 1e-5, "non-unit normal: {:?}", n);
            }
        } else {
            panic!("expected Float32x3 normals");
        }
    }

    // ── build_triangle_face ──────────────────────────────────────────────────

    #[test]
    fn triangle_face_vertex_count() {
        let mesh = build_triangle_face(0.5, Vec3::new(4.0, 3.0, 0.0), false);
        let pos = mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap();
        assert_eq!(pos.len(), 6, "expected 3 front + 3 back verts");
    }

    #[test]
    fn triangle_face_index_count() {
        let mesh = build_triangle_face(0.5, Vec3::new(4.0, 3.0, 0.0), false);
        if let Some(Indices::U32(idx)) = mesh.indices() {
            assert_eq!(idx.len(), 6, "expected 2 triangles × 3 indices");
        } else {
            panic!("expected U32 indices");
        }
    }

    #[test]
    fn triangle_face_front_winding_is_ccw() {
        let mesh = build_triangle_face(0.5, Vec3::ONE, false);
        let positions = match mesh.attribute(Mesh::ATTRIBUTE_POSITION) {
            Some(VertexAttributeValues::Float32x3(p)) => p,
            _ => panic!("expected Float32x3"),
        };
        // Front triangle is indices [0,1,2]; cross product must give +Z.
        let p0 = Vec3::from(positions[0]);
        let p1 = Vec3::from(positions[1]);
        let p2 = Vec3::from(positions[2]);
        let normal = (p1 - p0).cross(p2 - p0);
        assert!(
            normal.z > 0.0,
            "front face should have +Z normal, got {normal:?}"
        );
    }

    #[test]
    fn triangle_face_uvs_correct() {
        let size = Vec3::new(4.0, 3.0, 0.0);
        let mesh = build_triangle_face(0.5, size, false);
        let uvs = match mesh.attribute(Mesh::ATTRIBUTE_UV_0) {
            Some(VertexAttributeValues::Float32x2(u)) => u.clone(),
            _ => panic!("expected Float32x2 UVs"),
        };
        // V0 (bottom-left): U=0, V=h
        assert!((uvs[0][0]).abs() < 1e-5, "V0 U should be 0");
        assert!((uvs[0][1] - 3.0).abs() < 1e-5, "V0 V should be size.y=3");
        // V1 (bottom-right): U=w, V=h
        assert!((uvs[1][0] - 4.0).abs() < 1e-5, "V1 U should be size.x=4");
        // V2 (apex at peak=0.5): U=0.5*w=2, V=0
        assert!(
            (uvs[2][0] - 2.0).abs() < 1e-5,
            "V2 U should be 2.0 for peak=0.5"
        );
        assert!((uvs[2][1]).abs() < 1e-5, "V2 V should be 0 at ridge");
    }

    #[test]
    fn triangle_face_normals_are_unit() {
        let mesh = build_triangle_face(0.3, Vec3::new(5.0, 4.0, 0.0), false);
        if let Some(VertexAttributeValues::Float32x3(normals)) =
            mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
        {
            for n in normals {
                let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
                assert!((len - 1.0).abs() < 1e-5, "non-unit normal: {n:?}");
            }
        } else {
            panic!("expected Float32x3 normals");
        }
    }

    // ── build_trapezoid_face ─────────────────────────────────────────────────

    #[test]
    fn trapezoid_face_vertex_count() {
        let mesh = build_trapezoid_face(0.5, 0.25, Vec3::new(10.0, 5.0, 0.0), false);
        let pos = mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap();
        assert_eq!(pos.len(), 8, "expected 4 front + 4 back verts");
    }

    #[test]
    fn trapezoid_face_index_count() {
        let mesh = build_trapezoid_face(0.5, 0.25, Vec3::new(10.0, 5.0, 0.0), false);
        if let Some(Indices::U32(idx)) = mesh.indices() {
            assert_eq!(idx.len(), 12, "expected 4 triangles × 3 indices");
        } else {
            panic!("expected U32 indices");
        }
    }

    #[test]
    fn trapezoid_face_front_winding_is_ccw() {
        let mesh = build_trapezoid_face(0.5, 0.25, Vec3::ONE, false);
        let positions = match mesh.attribute(Mesh::ATTRIBUTE_POSITION) {
            Some(VertexAttributeValues::Float32x3(p)) => p,
            _ => panic!("expected Float32x3"),
        };
        // First front triangle: [0,1,2]
        let p0 = Vec3::from(positions[0]);
        let p1 = Vec3::from(positions[1]);
        let p2 = Vec3::from(positions[2]);
        let n = (p1 - p0).cross(p2 - p0);
        assert!(
            n.z > 0.0,
            "front face first tri should have +Z normal, got {n:?}"
        );
    }

    #[test]
    fn trapezoid_face_uvs_correct() {
        // top_width=0.5, offset_x=0.25 → top edge X ∈ [0.25, 0.75] of scope width
        let size = Vec3::new(10.0, 5.0, 0.0);
        let mesh = build_trapezoid_face(0.5, 0.25, size, false);
        let uvs = match mesh.attribute(Mesh::ATTRIBUTE_UV_0) {
            Some(VertexAttributeValues::Float32x2(u)) => u.clone(),
            _ => panic!("expected Float32x2 UVs"),
        };
        // V0 bottom-left: U=0, V=h=5
        assert!((uvs[0][0]).abs() < 1e-5);
        assert!((uvs[0][1] - 5.0).abs() < 1e-5);
        // V1 bottom-right: U=w=10, V=5
        assert!((uvs[1][0] - 10.0).abs() < 1e-5);
        // V2 top-right: U=(0.25+0.5)*10=7.5, V=0
        assert!((uvs[2][0] - 7.5).abs() < 1e-5);
        assert!((uvs[2][1]).abs() < 1e-5);
        // V3 top-left: U=0.25*10=2.5, V=0
        assert!((uvs[3][0] - 2.5).abs() < 1e-5);
        assert!((uvs[3][1]).abs() < 1e-5);
    }

    // ── ear_clip ─────────────────────────────────────────────────────────────

    #[test]
    fn ear_clip_triangle() {
        let verts = vec![
            Vec2::new(0.0, 0.0),
            Vec2::new(1.0, 0.0),
            Vec2::new(0.5, 1.0),
        ];
        let tris = ear_clip(&verts);
        assert_eq!(tris, vec![[0, 1, 2]]);
    }

    #[test]
    fn ear_clip_square_gives_two_triangles() {
        // CCW square
        let verts = vec![
            Vec2::new(0.0, 0.0),
            Vec2::new(1.0, 0.0),
            Vec2::new(1.0, 1.0),
            Vec2::new(0.0, 1.0),
        ];
        let tris = ear_clip(&verts);
        assert_eq!(tris.len(), 2, "square → 2 triangles");
        // Verify no index out of bounds
        for tri in &tris {
            for &i in tri {
                assert!(i < 4);
            }
        }
    }

    #[test]
    fn ear_clip_pentagon_gives_three_triangles() {
        use std::f32::consts::TAU;
        // Regular pentagon, CCW
        let verts: Vec<Vec2> = (0..5)
            .map(|i| {
                let t = TAU * i as f32 / 5.0;
                Vec2::new(t.cos(), t.sin())
            })
            .collect();
        let tris = ear_clip(&verts);
        assert_eq!(tris.len(), 3, "pentagon → 3 triangles");
    }

    // ── build_profiled_mesh dispatch ─────────────────────────────────────────

    #[test]
    fn profiled_mesh_rectangle_matches_cuboid() {
        let size = Vec3::new(2.0, 3.0, 1.0);
        let a = build_profiled_mesh(&FaceProfile::Rectangle, size, false);
        let b = build_tapered_cuboid(0.0, size, false);
        assert_eq!(
            a.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().len(),
            b.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().len()
        );
    }

    #[test]
    fn profiled_mesh_triangle_has_six_verts() {
        let mesh = build_profiled_mesh(
            &FaceProfile::Triangle { peak_offset: 0.5 },
            Vec3::new(4.0, 3.0, 0.0),
            false,
        );
        assert_eq!(mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().len(), 6);
    }

    #[test]
    fn profiled_mesh_trapezoid_has_eight_verts() {
        let mesh = build_profiled_mesh(
            &FaceProfile::Trapezoid {
                top_width: 0.5,
                offset_x: 0.25,
            },
            Vec3::new(10.0, 5.0, 0.0),
            false,
        );
        assert_eq!(mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().len(), 8);
    }

    #[test]
    fn profiled_mesh_polygon_square_has_eight_verts() {
        use bevy::math::DVec2;
        let pts = vec![
            DVec2::new(0.0, 0.0),
            DVec2::new(1.0, 0.0),
            DVec2::new(1.0, 1.0),
            DVec2::new(0.0, 1.0),
        ];
        let mesh = build_profiled_mesh(&FaceProfile::Polygon(pts), Vec3::new(4.0, 4.0, 0.0), false);
        // 4 front + 4 back
        assert_eq!(mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().len(), 8);
    }
}