File: pattern.py

package info (click to toggle)
fpdf2 2.8.7-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 114,352 kB
  • sloc: python: 50,410; sh: 133; makefile: 12
file content (1547 lines) | stat: -rw-r--r-- 56,287 bytes parent folder | download
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
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
"""
Handles the creation of patterns and gradients

Usage documentation at: <https://py-pdf.github.io/fpdf2/Patterns.html>
"""

import math
import struct
from abc import ABC
from typing import TYPE_CHECKING, Optional, Sequence, Union

from .drawing_primitives import (
    Color,
    ColorClass,
    ColorInput,
    DeviceCMYK,
    DeviceGray,
    DeviceRGB,
    Transform,
    convert_to_device_color,
)
from .enums import GradientSpreadMethod
from .syntax import Name, PDFArray, PDFContentStream, PDFObject
from .util import FloatTolerance, NumberClass, format_number

if TYPE_CHECKING:
    from .drawing import BoundingBox


def lerp(a: float, b: float, t: float) -> float:
    return a + (b - a) * t


def lerp_tuple(
    a: tuple[float, ...], b: tuple[float, ...], t: float
) -> tuple[float, ...]:
    if len(a) != len(b):
        raise ValueError("Mismatched color component counts")
    return tuple(lerp(a[i], b[i], t) for i in range(len(a)))


def pick_colorspace_and_promote(colors: list[Color]) -> tuple[str, list[Color]]:
    kinds = {type(c).__name__ for c in colors}
    if "DeviceCMYK" in kinds and len(kinds) > 1:
        raise ValueError("Can't mix CMYK with other color spaces.")
    if kinds == {"DeviceGray", "DeviceRGB"}:
        # promote Gray -> RGB
        promoted: list[Color] = [
            DeviceRGB(c.g, c.g, c.g) if isinstance(c, DeviceGray) else c for c in colors
        ]
        return "DeviceRGB", promoted
    if kinds == {"DeviceGray"}:
        return "DeviceGray", colors
    if kinds == {"DeviceRGB"}:
        return "DeviceRGB", colors
    return "DeviceRGB", colors


def normalize_stops(
    stops: Sequence[tuple[float, Union[Color, str]]],
    coerce_to_device: bool = True,
    *,
    return_raw: bool = False,
) -> tuple[str, list[tuple[float, Color]], Optional[list[tuple[float, Color]]]]:
    """
    Clamp/sort/merge, ensure endpoints at 0 and 1, coerce to single Device* colorspace.

    When ``return_raw`` is true, also returns a list of the original stop positions
    (prior to clamping to [0,1]) converted to the same device colorspace. The raw
    offsets are sorted and merged (last stop wins for near-duplicates) but no
    implicit 0/1 endpoints are synthesized.
    """

    if not stops:
        raise ValueError("At least one stop is required")

    raw_entries: list[tuple[float, Color]] = []
    for off, col in stops:
        raw_u = float(off)
        c = (
            convert_to_device_color(col)
            if (coerce_to_device and not hasattr(col, "colors"))
            else col
        )
        raw_entries.append((raw_u, c))  # type: ignore[arg-type]
    raw_entries.sort(key=lambda t: t[0])

    merged_raw: list[tuple[float, Color]] = []
    for raw_u, color in raw_entries:
        if merged_raw and FloatTolerance.equal(merged_raw[-1][0], raw_u):
            merged_raw[-1] = (raw_u, color)
        else:
            merged_raw.append((raw_u, color))

    def _lerp_color(c0: Color, c1: Color, t: float) -> Color:
        comps0 = c0.colors
        comps1 = c1.colors
        blended = lerp_tuple(comps0, comps1, t)
        a0 = getattr(c0, "a", None)
        a1 = getattr(c1, "a", None)
        alpha = None
        if a0 is not None or a1 is not None:
            alpha = lerp(
                1.0 if a0 is None else float(a0), 1.0 if a1 is None else float(a1), t
            )

        if isinstance(c0, DeviceGray):
            return DeviceGray(blended[0], alpha)
        if isinstance(c0, DeviceRGB):
            return DeviceRGB(blended[0], blended[1], blended[2], alpha)
        if isinstance(c0, DeviceCMYK):
            return DeviceCMYK(blended[0], blended[1], blended[2], blended[3], alpha)
        return c0

    def _ensure_stop(target: float) -> None:
        if not merged_raw:
            return
        if FloatTolerance.less_than(
            target, merged_raw[0][0]
        ) or FloatTolerance.greater_than(target, merged_raw[-1][0]):
            return
        for u, _ in merged_raw:
            if FloatTolerance.equal(u, target):
                return
        for idx in range(1, len(merged_raw)):
            u0, c0 = merged_raw[idx - 1]
            u1, c1 = merged_raw[idx]
            if FloatTolerance.greater_equal(target, u0) and FloatTolerance.less_equal(
                target, u1
            ):
                span = max(u1 - u0, FloatTolerance.TOLERANCE)
                t = (target - u0) / span
                merged_raw.insert(idx, (target, _lerp_color(c0, c1, t)))
                return

    _ensure_stop(0.0)
    _ensure_stop(1.0)

    clamped_entries: list[tuple[float, Color]] = []
    for raw_u, color in merged_raw:
        if raw_u < 0.0:
            u = 0.0
        elif raw_u > 1.0:
            u = 1.0
        else:
            u = raw_u
        clamped_entries.append((u, color))

    clamped_entries.sort(key=lambda t: t[0])

    merged_clamped: list[tuple[float, Color]] = []
    for u, color in clamped_entries:
        if merged_clamped and FloatTolerance.equal(merged_clamped[-1][0], u):
            merged_clamped[-1] = (u, color)
        else:
            merged_clamped.append((u, color))

    if len(merged_clamped) == 1:
        u, color = merged_clamped[0]
        merged_clamped = [(0.0, color), (1.0, color)]
    else:
        if not FloatTolerance.is_zero(merged_clamped[0][0]):
            merged_clamped.insert(0, (0.0, merged_clamped[0][1]))
        else:
            merged_clamped[0] = (0.0, merged_clamped[0][1])
        if not FloatTolerance.equal(merged_clamped[-1][0], 1.0):
            merged_clamped.append((1.0, merged_clamped[-1][1]))
        else:
            merged_clamped[-1] = (1.0, merged_clamped[-1][1])

    space_name, palette = pick_colorspace_and_promote([c for _, c in merged_clamped])
    normalized = [(u, p) for (u, _), p in zip(merged_clamped, palette)]

    if not return_raw:
        return space_name, normalized, None

    def promote_raw(color: Color) -> Color:
        if space_name == "DeviceGray":
            if isinstance(color, DeviceGray):
                return color
            if isinstance(color, DeviceRGB):
                return color.to_gray()
            if isinstance(color, DeviceCMYK):
                raise ValueError("Can't mix CMYK with non-CMYK gradients")
        if space_name == "DeviceRGB":
            if isinstance(color, DeviceRGB):
                return color
            if isinstance(color, DeviceGray):
                return DeviceRGB(color.g, color.g, color.g)
        return color

    raw_promoted = [(u, promote_raw(color)) for (u, color) in merged_raw]
    return space_name, normalized, raw_promoted


def merge_near_duplicates(
    pairs: Sequence[tuple[float, Union[Color, str]]],
) -> Sequence[tuple[float, Union[Color, str]]]:
    out: list[tuple[float, Union[Color, str]]] = []
    for u, col in pairs:
        if out and FloatTolerance.equal(out[-1][0], u):
            prev_u, prev_col = out[-1]
            if prev_col == col:
                # identical color: keep the newest sample
                out[-1] = (u, col)
                continue

            step = max(FloatTolerance.TOLERANCE * 10, 1e-6)
            nudged_prev = prev_u - step
            if FloatTolerance.greater_equal(nudged_prev, 0.0):
                out[-1] = (nudged_prev, prev_col)
                out.append((u, col))
            else:
                nudged = u + step
                if nudged > 1.0:
                    nudged = 1.0
                    out[-1] = (max(0.0, min(prev_u, nudged - step)), prev_col)
                else:
                    out[-1] = (prev_u, prev_col)
                out.append((nudged, col))
        else:
            out.append((u, col))
    return out


def spread_map(u: float, method: GradientSpreadMethod) -> float:
    """Map u∈R -> [0,1] via PAD/REPEAT/REFLECT."""
    if method == GradientSpreadMethod.PAD:
        return 0.0 if u < 0.0 else 1.0 if u > 1.0 else u
    if method == GradientSpreadMethod.REPEAT:
        return u - math.floor(u)
    # REFLECT: triangle wave
    v = u % 2.0
    return v if v <= 1.0 else 2.0 - v


def sample_stops(stops01: list[tuple[float, Color]], u: float) -> tuple[float, ...]:
    """Piecewise-linear sampling in [0,1]. Assumes normalized/sorted stops incl. endpoints."""
    for i in range(1, len(stops01)):
        u1, c1 = stops01[i]
        if FloatTolerance.less_equal(u, u1):
            u0, c0 = stops01[i - 1]
            span = max(u1 - u0, FloatTolerance.TOLERANCE)
            t = (u - u0) / span
            return lerp_tuple(c0.colors, c1.colors, t)
    return stops01[-1][1].colors


def extract_alpha_stops(
    stops01: list[tuple[float, Color]],
) -> list[tuple[float, float]]:
    """Return [(u, a)] with a∈[0,1]; missing alpha => 1.0."""
    out: list[tuple[float, float]] = []
    for u, c in stops01:
        a = getattr(c, "a", None)
        out.append((u, 1.0 if a is None else float(a)))
    return out


class Pattern(PDFObject):
    """
    Represents a PDF Pattern object.

    Currently, this class supports only "shading patterns" (pattern_type 2),
    using either a linear or radial gradient. Tiling patterns (pattern_type 1)
    are not yet implemented.
    """

    def __init__(self, shading: Union["Gradient", "Shading", "MeshShading"]):
        super().__init__()
        self.type = Name("Pattern")
        # 1 for a tiling pattern or type 2 for a shading pattern:
        self.pattern_type = 2
        self._shading = shading
        self._matrix = Transform.identity()
        # If True (default), OutputProducer will bake the page CTM into this pattern.
        # For patterns used inside Form XObjects (e.g., soft masks), set to False.
        self._apply_page_ctm = True

    @property
    def shading(self) -> str:
        return f"{self._shading.get_shading_object().id} 0 R"

    @property
    def matrix(self) -> str:
        return (
            f"[{format_number(self._matrix.a)} {format_number(self._matrix.b)} "
            f"{format_number(self._matrix.c)} {format_number(self._matrix.d)} "
            f"{format_number(self._matrix.e)} {format_number(self._matrix.f)}]"
        )

    def set_matrix(self, matrix: Transform) -> "Pattern":
        self._matrix = matrix
        return self

    def get_matrix(self) -> Transform:
        return self._matrix

    def set_apply_page_ctm(self, apply: bool) -> None:
        self._apply_page_ctm = apply

    def get_apply_page_ctm(self) -> bool:
        return self._apply_page_ctm


class Type2Function(PDFObject):
    """Transition between 2 colors"""

    def __init__(self, color_1: Color, color_2: Color):
        super().__init__()
        # 0: Sampled function; 2: Exponential interpolation function; 3: Stitching function; 4: PostScript calculator function
        self.function_type = 2
        self.domain = "[0 1]"
        c1 = self._get_color_components(color_1)
        c2 = self._get_color_components(color_2)
        if len(c1) != len(c2):
            raise ValueError("Type2Function endpoints must have same component count")
        self.c0 = f'[{" ".join(format_number(c) for c in c1)}]'
        self.c1 = f'[{" ".join(format_number(c) for c in c2)}]'
        self.n = 1

    @classmethod
    def _get_color_components(cls, color: Color) -> tuple[float, ...]:
        if isinstance(color, DeviceGray):
            return (color.g,)
        return color.colors


class Type2FunctionGray(PDFObject):
    """1‑channel exponential interpolation for alpha/luminance ramps."""

    def __init__(self, g0: float, g1: float):
        super().__init__()
        self.function_type = 2
        self.domain = "[0 1]"
        self.c0 = f"[{format_number(g0)}]"
        self.c1 = f"[{format_number(g1)}]"
        self.n = 1


class Type3Function(PDFObject):
    """When multiple colors are used, a type 3 function is necessary to stitch type 2 functions together
    and define the bounds between each color transition"""

    def __init__(
        self,
        functions: Sequence[Union[Type2Function, Type2FunctionGray, "Type3Function"]],
        bounds: Sequence[float],
    ):
        super().__init__()
        # 0: Sampled function; 2: Exponential interpolation function; 3: Stitching function; 4: PostScript calculator function
        self.function_type = 3
        self.domain = "[0 1]"
        self._functions = functions
        self.bounds = f"[{' '.join(format_number(bound) for bound in bounds)}]"
        self.encode = f"[{' '.join('0 1' for _ in functions)}]"

    @property
    def functions(self) -> str:
        return f"[{' '.join(f'{f.id} 0 R' for f in self._functions)}]"


class Shading(PDFObject):
    def __init__(
        self,
        shading_type: int,  # 2 for axial shading, 3 for radial shading
        background: Optional[Color],
        color_space: str,
        coords: Sequence[float] | str,
        functions: Sequence[Type2Function | Type2FunctionGray | Type3Function],
        extend_before: bool,
        extend_after: bool,
    ):
        super().__init__()
        self.shading_type = shading_type
        self.background = (
            f'[{" ".join(format_number(c) for c in background.colors)}]'
            if background
            else None
        )
        self.color_space = Name(color_space)
        self.coords = coords
        self._functions = functions
        self.extend = f'[{"true" if extend_before else "false"} {"true" if extend_after else "false"}]'
        self.anti_alias = True

    @property
    def function(self) -> str:
        """Reference to the *top-level* function object for the shading dictionary."""
        return f"{self._functions[-1].id} 0 R"

    def get_functions(
        self,
    ) -> Sequence[Type2Function | Type2FunctionGray | Type3Function]:
        """All function objects used by this shading (Type2 segments + final Type3)."""
        return self._functions

    def get_shading_object(self) -> "Shading":
        """Return self, as this is already a shading object."""
        return self


class Gradient(ABC):
    def __init__(
        self,
        colors: Sequence[ColorInput],
        background: Optional[ColorInput],
        extend_before: bool,
        extend_after: bool,
        bounds: Optional[Sequence[float]],
    ):
        self.color_space, self.colors, self._alphas = self._convert_colors(colors)
        self.background = None
        if background:
            bg = (
                convert_to_device_color(background)
                if isinstance(background, (str, *ColorClass, *NumberClass))
                else convert_to_device_color(*background)
            )
            # Re-map background to the chosen palette colorspace
            if self.color_space == "DeviceGray":
                if isinstance(bg, DeviceRGB):
                    bg = bg.to_gray()
                elif isinstance(bg, DeviceCMYK):
                    raise ValueError("Can't mix CMYK background with non-CMYK gradient")
            elif self.color_space == "DeviceRGB":
                if isinstance(bg, DeviceGray):
                    bg = DeviceRGB(bg.g, bg.g, bg.g)
                elif isinstance(bg, DeviceCMYK):
                    raise ValueError("Can't mix CMYK background with non-CMYK gradient")
            self.background = bg
        self.extend_before = extend_before
        self.extend_after = extend_after
        self.bounds = (
            bounds
            if bounds
            else [(i + 1) / (len(self.colors) - 1) for i in range(len(self.colors) - 2)]
        )
        if len(self.bounds) != len(self.colors) - 2:
            raise ValueError(
                "Bounds array length must be two less than the number of colors"
            )
        self.functions = self._generate_functions()
        self.pattern = Pattern(self)
        self._shading_object: Optional[Shading] = None
        self._alpha_shading_object: Optional[Shading] = None
        self.coords: Optional[Sequence[float]] = None
        self.shading_type = 0
        self.raw_stops: Optional[list[tuple[float, Color]]] = None

    @classmethod
    def _convert_colors(
        cls, colors: Sequence[ColorInput]
    ) -> tuple[str, list[Color], list[float]]:
        """Normalize colors to a single device colorspace and capture per-stop alpha (default 1.0)."""
        if len(colors) < 2:
            raise ValueError("A gradient must have at least two colors")

        # 1) Convert everything to Device* instances
        palette: list[Color] = []
        spaces: set[str] = set()
        alphas: list[float] = []
        for color in colors:
            dc = (
                convert_to_device_color(color)
                if isinstance(color, (str, *ColorClass, *NumberClass))
                else convert_to_device_color(*color)
            )
            palette.append(dc)
            spaces.add(type(dc).__name__)
            a = getattr(dc, "a", None)
            alphas.append(float(a) if a is not None else 1.0)

        # 2) Disallow any CMYK mixture with others
        if "DeviceCMYK" in spaces and len(spaces) > 1:
            raise ValueError("Can't mix CMYK with other color spaces.")

        # 3) If we ended up with plain CMYK, we're done
        if spaces == {"DeviceCMYK"}:
            return "DeviceCMYK", palette, alphas

        # 4) Promote mix of Gray+RGB to RGB
        if spaces == {"DeviceGray", "DeviceRGB"}:
            promoted: list[Color] = []
            for c in palette:
                if isinstance(c, DeviceGray):
                    promoted.append(DeviceRGB(c.g, c.g, c.g))
                else:
                    assert isinstance(c, DeviceRGB)
                    promoted.append(c)
            return "DeviceRGB", promoted, alphas

        # 5) All Gray: stay Gray
        if spaces == {"DeviceGray"}:
            return "DeviceGray", palette, alphas

        # 6) All RGB: optionally downcast to Gray if all are achromatic
        if spaces == {"DeviceRGB"}:
            # changing palette to typed list to please mypy
            rgb_palette: list[DeviceRGB] = [
                c for c in palette if isinstance(c, DeviceRGB)
            ]
            if all(c.is_achromatic() for c in rgb_palette):
                return "DeviceGray", [c.to_gray() for c in rgb_palette], alphas
            return "DeviceRGB", palette, alphas

        # Fallback: default to RGB
        return "DeviceRGB", palette, alphas

    def _generate_functions(
        self,
    ) -> list[Type2Function | Type2FunctionGray | Type3Function]:
        if len(self.colors) < 2:
            raise ValueError("A gradient must have at least two colors")
        if len(self.colors) == 2:
            return [Type2Function(self.colors[0], self.colors[1])]
        number_of_colors = len(self.colors)
        functions: list[Type2Function | Type2FunctionGray | Type3Function] = []
        for i in range(number_of_colors - 1):
            functions.append(Type2Function(self.colors[i], self.colors[i + 1]))
        functions.append(Type3Function(functions[:], self.bounds))
        return functions

    def get_functions(self) -> list[Type2Function | Type2FunctionGray | Type3Function]:
        return self.functions

    def get_shading_object(self) -> "Shading":
        if not self._shading_object:
            coords = (
                ""
                if self.coords is None
                else PDFArray(
                    [
                        (
                            format_number(value)
                            if isinstance(value, (int, float))
                            else value
                        )
                        for value in self.coords
                    ]
                ).serialize()
            )
            self._shading_object = Shading(
                shading_type=self.shading_type,
                background=self.background,
                color_space=self.color_space,
                coords=coords,
                functions=self.functions,
                extend_before=self.extend_before,
                extend_after=self.extend_after,
            )
        return self._shading_object

    def get_pattern(self) -> Pattern:
        return self.pattern

    def has_alpha(self) -> bool:
        """True if any stop carries alpha != 1.0."""
        return any(not FloatTolerance.equal(a, 1.0) for a in self._alphas)

    def _generate_alpha_functions(
        self,
    ) -> Sequence[Type2Function | Type2FunctionGray | Type3Function]:
        """Stitched Type2 gray functions mirroring the color ramp bounds."""
        if len(self._alphas) < 2:
            raise ValueError("Alpha ramp requires at least two stops")
        if len(self._alphas) == 2:
            return [Type2FunctionGray(self._alphas[0], self._alphas[1])]
        functions: list[Type2FunctionGray | Type3Function] = []
        for i in range(len(self._alphas) - 1):
            functions.append(Type2FunctionGray(self._alphas[i], self._alphas[i + 1]))
        functions.append(Type3Function(functions[:], self.bounds))
        return functions

    def get_alpha_shading_object(
        self, _: Optional["BoundingBox"] = None
    ) -> Optional["Shading"]:
        """Grayscale Shading object representing the alpha ramp (for a soft mask)."""
        if not self.has_alpha():
            return None
        if not self._alpha_shading_object:
            if (
                self.coords is not None
                and isinstance(self.coords, (list, tuple))
                and len(self.coords) > 1
            ):
                coords = PDFArray(self.coords).serialize()
            else:
                coords = ""
            self._alpha_shading_object = Shading(
                shading_type=self.shading_type,
                background=None,  # mask content should be pure coverage, no bg
                color_space="DeviceGray",
                coords=coords,
                functions=self._generate_alpha_functions(),
                extend_before=self.extend_before,
                extend_after=self.extend_after,
            )
        return self._alpha_shading_object


class LinearGradient(Gradient):
    def __init__(
        self,
        from_x: float,
        from_y: float,
        to_x: float,
        to_y: float,
        colors: Sequence[ColorInput],
        background: Optional[ColorInput] = None,
        extend_before: bool = False,
        extend_after: bool = False,
        bounds: Optional[list[float]] = None,
    ):
        """
        A shading pattern that creates a linear (axial) gradient in a PDF.

        The gradient is defined by two points: (from_x, from_y) and (to_x, to_y),
        along which the specified colors are interpolated. Optionally, you can set
        a background color, extend the gradient beyond its start or end, and
        specify custom color stop positions via `bounds`.

        Args:
            from_x (int or float): The x-coordinate of the starting point of the gradient,
                in user space units.
            from_y (int or float): The y-coordinate of the starting point of the gradient,
                in user space units.
            to_x (int or float): The x-coordinate of the ending point of the gradient,
                in user space units.
            to_y (int or float): The y-coordinate of the ending point of the gradient,
                in user space units.
            colors (list[str or tuple[int, int, int]]): A list of colors along which the gradient
                will be interpolated. Colors may be given as hex strings (e.g., "#FF0000") or
                (R, G, B) tuples.
            background (str or tuple[int, int, int], optional): A background color to use
                if the gradient does not fully cover the region it is applied to.
                Defaults to None (no background).
            extend_before (bool, optional): Whether to extend the first color beyond the
                starting point (from_x, from_y). Defaults to False.
            extend_after (bool, optional): Whether to extend the last color beyond the
                ending point (to_x, to_y). Defaults to False.
            bounds (list[float], optional): An optional list of floats in the range (0, 1)
                that represent gradient stops for color transitions. The number of bounds
                should be two less than the number of colors (for multi-color gradients).
                Defaults to None, which evenly distributes color stops.
        """
        super().__init__(colors, background, extend_before, extend_after, bounds)
        self.coords: tuple[  # pyright: ignore[reportIncompatibleVariableOverride]
            float, float, float, float
        ] = (
            from_x,
            from_y,
            to_x,
            to_y,
        )
        self.shading_type = 2


class RadialGradient(Gradient):
    def __init__(
        self,
        start_circle_x: float,
        start_circle_y: float,
        start_circle_radius: float,
        end_circle_x: float,
        end_circle_y: float,
        end_circle_radius: float,
        colors: Sequence[ColorInput],
        background: Optional[ColorInput] = None,
        extend_before: bool = False,
        extend_after: bool = False,
        bounds: Optional[list[float]] = None,
    ):
        """
        A shading pattern that creates a radial (or circular/elliptical) gradient in a PDF.

        The gradient is defined by two circles (start and end). Colors are blended from the
        start circle to the end circle, forming a radial gradient. You can optionally set a
        background color, extend the gradient beyond its circles, and provide custom color
        stop positions via `bounds`.

        Args:
            start_circle_x (int or float): The x-coordinate of the inner circle's center,
                in user space units.
            start_circle_y (int or float): The y-coordinate of the inner circle's center,
                in user space units.
            start_circle_radius (int or float): The radius of the inner circle, in user space units.
            end_circle_x (int or float): The x-coordinate of the outer circle's center,
                in user space units.
            end_circle_y (int or float): The y-coordinate of the outer circle's center,
                in user space units.
            end_circle_radius (int or float): The radius of the outer circle, in user space units.
            colors (list[str or tuple[int, int, int]]): A list of colors along which the gradient
                will be interpolated. Colors may be given as hex strings (e.g., "#FF0000") or
                (R, G, B) tuples.
            background (str or tuple[int, int, int], optional): A background color to display
                if the gradient does not fully cover the region it's applied to. Defaults to None
                (no background).
            extend_before (bool, optional): Whether to extend the gradient beyond the start circle.
                Defaults to False.
            extend_after (bool, optional): Whether to extend the gradient beyond the end circle.
                Defaults to False.
            bounds (list[float], optional): An optional list of floats in the range (0, 1) that
                represent gradient stops for color transitions. The number of bounds should be one
                less than the number of colors (for multi-color gradients). Defaults to None,
                which evenly distributes color stops.
        """
        super().__init__(colors, background, extend_before, extend_after, bounds)
        self.coords: tuple[  # pyright: ignore[reportIncompatibleVariableOverride]
            float, float, float, float, float, float
        ] = (
            start_circle_x,
            start_circle_y,
            start_circle_radius,
            end_circle_x,
            end_circle_y,
            end_circle_radius,
        )
        self.shading_type = 3


class MeshShading(PDFContentStream):
    """
    PDF Shading type 4 (free-form Gouraud triangle mesh) with per-vertex colors.
    """

    def __init__(
        self,
        *,
        color_space: str,
        bbox: "BoundingBox",
        comp_count: int,
        triangles: list[
            tuple[tuple[float, float], tuple[float, float], tuple[float, float]]
        ],
        colors: list[tuple[tuple[float, ...], tuple[float, ...], tuple[float, ...]]],
        background: Optional["Color"] = None,
        anti_alias: bool = True,
    ):
        self.type = Name("Shading")
        self.shading_type = 4
        self.color_space = Name(color_space)
        self.background = (
            f'[{" ".join(format_number(c) for c in background.colors)}]'
            if background
            else None
        )
        self._bbox = bbox
        self._triangles = triangles
        self._triangle_colors = colors
        self.anti_alias = anti_alias
        self._comp_count = comp_count

        # Fixed bit depths (simple encoder): use 16-bit components to reduce banding
        self.bits_per_coordinate = 16
        self.bits_per_component = 16
        self.bits_per_flag = 8

        # Decode = [xmin xmax ymin ymax  0 1 (per component)]
        decode_values = [
            bbox.x0,
            bbox.x1,
            bbox.y0,
            bbox.y1,
            *([0.0, 1.0] * comp_count),
        ]
        self.decode = PDFArray([format_number(value) for value in decode_values])

        super().__init__(contents=self._encode_stream_raw(), compress=True)

    # Let Pattern() accept MeshShading like other shadings
    def get_shading_object(self) -> "MeshShading":
        return self

    def _encode_stream_raw(self) -> bytes:
        xmin, xmax = self._bbox.x0, self._bbox.x1
        ymin, ymax = self._bbox.y0, self._bbox.y1
        maxc = (1 << self.bits_per_coordinate) - 1
        sx = maxc / max(xmax - xmin, FloatTolerance.TOLERANCE)
        sy = maxc / max(ymax - ymin, FloatTolerance.TOLERANCE)
        max_comp = (1 << self.bits_per_component) - 1

        def q16(u: float, umin: float, scale: float) -> int:
            ui = int(round((u - umin) * scale))
            return 0 if ui < 0 else maxc if ui > maxc else ui

        def q_component(v: float) -> int:
            iv = int(round(float(v) * max_comp))
            return 0 if iv < 0 else max_comp if iv > max_comp else iv

        comp_fmt = "H" if self.bits_per_component > 8 else "B"
        vertex_fmt = ">BHH" + (comp_fmt * self._comp_count)
        out = bytearray()
        for (v0, v1, v2), (c0, c1, c2) in zip(self._triangles, self._triangle_colors):
            for (x, y), comps in ((v0, c0), (v1, c1), (v2, c2)):
                component_bytes = [
                    q_component(comps[i]) if i < len(comps) else 0
                    for i in range(self._comp_count)
                ]
                out += struct.pack(
                    vertex_fmt,
                    0,  # flag = 0 (no reuse)
                    q16(x, xmin, sx),  # x
                    q16(y, ymin, sy),  # y
                    *component_bytes,
                )
        return bytes(out)

    @classmethod
    def get_functions(
        cls,
    ) -> Sequence[Type2Function | Type2FunctionGray | Type3Function]:
        """Type-4 mesh shadings don't use Function objects; return empty list for output."""
        return []


class SweepGradient(PDFObject):
    """
    Conic/sweep gradient that materializes as a type-4 (mesh) Shading.
    Build is bbox-dependent, so we create the shading lazily at emit time.
    """

    __slots__ = (
        "cx",
        "cy",
        "start_angle",
        "end_angle",
        "stops",
        "spread_method",
        "segments",
        "inner_radius_factor",
        "_cached_key",
        "_shading",
        "_alpha_shading",
    )

    def __init__(
        self,
        cx: float,
        cy: float,
        start_angle: float,
        end_angle: float,
        stops: Sequence[tuple[float, Union[Color, str]]],
        spread_method: Union["GradientSpreadMethod", str] = GradientSpreadMethod.PAD,
        segments: Optional[int] = None,
        inner_radius_factor: float = 0.002,
    ):
        super().__init__()
        self.cx, self.cy = float(cx), float(cy)
        self.start_angle, self.end_angle = float(start_angle), float(end_angle)
        self.stops = stops
        self.spread_method = (
            GradientSpreadMethod.coerce(spread_method)
            if hasattr(GradientSpreadMethod, "coerce")
            else GradientSpreadMethod(spread_method)
        )
        self.segments = segments
        self.inner_radius_factor = inner_radius_factor
        self._cached_key: Optional[
            tuple[
                float,
                float,
                float,
                float,
                float,
                float,
                float,
                float,
                Optional[int],
                float,
                str,
            ]
        ] = None
        self._shading: Optional[MeshShading] = None
        self._alpha_shading: Optional[MeshShading] = None

    def has_alpha(self) -> bool:
        # any stop carries alpha != 1
        for _, c in self.stops:
            dc = convert_to_device_color(c) if not hasattr(c, "colors") else c
            a = getattr(dc, "a", None)
            if a is not None and not FloatTolerance.equal(float(a), 1.0):
                return True
        return False

    def get_shading_object(self, bbox: "BoundingBox") -> "MeshShading":
        key = (
            bbox.x0,
            bbox.y0,
            bbox.x1,
            bbox.y1,
            self.cx,
            self.cy,
            self.start_angle,
            self.end_angle,
            self.segments,
            self.inner_radius_factor,
            self.spread_method.value,
        )
        if self._shading is not None and self._cached_key == key:
            return self._shading
        self._cached_key = key
        self._shading = shape_sweep_gradient_as_mesh(
            self.cx,
            self.cy,
            self.start_angle,
            self.end_angle,
            self.stops,
            spread_method=self.spread_method,
            bbox=bbox,
            segments=self.segments,
            inner_radius_factor=self.inner_radius_factor,
        )
        return self._shading

    def get_alpha_shading_object(self, bbox: "BoundingBox") -> Optional["MeshShading"]:
        if not self.has_alpha():
            return None

        # Normalize color stops once, then extract alpha
        _, stops01, _ = normalize_stops(self.stops)
        alpha01 = extract_alpha_stops(stops01)
        gray_stops: list[tuple[float, Color | str]] = [
            (u, DeviceGray(a)) for (u, a) in alpha01
        ]

        key = (
            "alpha",
            bbox.x0,
            bbox.y0,
            bbox.x1,
            bbox.y1,
            self.cx,
            self.cy,
            self.start_angle,
            self.end_angle,
            self.segments,
            self.inner_radius_factor,
            self.spread_method.value,
        )

        if getattr(self, "_alpha_cached_key", None) == key:
            return self._alpha_shading

        self._alpha_shading = shape_sweep_gradient_as_mesh(
            self.cx,
            self.cy,
            self.start_angle,
            self.end_angle,
            gray_stops,
            spread_method=self.spread_method,
            bbox=bbox,
            segments=self.segments,
            inner_radius_factor=self.inner_radius_factor,
        )
        self._alpha_cached_key = key
        return self._alpha_shading


def shape_sweep_gradient_as_mesh(
    cx: float,
    cy: float,
    start_angle: float,
    end_angle: float,
    stops: Sequence[tuple[float, Union[Color, str]]],
    spread_method: GradientSpreadMethod,
    bbox: "BoundingBox",
    segments: Optional[int] = None,
    inner_radius_factor: float = 0.002,
) -> MeshShading:
    """
    Approximate a sweep (conic) gradient as a Type 4 mesh (triangles).
    We build a full 0..2π fan so PAD/REPEAT/REFLECT outside [0,1] are respected.
    Angles are expected in radians.
    """
    _, norm_stops, _ = normalize_stops(stops)
    first_c = norm_stops[0][1]
    if isinstance(first_c, DeviceGray):
        color_space = "DeviceGray"
        comp_count = 1
    elif isinstance(first_c, DeviceRGB):
        color_space = "DeviceRGB"
        comp_count = 3
    else:
        color_space = "DeviceCMYK"
        comp_count = 4

    tau = 2.0 * math.pi
    delta = end_angle - start_angle
    if FloatTolerance.is_zero(delta):
        delta = tau

    if delta < 0.0:
        start_angle, end_angle = end_angle, start_angle
        norm_stops = [(1.0 - u, c) for (u, c) in norm_stops]
        norm_stops.sort(key=lambda t: t[0])
        delta = -delta

    span = delta if FloatTolerance.greater_than(delta, 0.0) else tau
    cover_span = max(span, tau)

    if segments is None:
        base_segments = max(1024, len(norm_stops) * 96)
    else:
        base_segments = max(16, segments)
    max_angle = cover_span / float(base_segments)
    max_angle = max(min(max_angle, math.pi / 2.0), math.pi / 360.0)

    r_outer = bbox.max_distance_to_point(cx, cy)
    r_inner = max(
        min(bbox.width, bbox.height) * float(inner_radius_factor),
        FloatTolerance.TOLERANCE,
    )

    start_mod = math.fmod(start_angle, tau)
    if start_mod < 0.0:
        start_mod += tau
    end_mod = math.fmod(start_mod + span, tau)
    if end_mod < 0.0:
        end_mod += tau
    wraps = FloatTolerance.less_than(span, tau) and end_mod < start_mod
    span_covers_full_circle = FloatTolerance.greater_equal(span, tau)
    seam_progress = (tau - start_mod) % tau
    if FloatTolerance.less_equal(seam_progress, 0.0):
        seam_progress = cover_span

    progress_candidates: list[float] = [0.0]
    tile_count = int(math.floor(cover_span / span))
    remainder = cover_span - tile_count * span
    if FloatTolerance.less_equal(remainder, 0.0):
        remainder = 0.0

    for tile in range(tile_count):
        base_progress = tile * span
        for u, _ in norm_stops:
            progress_candidates.append(base_progress + u * span)

    if remainder > 0.0:
        portion = remainder / span
        base_progress = tile_count * span
        for u, _ in norm_stops:
            if FloatTolerance.greater_than(u, portion):
                break
            progress_candidates.append(base_progress + u * span)
        progress_candidates.append(cover_span)
    else:
        progress_candidates.append(cover_span)

    if spread_method == GradientSpreadMethod.PAD and not span_covers_full_circle:
        tail_length = max(cover_span - span, 0.0)
        if FloatTolerance.greater_than(
            seam_progress, 0.0
        ) and FloatTolerance.less_equal(seam_progress, cover_span):
            progress_candidates.append(seam_progress)
        if (
            FloatTolerance.greater_than(tail_length, 0.0)
            and FloatTolerance.less_than(seam_progress, cover_span)
            and FloatTolerance.greater_than(seam_progress, span)
        ):
            seam_eps = min(
                max(span * 0.01, FloatTolerance.TOLERANCE),
                seam_progress - span - FloatTolerance.TOLERANCE,
                cover_span - seam_progress - FloatTolerance.TOLERANCE,
            )
            if FloatTolerance.greater_than(seam_eps, 0.0):
                progress_candidates.append(seam_progress - seam_eps)

    progress_candidates.sort()
    progress_nodes: list[float] = []
    for progress in progress_candidates:
        if progress_nodes and FloatTolerance.equal(progress, progress_nodes[-1]):
            progress_nodes[-1] = progress
        else:
            progress_nodes.append(progress)

    if not progress_nodes:
        progress_nodes = [0.0, cover_span]
    elif len(progress_nodes) == 1:
        progress_nodes.append(progress_nodes[0] + cover_span)

    span_plus = start_mod + span
    crosses_360 = FloatTolerance.greater_than(span_plus, tau)
    limit_theta = start_angle + seam_progress

    # pylint: disable=too-many-return-statements
    def raw_from_progress(progress: float) -> float:
        if FloatTolerance.less_equal(span, 0.0):
            return 0.0

        theta = start_angle + progress

        if FloatTolerance.greater_equal(progress, cover_span):
            if (
                spread_method == GradientSpreadMethod.PAD
                and not span_covers_full_circle
                and FloatTolerance.greater_than(cover_span, span)
            ):
                return 0.0
            return 1.0

        if spread_method == GradientSpreadMethod.PAD:
            if span_covers_full_circle:
                return (
                    progress / span if FloatTolerance.greater_than(span, 0.0) else 0.0
                )

            if not crosses_360:
                angle_mod = math.fmod(theta, tau)
                if angle_mod < 0.0:
                    angle_mod += tau
                end_limit = start_mod + span
                if FloatTolerance.less_than(angle_mod, start_mod):
                    return 0.0
                if FloatTolerance.less_equal(angle_mod, end_limit):
                    return (angle_mod - start_mod) / span
                return 0.0

            # crosses 360°: only sample up to the seam (start -> 360°)
            visible = max(seam_progress, FloatTolerance.TOLERANCE)
            if FloatTolerance.less_equal(progress, visible):
                return progress / visible
            return 0.0

        return progress / span

    fan_line_raw: list[tuple[float, float, tuple[float, ...]]] = []
    for progress in progress_nodes:
        if (
            FloatTolerance.greater_equal(progress, cover_span)
            and not span_covers_full_circle
            and FloatTolerance.greater_than(cover_span, span)
            and spread_method != GradientSpreadMethod.PAD
        ):
            continue
        theta = start_angle + progress
        raw = raw_from_progress(progress)
        if spread_method == GradientSpreadMethod.PAD:
            mapped = 0.0 if raw <= 0.0 else 1.0 if raw >= 1.0 else raw
        else:
            mapped = spread_map(raw, spread_method)
        color = sample_stops(norm_stops, mapped)
        fan_line_raw.append((theta, raw, color))

    if not fan_line_raw:
        fan_line: list[tuple[float, tuple[float, ...]]] = []
    elif (
        spread_method == GradientSpreadMethod.PAD
        and not span_covers_full_circle
        and wraps
    ):
        limit_theta = start_angle + seam_progress
        pad_color = fan_line_raw[0][2]
        fan_line = []
        inserted = False
        for theta, raw, color in fan_line_raw:
            fan_line.append((theta, color))
            if not inserted and FloatTolerance.equal(theta, limit_theta):
                fan_line.append((theta + FloatTolerance.TOLERANCE, pad_color))
                inserted = True
        if not inserted:
            fan_line.append((limit_theta + FloatTolerance.TOLERANCE, pad_color))
    else:
        fan_line = [(theta, color) for (theta, _, color) in fan_line_raw]

    samples: list[tuple[float, tuple[float, ...]]] = []
    start_color_components = norm_stops[0][1].colors
    if fan_line:
        samples.append(fan_line[0])
        for idx in range(len(fan_line) - 1):
            theta0, color0 = fan_line[idx]
            theta1, color1 = fan_line[idx + 1]
            delta_theta = theta1 - theta0
            if FloatTolerance.less_equal(delta_theta, 0.0):
                if samples:
                    samples[-1] = (theta1, color1)
                else:
                    samples.append((theta1, color1))
                continue
            if wraps and FloatTolerance.greater_than(theta0, limit_theta):
                color0 = start_color_components
                color1 = start_color_components
            splits = max(1, int(math.ceil(delta_theta / max_angle)))
            for s in range(1, splits + 1):
                t = s / splits
                theta = theta0 + t * delta_theta
                color = tuple(
                    color0[j] + (color1[j] - color0[j]) * t for j in range(comp_count)
                )
                samples.append((theta, color))

    if len(samples) <= 1:
        theta = fan_line[0][0] if fan_line else start_angle
        base_color = fan_line[0][1] if fan_line else norm_stops[0][1].colors
        samples = [
            (theta, base_color),
            (theta + cover_span, base_color),
        ]

    triangles: list[
        tuple[tuple[float, float], tuple[float, float], tuple[float, float]]
    ] = []
    tri_colors: list[tuple[tuple[float, ...], tuple[float, ...], tuple[float, ...]]] = (
        []
    )

    theta_prev, color_prev = samples[0]
    x_prev_inner = cx + r_inner * math.cos(theta_prev)
    y_prev_inner = cy + r_inner * math.sin(theta_prev)
    x_prev_outer = cx + r_outer * math.cos(theta_prev)
    y_prev_outer = cy + r_outer * math.sin(theta_prev)

    for theta_next, color_next in samples[1:]:
        x_next_inner = cx + r_inner * math.cos(theta_next)
        y_next_inner = cy + r_inner * math.sin(theta_next)
        x_next_outer = cx + r_outer * math.cos(theta_next)
        y_next_outer = cy + r_outer * math.sin(theta_next)

        triangles.append(
            (
                (x_prev_inner, y_prev_inner),
                (x_prev_outer, y_prev_outer),
                (x_next_outer, y_next_outer),
            )
        )
        tri_colors.append((color_prev, color_prev, color_next))

        triangles.append(
            (
                (x_prev_inner, y_prev_inner),
                (x_next_outer, y_next_outer),
                (x_next_inner, y_next_inner),
            )
        )
        tri_colors.append((color_prev, color_next, color_next))

        theta_prev, color_prev = theta_next, color_next
        x_prev_inner, y_prev_inner = x_next_inner, y_next_inner
        x_prev_outer, y_prev_outer = x_next_outer, y_next_outer

    return MeshShading(
        color_space=color_space,
        bbox=bbox,
        comp_count=comp_count,
        triangles=triangles,
        colors=tri_colors,
        background=None,
        anti_alias=True,
    )


def shape_linear_gradient(
    x1: float,
    y1: float,
    x2: float,
    y2: float,
    stops: Sequence[tuple[float, Union[Color, str]]],
    spread_method: Union[GradientSpreadMethod, str] = GradientSpreadMethod.PAD,
    bbox: Optional["BoundingBox"] = None,
) -> LinearGradient:
    """
    Create a linear gradient for a shape with SVG-like stops (offset in [0,1]).
    REPEAT/REFLECT are implemented by expanding stops to cover the bbox projection.
    """
    if not stops:
        raise ValueError("At least one stop is required")

    spread_method = GradientSpreadMethod.coerce(spread_method)

    _, normalized_stops, raw_stops = normalize_stops(stops, return_raw=True)

    if spread_method == GradientSpreadMethod.PAD or bbox is None:
        # if the spread_method is PAD this is the final gradient
        # if the spread_method is REPEAT/REFLECT but no bbox is given, we can't expand yet
        # gradient paint will call this method again with the bbox to replace the gradient
        # at render time
        colors = [color for _, color in normalized_stops]
        bounds = [offset for offset, _ in normalized_stops[1:-1]]

        gradient = LinearGradient(
            from_x=x1,
            from_y=y1,
            to_x=x2,
            to_y=y2,
            colors=colors,
            bounds=bounds,
            extend_before=True,
            extend_after=True,
        )
        gradient.raw_stops = raw_stops
        return gradient

    # 5) Expand for REPEAT / REFLECT
    use_raw_period = raw_stops is not None and len(raw_stops) >= 2
    tile_stops = raw_stops if use_raw_period else normalized_stops
    assert tile_stops is not None  # pleasing mypy
    base_start = tile_stops[0][0]
    base_end = tile_stops[-1][0]
    base_span = max(base_end - base_start, FloatTolerance.TOLERANCE)
    if FloatTolerance.less_equal(base_span, 0.0):
        base_start = 0.0
        base_span = 1.0
        tile_stops = normalized_stops

    tmin, tmax, L = bbox.project_interval_on_axis(x1, y1, x2, y2)
    if FloatTolerance.less_equal(L, 0.0):
        # Degenerate axis: synthesize flat
        c0, c1 = normalized_stops[0][1], normalized_stops[-1][1]
        return LinearGradient(
            from_x=x1,
            from_y=y1,
            to_x=x2,
            to_y=y2,
            colors=[c0, c1],
            bounds=[],
            extend_before=False,
            extend_after=False,
        )

    tmin_norm = tmin / L
    tmax_norm = tmax / L

    start_tile = math.floor((tmin_norm - base_start) / base_span) - 1
    end_tile = math.ceil((tmax_norm - base_start) / base_span) + 1

    expanded: list[tuple[float, Union[Color, str]]] = []
    for k in range(start_tile, end_tile + 1):
        shift = k * base_span
        if spread_method == GradientSpreadMethod.REPEAT or (k & 1) == 0:
            # even tiles for REFLECT behave like REPEAT
            for u, col in tile_stops:
                expanded.append((shift + u, col))
        else:
            # REFLECT on odd tiles: reverse order + mirrored u
            for u, col in reversed(tile_stops):
                mirrored = shift + base_start + base_span - (u - base_start)
                expanded.append((mirrored, col))

    # Clip a bit beyond bbox for compactness
    margin = max(base_span, 1.0)
    a = tmin_norm - margin
    b = tmax_norm + margin
    clipped = [
        (s, c)
        for (s, c) in expanded
        if FloatTolerance.greater_equal(s, a) and FloatTolerance.less_equal(s, b)
    ] or expanded

    # Renormalize to [0..1] over synthetic span
    s0 = clipped[0][0]
    sN = clipped[-1][0]
    span = max(sN - s0, FloatTolerance.TOLERANCE)
    renorm = [((s - s0) / span, c) for (s, c) in clipped]

    # Shift/scale the coords so u=0..1 aligns to absolute positions s0..sN
    lam0 = s0  # in units of periods
    lam1 = s0 + span
    nx1 = x1 + lam0 * (x2 - x1)
    ny1 = y1 + lam0 * (y2 - y1)
    nx2 = x1 + lam1 * (x2 - x1)
    ny2 = y1 + lam1 * (y2 - y1)

    # Merge identical offsets after math
    merged = merge_near_duplicates(renorm)

    linear_gradient_colors = [c for _, c in merged]
    linear_gradient_bounds = [o for o, _ in merged[1:-1]]

    gradient = LinearGradient(
        from_x=nx1,
        from_y=ny1,
        to_x=nx2,
        to_y=ny2,
        colors=linear_gradient_colors,
        bounds=linear_gradient_bounds,
        extend_before=False,
        extend_after=False,
    )
    gradient.raw_stops = raw_stops
    return gradient


def shape_radial_gradient(
    cx: float,
    cy: float,
    r: float,
    stops: Sequence[tuple[float, Union[Color, str]]],
    fx: Optional[float] = None,
    fy: Optional[float] = None,
    fr: float = 0.0,
    spread_method: Union[GradientSpreadMethod, str] = GradientSpreadMethod.PAD,
    bbox: Optional["BoundingBox"] = None,
) -> RadialGradient:
    """
    Create a radial gradient for a shape with SVG-like stops (offset in [0,1]).
    - (cx, cy, r): outer circle
    - (fx, fy, fr): focal/inner circle (defaults to center with radius 0)
    REPEAT/REFLECT are implemented by expanding stops to cover the bbox projection.
    """
    if not stops:
        raise ValueError("At least one stop is required")

    spread_method = GradientSpreadMethod.coerce(spread_method)

    _, normalized_stops, raw_stops = normalize_stops(stops, return_raw=True)

    if r < 0:
        raise ValueError("Outer radius r must be >= 0")
    if fr < 0:
        fr = 0.0
    if fx is None:
        fx = cx
    if fy is None:
        fy = cy
    # If inner radius exceeds outer, clamp
    if fr > r:
        fr = r

    if spread_method == GradientSpreadMethod.PAD or bbox is None:
        # if the spread_method is PAD this is the final gradient
        # if the spread_method is REPEAT/REFLECT but no bbox is given, we can't expand yet
        # gradient paint will call this method again with the bbox to replace the gradient
        # at render time
        colors = [color for _, color in normalized_stops]
        bounds = [offset for offset, _ in normalized_stops[1:-1]]

        gradient = RadialGradient(
            start_circle_x=fx,
            start_circle_y=fy,
            start_circle_radius=fr,
            end_circle_x=cx,
            end_circle_y=cy,
            end_circle_radius=r,
            colors=colors,
            bounds=bounds,
            extend_before=True,
            extend_after=True,
        )
        gradient.raw_stops = raw_stops
        return gradient

    # 5) Expand for REPEAT / REFLECT across rings
    use_raw_period = raw_stops is not None and len(raw_stops) >= 2
    tile_stops = raw_stops if use_raw_period else normalized_stops
    assert tile_stops is not None  # pleasing mypy
    base_start = tile_stops[0][0]
    base_end = tile_stops[-1][0]
    base_span = max(base_end - base_start, FloatTolerance.TOLERANCE)
    if FloatTolerance.less_equal(base_span, 0.0):
        base_start = 0.0
        base_span = 1.0
        tile_stops = normalized_stops

    # Degenerate gradients with no radial growth can't be meaningfully repeated
    if FloatTolerance.equal(r, fr):
        colors = [color for _, color in normalized_stops]
        bounds = [offset for offset, _ in normalized_stops[1:-1]]
        gradient = RadialGradient(
            start_circle_x=fx,
            start_circle_y=fy,
            start_circle_radius=fr,
            end_circle_x=cx,
            end_circle_y=cy,
            end_circle_radius=r,
            colors=colors,
            bounds=bounds,
            extend_before=True,
            extend_after=True,
        )
        gradient.raw_stops = raw_stops
        return gradient

    def sigma_to_lambda(sigma: float) -> float:
        return (sigma - base_start) / base_span

    def circle_at(lam: float) -> tuple[float, float, float]:
        return (
            lerp(fx, cx, lam),
            lerp(fy, cy, lam),
            lerp(fr, r, lam),
        )

    target_sigma = base_end
    if bbox is not None:
        max_tiles = 256
        for _ in range(max_tiles):
            lam = sigma_to_lambda(target_sigma)
            cx_lam, cy_lam, r_lam = circle_at(lam)
            if FloatTolerance.less_equal(
                bbox.max_distance_to_point(cx_lam, cy_lam), r_lam
            ):
                break
            target_sigma += base_span
        else:
            target_sigma = base_end + max_tiles * base_span

    tiles_needed = 0
    if target_sigma > base_end:
        tiles_needed = math.ceil((target_sigma - base_end) / base_span)

    expanded: list[tuple[float, Color]] = []
    for k in range(tiles_needed + 1):
        shift = k * base_span
        if spread_method == GradientSpreadMethod.REPEAT or (k & 1) == 0:
            for u, col in tile_stops:
                expanded.append((shift + u, col))
        else:
            for u, col in reversed(tile_stops):
                mirrored = shift + base_start + base_span - (u - base_start)
                expanded.append((mirrored, col))

    if not expanded:
        expanded = tile_stops[:]

    # Clip a little beyond the target span to keep the list tight while preserving continuity
    clip_limit = target_sigma + base_span + 1e-6
    expanded = [pair for pair in expanded if pair[0] <= clip_limit]

    s0 = expanded[0][0]
    sN = expanded[-1][0]
    span = max(sN - s0, FloatTolerance.TOLERANCE)
    renorm = [((s - s0) / span, c) for (s, c) in expanded]

    lam0 = sigma_to_lambda(s0)
    lam1 = sigma_to_lambda(sN)
    sx, sy, sr = circle_at(lam0)
    ex, ey, er = circle_at(lam1)

    # Merge identical offsets after math
    merged = merge_near_duplicates(renorm)

    radial_gradient_colors = [c for _, c in merged]
    radial_gradient_bounds = [o for o, _ in merged[1:-1]]

    gradient = RadialGradient(
        start_circle_x=sx,
        start_circle_y=sy,
        start_circle_radius=sr,
        end_circle_x=ex,
        end_circle_y=ey,
        end_circle_radius=er,
        colors=radial_gradient_colors,
        bounds=radial_gradient_bounds,
        extend_before=False,
        extend_after=False,
    )
    gradient.raw_stops = raw_stops
    return gradient