hephaestus 0.1.0

Backend-agnostic 2D scene renderer for data visualization.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
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
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
//! Polyline- and polygon-as-ribbon tessellation.
//!
//! A "ribbon" is a stroked open polyline or closed polygon expressed
//! as a triangle [`Mesh`] with per-vertex colour and per-vertex
//! half-width. Drawing happens via
//! [`SceneBuilder::draw_mesh`](crate::scene::SceneBuilder); the Vello
//! backend decomposes the mesh into per-triangle linear-gradient
//! fills, which gives perfect Gouraud-equivalent colour blending
//! along ribbon strips (because the two shoulders at each polyline
//! vertex carry the same colour, so the gradient axis runs cleanly
//! between adjacent segments).
//!
//! # Entry points
//!
//! Open polylines (with end caps):
//! - [`polyline_ribbon`] — constant colour, constant half-width.
//! - [`polyline_gradient`] — per-vertex colour, constant half-width.
//! - [`polyline_ribbon_full`] — per-vertex colour and per-vertex
//!   half-width.
//!
//! Closed polygons (no caps; the loop closes from `points[n - 1]`
//! back to `points[0]` — do not repeat the first vertex):
//! - [`polygon_ribbon`] — constant colour, constant half-width.
//! - [`polygon_gradient`] — per-vertex colour, constant half-width.
//! - [`polygon_ribbon_full`] — per-vertex colour and per-vertex
//!   half-width.
//!
//! Quad-strip band between two arbitrary co-indexed polylines:
//! - [`ribbon_band_mesh`] — fills the band between curve A and curve
//!   B with per-vertex colour on each side. Used by `RibbonGeom`
//!   under free-form orientation and under non-linear projections
//!   when fill varies.
//!
//! Caps: butt / square / round (open only — [`RibbonOptions::cap`]
//! is ignored by the `polygon_*` entry points). Joins: miter (with
//! auto-bevel fallback when the miter exceeds
//! [`RibbonOptions::miter_limit`]), bevel, round.
//!
//! All distances are in **panel pixels**. Callers convert from pt at
//! their own draw sites (`px = pt * dpi / 72.0`).

use std::ops::RangeInclusive;

use super::tolerance::{
    ARC_FAN_MAX_STEP, ARC_FAN_MIN_STEP, ARC_FAN_TOLERANCE, DEGENERATE_EPS as EPSILON,
};
use crate::color::Color;
use crate::geometry::{Point, Vec2};
use crate::mesh::Mesh;
use crate::stroke::{Cap, Join};

/// Colour used by the entry points that accept an optional per-vertex
/// colour slice when none is supplied.
const DEFAULT_COLOR: Color = Color::new([0.0, 0.0, 0.0, 1.0]);

/// Segment-count bounds for a round **cap** fan. The floor keeps a
/// hairline cap from collapsing to a triangle; the ceiling caps the
/// vertex cost of a very wide one.
const CAP_FAN_SEGMENTS: RangeInclusive<usize> = 4..=64;
/// Segment-count bounds for a round **join** fan. A join sweeps only
/// the turn angle rather than a half-circle, so it needs fewer
/// segments than a cap at the same radius.
const JOIN_FAN_SEGMENTS: RangeInclusive<usize> = 2..=32;

/// Per-segment seam-bleed in panel pixels. Each interior quad is
/// extended this far past its natural endpoint at both ends along the
/// local segment tangent, so adjacent quads overlap and SrcOver
/// compositing on the overlap region renders fully opaque — hiding
/// the AA seam that would otherwise appear at segment boundaries.
/// `0.75 px` is enough to cover a 1-px AA edge on each side while
/// keeping the gradient-axis distortion below 1.5% for typical
/// segment lengths.
const SEAM_BLEED_PX: f64 = 0.75;

// ── Options ────────────────────────────────────────────────────────────────

/// Tessellation options for [`polyline_ribbon`] / [`polyline_gradient`]
/// / [`polyline_ribbon_full`]. Caps and joins reuse [`crate::stroke::Cap`]
/// and [`crate::stroke::Join`] — same three variants each.
#[derive(Clone, Copy, Debug)]
pub struct RibbonOptions {
    /// Half-width in panel pixels. Used by entry points that don't
    /// take a per-vertex half-width slice; ignored by
    /// [`polyline_ribbon_full`] when `half_widths` is `Some`.
    pub half_width: f64,
    /// End-cap style for open ribbons. Ignored by `polygon_*` entry
    /// points (closed loops have no endpoints to cap).
    pub cap: Cap,
    /// Corner-join style at each interior vertex.
    pub join: Join,
    /// Maximum ratio `1 / cos(turn_angle / 2)` allowed at a mitre
    /// join. Joins exceeding this fall back to bevel for that join
    /// only. Matches the SVG default of `4.0`.
    pub miter_limit: f64,
}

impl Default for RibbonOptions {
    fn default() -> Self {
        Self {
            half_width: 1.0,
            cap: Cap::Butt,
            join: Join::Miter,
            miter_limit: 4.0,
        }
    }
}

// ── Public entry points ─────────────────────────────────────────────────────

/// Constant-colour, constant-width ribbon. Equivalent to a uniformly
/// stroked polyline expressed as a mesh.
pub fn polyline_ribbon(points: &[Point], color: Color, opts: &RibbonOptions) -> Mesh {
    ribbon(
        "polyline_ribbon",
        points,
        ColorSource::Constant(color),
        None,
        opts,
        false,
    )
}

/// Per-vertex coloured, constant-width ribbon. `colors.len()` must
/// equal `points.len()`.
pub fn polyline_gradient(points: &[Point], colors: &[Color], opts: &RibbonOptions) -> Mesh {
    ribbon(
        "polyline_gradient",
        points,
        ColorSource::PerVertex(colors),
        None,
        opts,
        false,
    )
}

/// Full ribbon: optionally per-vertex coloured, optionally per-vertex
/// half-width. `colors` defaults to opaque black and `half_widths` to
/// [`RibbonOptions::half_width`]; a supplied slice must match
/// `points.len()`.
pub fn polyline_ribbon_full(
    points: &[Point],
    colors: Option<&[Color]>,
    half_widths: Option<&[f64]>,
    opts: &RibbonOptions,
) -> Mesh {
    ribbon(
        "polyline_ribbon_full",
        points,
        ColorSource::from_optional(colors),
        half_widths,
        opts,
        false,
    )
}

/// Constant-colour, constant-width closed-polygon ribbon. The loop
/// closes from `points[n - 1]` back to `points[0]` — do **not**
/// repeat the first vertex. [`RibbonOptions::cap`] is ignored (a
/// closed loop has no endpoints to cap). Returns an empty mesh when
/// `points.len() < 3`.
pub fn polygon_ribbon(points: &[Point], color: Color, opts: &RibbonOptions) -> Mesh {
    ribbon(
        "polygon_ribbon",
        points,
        ColorSource::Constant(color),
        None,
        opts,
        true,
    )
}

/// Per-vertex coloured, constant-width closed-polygon ribbon.
/// `colors.len()` must equal `points.len()`. The wrap segment
/// interpolates `colors[n - 1] → colors[0]` like any other segment,
/// so the gradient closes seamlessly. See [`polygon_ribbon`] for the
/// closure convention.
pub fn polygon_gradient(points: &[Point], colors: &[Color], opts: &RibbonOptions) -> Mesh {
    ribbon(
        "polygon_gradient",
        points,
        ColorSource::PerVertex(colors),
        None,
        opts,
        true,
    )
}

/// Full closed-polygon ribbon: optionally per-vertex coloured,
/// optionally per-vertex half-width. `colors` defaults to opaque black
/// and `half_widths` to [`RibbonOptions::half_width`]; a supplied slice
/// must match `points.len()`. See [`polygon_ribbon`] for the closure
/// convention.
pub fn polygon_ribbon_full(
    points: &[Point],
    colors: Option<&[Color]>,
    half_widths: Option<&[f64]>,
    opts: &RibbonOptions,
) -> Mesh {
    ribbon(
        "polygon_ribbon_full",
        points,
        ColorSource::from_optional(colors),
        half_widths,
        opts,
        true,
    )
}

/// Validate the per-vertex slices on behalf of one of the six entry
/// points — `who` names it in the panic — then tessellate.
fn ribbon(
    who: &str,
    points: &[Point],
    colors: ColorSource<'_>,
    half_widths: Option<&[f64]>,
    opts: &RibbonOptions,
    closed: bool,
) -> Mesh {
    if let ColorSource::PerVertex(c) = colors {
        assert_eq!(
            points.len(),
            c.len(),
            "{who}: points.len() ({}) != colors.len() ({})",
            points.len(),
            c.len(),
        );
    }
    if let Some(w) = half_widths {
        assert_eq!(
            points.len(),
            w.len(),
            "{who}: points.len() ({}) != half_widths.len() ({})",
            points.len(),
            w.len(),
        );
    }
    ribbon_inner(points, colors, half_widths, opts, closed)
}

/// Build a filled quad-strip mesh between two co-indexed polylines.
///
/// `curve_a` and `curve_b` must have the same length. Each interior
/// segment from index `i` to `i + 1` emits a quad with corners
/// `(curve_a[i], curve_b[i], curve_b[i + 1], curve_a[i + 1])`,
/// tessellated as two triangles in the canonical `[A, B, C, A, C, D]`
/// pattern that the Vello backend's quad-pair detector folds into a
/// single bilinear-gradient quad fill. Per-vertex colours come from
/// `colors_a` (curve A side) and `colors_b` (curve B side).
///
/// Returns an empty mesh when either curve has fewer than two points.
/// Panics on length mismatch.
///
/// Adjacent quads overlap by a small fraction of `SEAM_BLEED_PX` along
/// the local sweep tangent at every interior boundary so the AA seam
/// between independent quad fills is hidden. The overlap is much
/// smaller than the polyline-ribbon's `SEAM_BLEED_PX` because each
/// quad of the band gets its own linear-gradient brush (the
/// Vello backend's quad-pair detector folds the strip into one gradient
/// fill per quad); two adjacent quads paint the overlap region twice
/// with the **same** boundary colour, so SrcOver compositing stacks
/// the alpha when the fill is translucent and reveals the seam as a
/// darker band. A small bleed is enough to bridge the AA edge without
/// producing a perceptible double-coat.
///
/// For a uniformly-coloured band a plain `fill` on the path that
/// traces curve A forward then curve B in reverse is cheaper — the
/// per-vertex colour is the point of the mesh path.
pub fn ribbon_band_mesh(
    curve_a: &[Point],
    curve_b: &[Point],
    colors_a: &[Color],
    colors_b: &[Color],
) -> Mesh {
    assert_eq!(
        curve_a.len(),
        curve_b.len(),
        "ribbon_band_mesh: curve_a.len() ({}) != curve_b.len() ({})",
        curve_a.len(),
        curve_b.len(),
    );
    assert_eq!(
        curve_a.len(),
        colors_a.len(),
        "ribbon_band_mesh: colors_a.len() must match curve_a.len()"
    );
    assert_eq!(
        curve_b.len(),
        colors_b.len(),
        "ribbon_band_mesh: colors_b.len() must match curve_b.len()"
    );
    let n = curve_a.len();
    if n < 2 {
        return Mesh::new(Vec::new(), Vec::new(), Vec::new());
    }

    let segs = n - 1;
    let mut vertices: Vec<Point> = Vec::with_capacity(4 * segs);
    let mut colors: Vec<Color> = Vec::with_capacity(4 * segs);
    let mut indices: Vec<u32> = Vec::with_capacity(6 * segs);

    for i in 0..segs {
        // Sweep tangent for segment i: midpoint(a[i], b[i]) → midpoint(a[i+1], b[i+1]).
        let m0 = Vec2::new(
            (curve_a[i].x + curve_b[i].x) * 0.5,
            (curve_a[i].y + curve_b[i].y) * 0.5,
        );
        let m1 = Vec2::new(
            (curve_a[i + 1].x + curve_b[i + 1].x) * 0.5,
            (curve_a[i + 1].y + curve_b[i + 1].y) * 0.5,
        );
        let delta = m1 - m0;
        let len = delta.hypot();
        let tangent = if len > EPSILON {
            delta / len
        } else {
            Vec2::new(0.0, 0.0)
        };
        // Bleed interior seams; outer-most quad edges (segment 0's near
        // end and the last segment's far end) carry the band's actual
        // endpoints — leave them alone so any caller-drawn endcap lines
        // up flush. Use a third of the polyline-ribbon's bleed: enough
        // to cover the AA edge without stacking enough alpha to be
        // perceptible on translucent fills.
        let interior_bleed = SEAM_BLEED_PX / 3.0;
        let near_bleed = if i > 0 { interior_bleed } else { 0.0 };
        let far_bleed = if i + 1 < segs { interior_bleed } else { 0.0 };
        let near_off = tangent * near_bleed;
        let far_off = tangent * far_bleed;

        let base = vertices.len() as u32;
        vertices.push(curve_a[i] - near_off);
        vertices.push(curve_b[i] - near_off);
        vertices.push(curve_b[i + 1] + far_off);
        vertices.push(curve_a[i + 1] + far_off);
        colors.push(colors_a[i]);
        colors.push(colors_b[i]);
        colors.push(colors_b[i + 1]);
        colors.push(colors_a[i + 1]);
        indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
    }

    Mesh::new(vertices, colors, indices)
}

// ── Inner machinery ─────────────────────────────────────────────────────────

#[derive(Clone, Copy)]
enum ColorSource<'a> {
    Constant(Color),
    PerVertex(&'a [Color]),
}

impl<'a> ColorSource<'a> {
    /// Per-vertex when a colour slice is supplied, opaque black
    /// otherwise.
    fn from_optional(colors: Option<&'a [Color]>) -> Self {
        match colors {
            Some(c) => ColorSource::PerVertex(c),
            None => ColorSource::Constant(DEFAULT_COLOR),
        }
    }

    fn at(&self, i: usize) -> Color {
        match self {
            ColorSource::Constant(c) => *c,
            ColorSource::PerVertex(slice) => slice[i],
        }
    }
}

/// Per-vertex layout info computed in pass 1.
struct VertexLayout {
    /// Inbound shoulder pair `(left, right)` — at the end of the
    /// previous segment. Equal to `out` for mitre / endpoint cases.
    in_left: Point,
    in_right: Point,
    /// Outbound shoulder pair `(left, right)` — at the start of the
    /// next segment.
    out_left: Point,
    out_right: Point,
    /// `true` when the vertex is a bevel join (in_pair ≠ out_pair). A
    /// bevel-fill triangle is emitted on the outside of the turn.
    is_bevel: bool,
    /// Which side bulges out at this bevel join — `true` for "left",
    /// `false` for "right". Ignored when `is_bevel` is false.
    bevel_outside_left: bool,
}

fn ribbon_inner(
    points: &[Point],
    colors: ColorSource<'_>,
    half_widths: Option<&[f64]>,
    opts: &RibbonOptions,
    closed: bool,
) -> Mesh {
    let n = points.len();
    // Open polylines need >= 2 points; closed polygons need >= 3
    // (anything less is degenerate).
    let min_pts = if closed { 3 } else { 2 };
    if n < min_pts {
        return Mesh::new(Vec::new(), Vec::new(), Vec::new());
    }

    // Per-vertex half-widths (panel-px). Falls back to opts.half_width.
    let hw = |i: usize| -> f64 {
        match half_widths {
            Some(w) => w[i],
            None => opts.half_width,
        }
    };

    // Compute unit segment tangents. `seg_tangent[i]` is the tangent
    // of segment `points[i] → points[(i + 1) % n]`. Open polylines
    // have n-1 segments; closed polygons have n (the last one wraps
    // back to vertex 0).
    let n_segs = if closed { n } else { n - 1 };
    let mut seg_tangent: Vec<Vec2> = Vec::with_capacity(n_segs);
    for i in 0..n_segs {
        let delta = points[(i + 1) % n] - points[i];
        let len = delta.hypot();
        if len <= EPSILON {
            // Degenerate segment — re-use last tangent if any,
            // otherwise +x. The resulting ribbon will still be valid;
            // a duplicated polyline vertex just creates a zero-area
            // quad.
            let last = seg_tangent.last().copied().unwrap_or(Vec2::new(1.0, 0.0));
            seg_tangent.push(last);
        } else {
            seg_tangent.push(delta / len);
        }
    }

    // Compute per-vertex layout.
    let mut layouts: Vec<VertexLayout> = Vec::with_capacity(n);
    for i in 0..n {
        // For closed loops vertex 0's inbound segment is the wrap
        // (seg_tangent[n - 1]), and vertex n-1's outbound is the same
        // wrap. For open polylines the endpoint branch below picks
        // whichever tangent it actually needs, so the dummy values
        // here are unused.
        let t_in = if i == 0 {
            if closed {
                seg_tangent[n - 1]
            } else {
                seg_tangent[0]
            }
        } else {
            seg_tangent[i - 1]
        };
        let t_out = if i + 1 == n {
            if closed {
                seg_tangent[n - 1]
            } else {
                seg_tangent[n - 2]
            }
        } else {
            seg_tangent[i]
        };
        let pi = points[i];
        let w = hw(i);

        if !closed && (i == 0 || i + 1 == n) {
            // Endpoint: single perpendicular offset.
            let t = if i == 0 { t_out } else { t_in };
            let n_left = perp_left(t);
            let l = pi + n_left * w;
            let r = pi - n_left * w;
            layouts.push(VertexLayout {
                in_left: l,
                in_right: r,
                out_left: l,
                out_right: r,
                is_bevel: false,
                bevel_outside_left: false,
            });
            continue;
        }

        // Interior vertex.
        let perp_in = perp_left(t_in);
        let perp_out = perp_left(t_out);
        // Determine outside direction: a left turn (cross > 0) bulges
        // on the right side; right turn bulges on the left.
        let cross = t_in.x * t_out.y - t_in.y * t_out.x;
        let dot = t_in.x * t_out.x + t_in.y * t_out.y;
        let bevel_outside_left = cross < 0.0;

        // Try miter: shoulder pair at the bisector position.
        let denom = 1.0 + dot;
        let miter_mag = if denom > EPSILON {
            // 1 / cos(α/2) where α is the turn angle. Equivalent to
            // `(perp_in + perp_out) / denom`'s magnitude divided by 1
            // (the unit perpendicular length). Cheaper to compute via
            // the half-angle identity.
            (2.0 / denom).sqrt()
        } else {
            f64::INFINITY
        };

        let want_miter = match opts.join {
            Join::Miter => miter_mag <= opts.miter_limit && denom > EPSILON,
            // Round and bevel both emit two shoulder pairs; round
            // additionally fills the outside notch with a fan, bevel
            // fills it with one triangle.
            _ => false,
        };

        if want_miter {
            let mitre = (perp_in + perp_out) * (w / denom);
            let l = pi + mitre;
            let r = pi - mitre;
            layouts.push(VertexLayout {
                in_left: l,
                in_right: r,
                out_left: l,
                out_right: r,
                is_bevel: false,
                bevel_outside_left,
            });
        } else {
            // Bevel (or round, handled as bevel + fan in the emit
            // step). Two shoulder pairs perpendicular to each segment.
            let in_l = pi + perp_in * w;
            let in_r = pi - perp_in * w;
            let out_l = pi + perp_out * w;
            let out_r = pi - perp_out * w;
            layouts.push(VertexLayout {
                in_left: in_l,
                in_right: in_r,
                out_left: out_l,
                out_right: out_r,
                is_bevel: true,
                bevel_outside_left,
            });
        }
    }

    // Build the mesh. Output buffers.
    let mut vertices: Vec<Point> = Vec::new();
    let mut vcolors: Vec<Color> = Vec::new();
    let mut indices: Vec<u32> = Vec::new();

    // Helper: push a single vertex with colour, return its index.
    let push_vertex =
        |vertices: &mut Vec<Point>, vcolors: &mut Vec<Color>, p: Point, c: Color| -> u32 {
            let idx = vertices.len() as u32;
            vertices.push(p);
            vcolors.push(c);
            idx
        };

    // Emission order: path-order. For a self-intersecting polyline,
    // later geometry draws on top of earlier geometry under SrcOver —
    // so emitting "start cap → segments → joins → end cap" in path
    // order ensures the path's tail correctly occludes its head when
    // they cross. The previous ordering (caps last) caused the start
    // cap to draw OVER segments that happened to pass through it.
    //
    // **Seam-bleed**: each interior segment quad is extended by
    // `SEAM_BLEED_PX` along its local tangent at both ends, so
    // adjacent quads overlap by ~2 × bleed in their shared boundary
    // region. SrcOver compositing on the overlap renders fully
    // opaque, eliminating the AA seam between adjacent fills. The
    // gradient stops are computed against the original (unbled)
    // axis, so the bleed introduces a tiny ε/L colour shift at the
    // original endpoints — invisible for typical segment lengths.
    // Endpoint edges (segment 0's near / last segment's far) are NOT
    // bled, so cap geometry attaches at the natural shoulder
    // positions.

    // 1. Start cap (open polylines only — closed polygons have no
    //    endpoints to cap).
    if !closed {
        emit_cap(
            &mut vertices,
            &mut vcolors,
            &mut indices,
            points[0],
            layouts[0].out_left,
            layouts[0].out_right,
            -seg_tangent[0],
            colors.at(0),
            opts.cap,
            hw(0),
        );
    }

    // 2. Per-segment quads, interleaved with joins at the segment's
    //    *end* vertex (the start vertex of the next segment).
    //
    // Endpoint-edge bleed: for caps with geometry (square / round),
    // bleed the segment's endpoint edge **into the cap region** so
    // the segment overlaps the cap's interior — eliminating the AA
    // seam between the segment quad and the cap polygon. For butt
    // caps there's no cap geometry, so the bleed would just extend
    // the line by ε past its nominal endpoint — skip it. For closed
    // polygons every segment is interior, so the cap-bleed path is
    // unused.
    let cap_bleed_amount = match opts.cap {
        Cap::Butt => 0.0,
        Cap::Square | Cap::Round => SEAM_BLEED_PX,
    };
    for i in 0..n_segs {
        let i_next = (i + 1) % n;
        let ci = colors.at(i);
        let cj = colors.at(i_next);
        let t = seg_tangent[i];
        // For closed loops every boundary is interior; for open
        // polylines the segment's near boundary is the start cap when
        // i == 0, and the far boundary is the end cap when i == n-2.
        let near_bleed_amount = if closed || i > 0 {
            SEAM_BLEED_PX
        } else {
            cap_bleed_amount
        };
        let far_bleed_amount = if closed || i + 1 < n - 1 {
            SEAM_BLEED_PX
        } else {
            cap_bleed_amount
        };
        let near_bleed = t * near_bleed_amount;
        let far_bleed = t * far_bleed_amount;
        let a_pos = layouts[i].out_left - near_bleed;
        let b_pos = layouts[i].out_right - near_bleed;
        let c_pos = layouts[i_next].in_right + far_bleed;
        let d_pos = layouts[i_next].in_left + far_bleed;
        let a = push_vertex(&mut vertices, &mut vcolors, a_pos, ci);
        let b = push_vertex(&mut vertices, &mut vcolors, b_pos, ci);
        let c = push_vertex(&mut vertices, &mut vcolors, c_pos, cj);
        let d = push_vertex(&mut vertices, &mut vcolors, d_pos, cj);
        indices.extend_from_slice(&[a, b, c, a, c, d]);

        // Join at vertex i_next, if it's a bevel/round.
        // Open: only interior vertices (vertex 0 and n-1 are caps).
        // Closed: every vertex is interior, including the wrap-back
        // to vertex 0 emitted by the last segment.
        let is_interior_join = closed || i_next < n - 1;
        if is_interior_join && layouts[i_next].is_bevel {
            emit_join_fill(
                &mut vertices,
                &mut vcolors,
                &mut indices,
                points[i_next],
                &layouts[i_next],
                colors.at(i_next),
                opts.join,
            );
        }
    }

    // 3. End cap (open polylines only).
    if !closed {
        let last = n - 1;
        emit_cap(
            &mut vertices,
            &mut vcolors,
            &mut indices,
            points[last],
            layouts[last].in_right,
            layouts[last].in_left,
            seg_tangent[n - 2],
            colors.at(last),
            opts.cap,
            hw(last),
        );
    }

    Mesh::new(vertices, vcolors, indices)
}

/// Emit the bevel / round fill triangle(s) at a single interior
/// vertex. For mitre joins that didn't fall back to bevel, `is_bevel`
/// is false and the caller skips this entirely.
fn emit_join_fill(
    vertices: &mut Vec<Point>,
    vcolors: &mut Vec<Color>,
    indices: &mut Vec<u32>,
    pi: Point,
    layout: &VertexLayout,
    color: Color,
    join: Join,
) {
    let (outside_in, outside_out) = if layout.bevel_outside_left {
        (layout.in_left, layout.out_left)
    } else {
        (layout.in_right, layout.out_right)
    };
    match join {
        Join::Bevel | Join::Miter => {
            let i_p = vertices.len() as u32;
            vertices.push(pi);
            vcolors.push(color);
            let i_oi = vertices.len() as u32;
            vertices.push(outside_in);
            vcolors.push(color);
            let i_oo = vertices.len() as u32;
            vertices.push(outside_out);
            vcolors.push(color);
            indices.extend_from_slice(&[i_p, i_oi, i_oo]);
        }
        Join::Round => {
            // The fan fills the outside notch, so it takes the shorter
            // of the two sweeps between the outside shoulders.
            let va = outside_in - pi;
            emit_arc_fan(
                vertices,
                vcolors,
                indices,
                pi,
                outside_in,
                va.hypot(),
                va.y.atan2(va.x),
                normalized_delta(va, outside_out - pi),
                JOIN_FAN_SEGMENTS,
                color,
            );
        }
    }
}

/// Emit cap geometry at one endpoint. `outward` is the unit vector
/// pointing away from the polyline at this endpoint (start cap:
/// `-tangent_of_first_segment`; end cap: `+tangent_of_last_segment`).
/// `(a, b)` are the two shoulder vertices already placed at the
/// endpoint, ordered so that a→b crosses outward to the right of the
/// outward direction (i.e., `a = left_relative_to_outward,
/// b = right_relative_to_outward`).
#[allow(clippy::too_many_arguments, clippy::ptr_arg)]
fn emit_cap(
    vertices: &mut Vec<Point>,
    vcolors: &mut Vec<Color>,
    indices: &mut Vec<u32>,
    endpoint: Point,
    a: Point,
    b: Point,
    outward: Vec2,
    color: Color,
    cap: Cap,
    half_width: f64,
) {
    match cap {
        Cap::Butt => {} // No cap geometry.
        Cap::Square => {
            // Extrude (a, b) by `half_width` along `outward`, emit a
            // quad.
            let a_ext = a + outward * half_width;
            let b_ext = b + outward * half_width;
            let i_a = vertices.len() as u32;
            vertices.push(a);
            vcolors.push(color);
            let i_b = vertices.len() as u32;
            vertices.push(b);
            vcolors.push(color);
            let i_be = vertices.len() as u32;
            vertices.push(b_ext);
            vcolors.push(color);
            let i_ae = vertices.len() as u32;
            vertices.push(a_ext);
            vcolors.push(color);
            indices.extend_from_slice(&[i_a, i_b, i_be, i_a, i_be, i_ae]);
        }
        Cap::Round => {
            // Sweep from shoulder `a` round to shoulder `b` on the
            // outward side: the semicircle, not the (zero-length) sweep
            // straight across the endpoint.
            let va = a - endpoint;
            let mut delta = normalized_delta(va, b - endpoint);
            // The two shoulders sit on opposite sides of the endpoint,
            // so the semicircle is whichever direction has magnitude
            // ≈ π. When the natural (-π, π] delta is shorter than that,
            // the cap has to go the other way round.
            if delta.abs() < std::f64::consts::PI - 1e-6 {
                delta = if delta >= 0.0 {
                    delta - std::f64::consts::TAU
                } else {
                    delta + std::f64::consts::TAU
                };
            }
            emit_arc_fan(
                vertices,
                vcolors,
                indices,
                endpoint,
                a,
                half_width.max(EPSILON),
                va.y.atan2(va.x),
                delta,
                CAP_FAN_SEGMENTS,
                color,
            );
        }
    }
}

/// Signed angle from `from` to `to`, normalised into `(-π, π]` — the
/// shorter of the two ways round.
fn normalized_delta(from: Vec2, to: Vec2) -> f64 {
    let mut delta = to.y.atan2(to.x) - from.y.atan2(from.x);
    while delta > std::f64::consts::PI {
        delta -= std::f64::consts::TAU;
    }
    while delta <= -std::f64::consts::PI {
        delta += std::f64::consts::TAU;
    }
    delta
}

/// Emit a triangle fan approximating the circular arc of radius `r`
/// centred at `center`, running `delta` radians (signed) from angle
/// `theta_a`. The fan's first rim vertex is `start`, which the caller
/// supplies so the fan meets the neighbouring geometry exactly;
/// subsequent rim vertices are placed on the arc.
///
/// Two complementary bounds set the angular step: the chord error
/// `ε = R · (1 − cos(Δθ/2))` keeps positional deviation within
/// [`ARC_FAN_TOLERANCE`] at any radius, and [`ARC_FAN_MAX_STEP`] keeps
/// small radii from reading as faceted. The denser of the two wins,
/// and `seg_clamp` bounds the resulting count.
#[allow(clippy::too_many_arguments)]
fn emit_arc_fan(
    vertices: &mut Vec<Point>,
    vcolors: &mut Vec<Color>,
    indices: &mut Vec<u32>,
    center: Point,
    start: Point,
    r: f64,
    theta_a: f64,
    delta: f64,
    seg_clamp: RangeInclusive<usize>,
    color: Color,
) {
    let chord_step = (1.0 - (ARC_FAN_TOLERANCE / r.max(EPSILON)).clamp(0.0, 1.0)).acos() * 2.0;
    let theta_step = chord_step.clamp(ARC_FAN_MIN_STEP, ARC_FAN_MAX_STEP);
    let segments = (delta.abs() / theta_step).ceil() as usize;
    let n_steps = segments.clamp(*seg_clamp.start(), *seg_clamp.end());
    let step = delta / n_steps as f64;

    let i_center = vertices.len() as u32;
    vertices.push(center);
    vcolors.push(color);
    let i_start = vertices.len() as u32;
    vertices.push(start);
    vcolors.push(color);
    let mut prev = i_start;
    for k in 1..=n_steps {
        let theta = theta_a + step * k as f64;
        let p = Point::new(center.x + r * theta.cos(), center.y + r * theta.sin());
        let idx = vertices.len() as u32;
        vertices.push(p);
        vcolors.push(color);
        indices.extend_from_slice(&[i_center, prev, idx]);
        prev = idx;
    }
}

#[inline]
fn perp_left(v: Vec2) -> Vec2 {
    Vec2::new(-v.y, v.x)
}

// ── Tests ──────────────────────────────────────────────────────────────────

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

    fn pt(x: f64, y: f64) -> Point {
        Point::new(x, y)
    }
    fn red() -> Color {
        Color::new([1.0, 0.0, 0.0, 1.0])
    }
    fn green() -> Color {
        Color::new([0.0, 1.0, 0.0, 1.0])
    }
    fn blue() -> Color {
        Color::new([0.0, 0.0, 1.0, 1.0])
    }

    fn approx(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-9
    }

    #[test]
    fn polyline_ribbon_two_point_butt() {
        // Straight line along +x, half_width 1. Two segments end up
        // sharing shoulders — total 4 vertices (the two shoulder
        // pairs), 2 triangles.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let opts = RibbonOptions {
            half_width: 1.0,
            cap: Cap::Butt,
            join: Join::Miter,
            miter_limit: 4.0,
        };
        let mesh = polyline_ribbon(&pts, red(), &opts);
        assert_eq!(mesh.vertex_count(), 4);
        assert_eq!(mesh.triangle_count(), 2);
        // Shoulders sit at (0, ±1) and (10, ±1).
        let mut ys: Vec<f64> = mesh.vertices.iter().map(|p| p.y).collect();
        ys.sort_by(|a, b| a.partial_cmp(b).unwrap());
        assert!(approx(ys[0], -1.0));
        assert!(approx(ys[1], -1.0));
        assert!(approx(ys[2], 1.0));
        assert!(approx(ys[3], 1.0));
    }

    #[test]
    fn polyline_ribbon_constant_color_all_vertices_match() {
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let mesh = polyline_ribbon(&pts, red(), &RibbonOptions::default());
        for c in &mesh.colors {
            assert_eq!(*c, red());
        }
    }

    #[test]
    fn polyline_gradient_endpoint_colors_preserved() {
        // 2-point polyline; vertex 0 gets red, vertex 1 gets blue.
        // Both shoulders at vertex 0 carry red; both at vertex 1
        // carry blue. With butt caps + miter (no joins), there are
        // exactly 4 vertices.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let cols = [red(), blue()];
        let mesh = polyline_gradient(&pts, &cols, &RibbonOptions::default());
        assert_eq!(mesh.vertex_count(), 4);
        // The two left-most x vertices (x ≈ 0) carry red; the two
        // right-most (x ≈ 10) carry blue.
        for (p, c) in mesh.vertices.iter().zip(mesh.colors.iter()) {
            if approx(p.x, 0.0) {
                assert_eq!(*c, red());
            } else if approx(p.x, 10.0) {
                assert_eq!(*c, blue());
            }
        }
    }

    #[test]
    fn polyline_gradient_interior_color_shared_across_segments() {
        // 3-vertex polyline; interior vertex's shoulders carry green.
        // Miter join → single shoulder pair at interior. Each segment
        // quad gets a small bleed (SEAM_BLEED_PX) along the local
        // tangent to eliminate the AA seam between adjacent fills, so
        // shoulders near the interior vertex are emitted at slightly
        // staggered x-coordinates. All such shoulders should still
        // carry the green colour.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(20.0, 0.0)];
        let cols = [red(), green(), blue()];
        let mesh = polyline_gradient(&pts, &cols, &RibbonOptions::default());
        // Anything within ±2 × bleed of x=10 (the interior vertex) is
        // an interior-shoulder emission; all should be green.
        let interior_greens = mesh
            .vertices
            .iter()
            .zip(mesh.colors.iter())
            .filter(|(p, _)| (p.x - 10.0).abs() < 2.0)
            .map(|(_, c)| *c)
            .collect::<Vec<_>>();
        assert!(!interior_greens.is_empty());
        for c in &interior_greens {
            assert_eq!(*c, green(), "interior shoulder should be green");
        }
    }

    #[test]
    fn polyline_ribbon_full_variable_width_shoulder_offsets() {
        // Straight line along +x with widths [1, 2, 1]. Shoulder
        // y-coords should be ±1, ±2, ±1 at the (approximate) x
        // positions 0, 5, 10. Seam-bleed splits the interior x=5
        // shoulders into a stagger around x ≈ 4.25 and x ≈ 5.75, but
        // the y-coords remain unchanged.
        let pts = [pt(0.0, 0.0), pt(5.0, 0.0), pt(10.0, 0.0)];
        let widths = [1.0_f64, 2.0, 1.0];
        let mesh = polyline_ribbon_full(&pts, None, Some(&widths), &RibbonOptions::default());
        // Bucket shoulders by approximate x (within ±1 of the
        // expected polyline-vertex x).
        let mut shoulders_at_x: Vec<(f64, Vec<f64>)> =
            vec![(0.0, Vec::new()), (5.0, Vec::new()), (10.0, Vec::new())];
        for p in &mesh.vertices {
            for (x, ys) in shoulders_at_x.iter_mut() {
                if (p.x - *x).abs() < 1.0 {
                    ys.push(p.y);
                }
            }
        }
        for (x, ys) in shoulders_at_x {
            let expected: Vec<f64> = if approx(x, 5.0) {
                vec![-2.0, 2.0]
            } else {
                vec![-1.0, 1.0]
            };
            let mut sorted = ys.clone();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            sorted.dedup_by(|a, b| approx(*a, *b));
            assert_eq!(
                sorted.len(),
                expected.len(),
                "at x={x}, unique shoulder ys = {sorted:?}"
            );
            for (s, e) in sorted.iter().zip(expected.iter()) {
                assert!(approx(*s, *e), "at x={x}, got {s}, expected {e}");
            }
        }
    }

    #[test]
    fn polyline_ribbon_90_corner_mitre() {
        // Three points forming a right-turn 90° corner at (10, 0).
        // miter_mag = 1/cos(45°) ≈ 1.4142, within default miter_limit
        // of 4 → miter join, single shoulder pair at the corner.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 10.0)];
        let opts = RibbonOptions {
            half_width: 1.0,
            join: Join::Miter,
            ..RibbonOptions::default()
        };
        let mesh = polyline_ribbon(&pts, red(), &opts);
        // No bevel triangle → 2 segments × 2 tris = 4 triangles.
        assert_eq!(mesh.triangle_count(), 4);
        // The outer-corner mitre sits at (11, -1) in the layout, but
        // segment 0's far-end shoulders are bled forward by
        // SEAM_BLEED_PX (= 0.75) along seg_tangent[0] = (1, 0). So
        // the emitted vertex lands at (11.75, -1). Segment 1's
        // near-end shoulders are bled backward by SEAM_BLEED_PX along
        // -seg_tangent[1] = (0, -1), landing at (11, -0.75). Both
        // are valid bled-mitre emissions; test for *either*.
        let near_mitre = mesh.vertices.iter().find(|p| {
            (approx(p.x, 11.75) && approx(p.y, -1.0)) || (approx(p.x, 11.0) && approx(p.y, -0.25))
        });
        assert!(
            near_mitre.is_some(),
            "expected bled outer-mitre near (11, -1); got vertices = {:?}",
            mesh.vertices
        );
    }

    #[test]
    fn polyline_ribbon_sharp_corner_clamps_to_bevel() {
        // Near-U-turn — mitre would extend far beyond miter_limit, so
        // the miter-join setting falls back to a bevel at this vertex.
        // The bevel emits an extra fill triangle.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(0.0, 0.1)];
        let opts = RibbonOptions {
            half_width: 1.0,
            join: Join::Miter,
            miter_limit: 2.0,
            ..RibbonOptions::default()
        };
        let mesh = polyline_ribbon(&pts, red(), &opts);
        // 2 segments × 2 tris = 4, plus 1 bevel-fill = 5.
        assert_eq!(mesh.triangle_count(), 5);
    }

    #[test]
    fn polyline_ribbon_bevel_join_emits_extra_triangle() {
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 10.0)];
        let opts = RibbonOptions {
            half_width: 1.0,
            join: Join::Bevel,
            ..RibbonOptions::default()
        };
        let mesh = polyline_ribbon(&pts, red(), &opts);
        // 4 segment triangles + 1 bevel fill.
        assert_eq!(mesh.triangle_count(), 5);
    }

    #[test]
    fn polyline_ribbon_round_join_emits_fan() {
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 10.0)];
        let opts = RibbonOptions {
            half_width: 5.0, // larger radius → more fan segments
            join: Join::Round,
            ..RibbonOptions::default()
        };
        let mesh = polyline_ribbon(&pts, red(), &opts);
        // 4 segment triangles + N fan triangles (N >= 2).
        assert!(
            mesh.triangle_count() >= 6,
            "got {} triangles",
            mesh.triangle_count()
        );
    }

    #[test]
    fn polyline_ribbon_square_cap_extends_endpoint() {
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let opts = RibbonOptions {
            half_width: 1.0,
            cap: Cap::Square,
            ..RibbonOptions::default()
        };
        let mesh = polyline_ribbon(&pts, red(), &opts);
        // Square caps add 2 triangles per cap.
        // 2 segment + 2 (start cap) + 2 (end cap) = 6 triangles.
        assert_eq!(mesh.triangle_count(), 6);
        // Bounding box should now extend past x ∈ [-1, 11] (one
        // half-width beyond each endpoint).
        let bb = mesh.bounding_box();
        assert!(approx(bb.x0, -1.0));
        assert!(approx(bb.x1, 11.0));
    }

    #[test]
    fn polyline_ribbon_round_cap_emits_fan() {
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let opts = RibbonOptions {
            half_width: 5.0,
            cap: Cap::Round,
            ..RibbonOptions::default()
        };
        let mesh = polyline_ribbon(&pts, red(), &opts);
        // 2 segment + ≥4 fan triangles per round cap.
        assert!(mesh.triangle_count() >= 2 + 2 * 4);
    }

    #[test]
    fn polyline_ribbon_butt_cap_emits_no_cap_triangles() {
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let opts = RibbonOptions {
            half_width: 1.0,
            cap: Cap::Butt,
            ..RibbonOptions::default()
        };
        let mesh = polyline_ribbon(&pts, red(), &opts);
        assert_eq!(mesh.triangle_count(), 2);
    }

    #[test]
    fn polyline_ribbon_bounding_box_straight_butt() {
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let opts = RibbonOptions {
            half_width: 1.0,
            cap: Cap::Butt,
            ..RibbonOptions::default()
        };
        let mesh = polyline_ribbon(&pts, red(), &opts);
        let bb = mesh.bounding_box();
        assert!(approx(bb.x0, 0.0));
        assert!(approx(bb.x1, 10.0));
        assert!(approx(bb.y0, -1.0));
        assert!(approx(bb.y1, 1.0));
    }

    #[test]
    fn polyline_ribbon_under_two_points_returns_empty() {
        let pts = [pt(0.0, 0.0)];
        let mesh = polyline_ribbon(&pts, red(), &RibbonOptions::default());
        assert!(mesh.is_empty());
    }

    #[test]
    #[should_panic(expected = "colors.len()")]
    fn polyline_gradient_panics_on_length_mismatch() {
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let cols = [red(), green(), blue()];
        let _ = polyline_gradient(&pts, &cols, &RibbonOptions::default());
    }

    // ── Closed-polygon ribbon ──────────────────────────────────────

    #[test]
    fn polygon_ribbon_equilateral_triangle_segment_count() {
        // Interior angle 60°, turn angle 120°, miter_mag = 2 < 4 →
        // mitre at every vertex, no bevel fills. 3 wrap segments × 2
        // tris per segment = 6.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(5.0, 8.66)];
        let opts = RibbonOptions {
            half_width: 1.0,
            join: Join::Miter,
            ..RibbonOptions::default()
        };
        let mesh = polygon_ribbon(&pts, red(), &opts);
        assert_eq!(mesh.triangle_count(), 6);
    }

    #[test]
    fn polygon_ribbon_square_bevel_emits_four_extra_triangles() {
        // 4 segments × 2 + one bevel fill at each of 4 corners
        // (including the wrap-back to vertex 0).
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 10.0), pt(0.0, 10.0)];
        let opts = RibbonOptions {
            half_width: 1.0,
            join: Join::Bevel,
            ..RibbonOptions::default()
        };
        let mesh = polygon_ribbon(&pts, red(), &opts);
        assert_eq!(mesh.triangle_count(), 12);
    }

    #[test]
    fn polygon_ribbon_too_few_points_returns_empty() {
        // < 3 points → empty mesh; a 2-point closed loop is degenerate.
        for pts in [&[][..], &[pt(0.0, 0.0)], &[pt(0.0, 0.0), pt(10.0, 0.0)]] {
            let mesh = polygon_ribbon(pts, red(), &RibbonOptions::default());
            assert!(
                mesh.is_empty(),
                "expected empty mesh for {} points",
                pts.len()
            );
        }
    }

    #[test]
    fn polygon_ribbon_cap_setting_is_ignored() {
        // Closed polygon has no endpoints — varying `cap` must not
        // change the mesh.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(5.0, 8.66)];
        let make = |cap| {
            let opts = RibbonOptions {
                half_width: 1.0,
                cap,
                join: Join::Miter,
                ..RibbonOptions::default()
            };
            polygon_ribbon(&pts, red(), &opts).triangle_count()
        };
        let butt = make(Cap::Butt);
        assert_eq!(butt, make(Cap::Square));
        assert_eq!(butt, make(Cap::Round));
    }

    #[test]
    fn polygon_gradient_wrap_segment_closes_color_loop() {
        // Triangle with vertex colours [red, green, blue]. The wrap
        // segment (vertex 2 → vertex 0) must emit red shoulders at
        // its far end, otherwise the loop wouldn't actually close.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(5.0, 8.66)];
        let cols = [red(), green(), blue()];
        let opts = RibbonOptions {
            half_width: 1.0,
            join: Join::Miter,
            ..RibbonOptions::default()
        };
        let mesh = polygon_gradient(&pts, &cols, &opts);
        let mut counts = [0_usize; 3];
        for c in &mesh.colors {
            if *c == red() {
                counts[0] += 1;
            } else if *c == green() {
                counts[1] += 1;
            } else if *c == blue() {
                counts[2] += 1;
            }
        }
        // Each colour should appear at multiple shoulder emissions
        // (incoming AND outgoing segment at its vertex).
        assert!(counts[0] >= 2, "expected red shoulders, got {counts:?}");
        assert!(counts[1] >= 2, "expected green shoulders, got {counts:?}");
        assert!(counts[2] >= 2, "expected blue shoulders, got {counts:?}");
    }

    #[test]
    fn polygon_ribbon_full_variable_width_widens_with_width() {
        // Square loop at two width settings: the bounding box should
        // grow as the width grows. Exact equality is hard because the
        // seam-bleed shifts shoulders along the local tangent (which
        // for a square is the same axis as the bounding-box edge),
        // but the *outward* extent must still scale with width.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 10.0), pt(0.0, 10.0)];
        let opts = RibbonOptions {
            half_width: 1.0,
            join: Join::Miter,
            ..RibbonOptions::default()
        };
        let m_thin = polygon_ribbon_full(&pts, None, Some(&[1.0_f64; 4]), &opts);
        let m_thick = polygon_ribbon_full(&pts, None, Some(&[5.0_f64; 4]), &opts);
        let bb_thin = m_thin.bounding_box();
        let bb_thick = m_thick.bounding_box();
        // Outer extent grows by ~4 px on each side as w goes 1 → 5.
        assert!(
            bb_thick.x0 < bb_thin.x0 - 3.0,
            "expected thicker x0 ({}) at least 3 px outside thin x0 ({})",
            bb_thick.x0,
            bb_thin.x0,
        );
        assert!(
            bb_thick.x1 > bb_thin.x1 + 3.0,
            "expected thicker x1 ({}) at least 3 px outside thin x1 ({})",
            bb_thick.x1,
            bb_thin.x1,
        );
        assert!(bb_thick.y0 < bb_thin.y0 - 3.0);
        assert!(bb_thick.y1 > bb_thin.y1 + 3.0);
    }

    #[test]
    fn polygon_ribbon_full_per_vertex_width_changes_shoulder_offsets() {
        // Triangle with widths [1, 4, 1]. Vertex 1 (the wide one)
        // should produce shoulder pairs farther from the polyline
        // than vertex 0 or 2.
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(5.0, 8.66)];
        let widths = [1.0_f64, 4.0, 1.0];
        let opts = RibbonOptions {
            half_width: 1.0,
            join: Join::Miter,
            ..RibbonOptions::default()
        };
        let mesh = polygon_ribbon_full(&pts, None, Some(&widths), &opts);
        // Find max shoulder offset from each vertex (taking shoulder
        // as "any mesh vertex within ~3 px of the polyline vertex
        // along the polyline" is too fragile, so just measure
        // shoulder-vertex distance from polyline vertex and bucket
        // by closest polyline vertex).
        let mut max_offset = [0.0_f64; 3];
        for v in &mesh.vertices {
            let d = [
                (*v - pts[0]).hypot(),
                (*v - pts[1]).hypot(),
                (*v - pts[2]).hypot(),
            ];
            let (idx, dist) = d
                .iter()
                .enumerate()
                .min_by(|a, b| a.1.partial_cmp(b.1).unwrap())
                .unwrap();
            if *dist > max_offset[idx] {
                max_offset[idx] = *dist;
            }
        }
        // Vertex 1 (width 4) should sit further from its vertex than
        // vertices 0/2 (width 1).
        assert!(
            max_offset[1] > max_offset[0] + 2.0,
            "max shoulder offsets per vertex: {max_offset:?}",
        );
        assert!(max_offset[1] > max_offset[2] + 2.0);
    }

    #[test]
    #[should_panic(expected = "colors.len()")]
    fn polygon_gradient_panics_on_length_mismatch() {
        let pts = [pt(0.0, 0.0), pt(10.0, 0.0), pt(5.0, 8.66)];
        let cols = [red(), green()];
        let _ = polygon_gradient(&pts, &cols, &RibbonOptions::default());
    }

    // ── Quad-strip band mesh ───────────────────────────────────────

    #[test]
    fn ribbon_band_mesh_two_point_strip() {
        // Smallest case: one quad between two two-point curves.
        let a = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let b = [pt(0.0, 5.0), pt(10.0, 5.0)];
        let mesh = ribbon_band_mesh(&a, &b, &[red(); 2], &[blue(); 2]);
        assert_eq!(mesh.vertex_count(), 4);
        assert_eq!(mesh.triangle_count(), 2);
        let bb = mesh.bounding_box();
        assert!(approx(bb.x0, 0.0));
        assert!(approx(bb.x1, 10.0));
        assert!(approx(bb.y0, 0.0));
        assert!(approx(bb.y1, 5.0));
    }

    #[test]
    fn ribbon_band_mesh_quad_pair_index_pattern() {
        // Each segment must emit the canonical [base, base+1, base+2,
        // base, base+2, base+3] index pattern so the Vello quad-pair
        // detector folds it into a single quad fill.
        let a = [pt(0.0, 0.0), pt(10.0, 0.0), pt(20.0, 0.0)];
        let b = [pt(0.0, 5.0), pt(10.0, 5.0), pt(20.0, 5.0)];
        let mesh = ribbon_band_mesh(&a, &b, &[red(); 3], &[blue(); 3]);
        assert_eq!(mesh.indices.len(), 12);
        // Segment 0: 0,1,2,0,2,3
        assert_eq!(&mesh.indices[0..6], &[0, 1, 2, 0, 2, 3]);
        // Segment 1: 4,5,6,4,6,7
        assert_eq!(&mesh.indices[6..12], &[4, 5, 6, 4, 6, 7]);
    }

    #[test]
    fn ribbon_band_mesh_per_side_colors_preserved() {
        let a = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let b = [pt(0.0, 5.0), pt(10.0, 5.0)];
        let mesh = ribbon_band_mesh(&a, &b, &[red(), red()], &[blue(), blue()]);
        for (p, c) in mesh.vertices.iter().zip(mesh.colors.iter()) {
            if approx(p.y, 0.0) {
                assert_eq!(*c, red());
            } else if approx(p.y, 5.0) {
                assert_eq!(*c, blue());
            }
        }
    }

    #[test]
    fn ribbon_band_mesh_under_two_points_returns_empty() {
        let a = [pt(0.0, 0.0)];
        let b = [pt(0.0, 5.0)];
        let mesh = ribbon_band_mesh(&a, &b, &[red()], &[blue()]);
        assert!(mesh.is_empty());
    }

    #[test]
    #[should_panic(expected = "curve_a.len()")]
    fn ribbon_band_mesh_panics_on_curve_length_mismatch() {
        let a = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let b = [pt(0.0, 5.0)];
        let _ = ribbon_band_mesh(&a, &b, &[red(); 2], &[blue(); 1]);
    }

    #[test]
    #[should_panic(expected = "colors_a.len()")]
    fn ribbon_band_mesh_panics_on_colors_a_mismatch() {
        let a = [pt(0.0, 0.0), pt(10.0, 0.0)];
        let b = [pt(0.0, 5.0), pt(10.0, 5.0)];
        let _ = ribbon_band_mesh(&a, &b, &[red()], &[blue(); 2]);
    }
}