bevy_symbios_shape 0.4.0

Bevy integration for Symbios Shape.
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
//! 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 {
    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 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::*;

    #[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);
    }
}