pax-runtime-api 0.39.1

Userland constructs used at the runtime API boundary of Pax Engine
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
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
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
//! Vector drawing primitives: paths, fills, strokes, caps, and gradients.

use super::*;

pub mod path_smoothing;
pub mod path_trim;
pub mod stroke_utils;

/// Describes a single element of a vector path, such as a line, a point, or curve segment.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
#[serde(crate = "crate::serde")]
pub enum PathElement {
    /// No-op path element.
    #[default]
    Empty,
    /// Moves the current point to the provided coordinate.
    Point(Size, Size),
    /// Draws a straight line to the following `Point`.
    Line,
    /// Draws a quadratic Bézier segment with one control point, ending at the following `Point`.
    Quadratic(Size, Size),
    /// Draws a cubic Bézier segment with two control points, ending at the following `Point`.
    Cubic(Size, Size, Size, Size),
    /// Closes the current contour.
    Close,
}

impl Interpolatable for PathElement {}
impl HelperFunctions for PathElement {}

/// Controls optional curve smoothing for path geometry before tessellation.
///
/// `PathSmoothing` is intended for authored or imported paths whose source data
/// approximates curves with many short line segments, such as single-stroke SVG
/// fonts. Existing paths keep their exact geometry by default.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
#[serde(crate = "crate::serde")]
pub enum PathSmoothing {
    /// Preserve the authored path exactly.
    #[default]
    None,
    /// Lightly smooth polyline runs while preserving sharp corners.
    Light,
    /// More aggressively smooth polyline runs for pen-like paths.
    Strong,
}

impl Interpolatable for PathSmoothing {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        if t < 1.0 {
            *self
        } else {
            *other
        }
    }
}

/// Controls how an open stroke terminates at the exposed endpoints of a path.
///
/// `StrokeCap` affects primitives such as `Line` and open `Path` subpaths.
/// Closed geometry ignores cap style because it has no exposed endpoints.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
#[serde(crate = "crate::serde")]
pub enum StrokeCap {
    /// Ends exactly at the path endpoint without extending past it.
    #[default]
    Butt,
    /// Adds a semicircular cap whose radius is half the stroke width.
    Round,
    /// Adds a square cap that extends half the stroke width past the endpoint.
    Square,
}

impl Interpolatable for StrokeCap {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        if t < 1.0 {
            self.clone()
        } else {
            other.clone()
        }
    }
}

/// Controls how stroke segments are joined at path vertices.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
#[serde(crate = "crate::serde")]
pub enum StrokeJoin {
    /// Extends outer edges to a point, subject to the renderer's miter limit.
    #[default]
    Miter,
    /// Rounds the outside of each join.
    Round,
    /// Cuts joins off with a straight edge.
    Bevel,
}

impl Interpolatable for StrokeJoin {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        if t < 1.0 {
            self.clone()
        } else {
            other.clone()
        }
    }
}

/// One interior paint layer. Index zero in an element's fill stack is topmost.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(crate = "crate::serde")]
pub struct Fill {
    /// Color or gradient sampled over the complete local geometry.
    pub paint: Property<Paint>,
    /// Light-reactive surface response, matte by default.
    pub material: Property<Material>,
    /// Opacity of this layer before element opacity is applied.
    pub opacity: Property<Opacity>,
    // Future blend_mode governs composition over lower layers.
}

/// One centered outline layer, drawn above every interior fill.
/// Index zero in an element's stroke stack is topmost.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(crate = "crate::serde")]
pub struct Stroke {
    /// Color or gradient sampled over the complete, untrimmed geometry.
    pub paint: Property<Paint>,
    /// Light-reactive surface response, matte by default.
    pub material: Property<Material>,
    /// Opacity of this layer before element opacity is applied.
    pub opacity: Property<Opacity>,
    /// Width in logical pixels. Percentages are unsupported; nonpositive widths draw nothing.
    pub width: Property<Size>,
    /// Style of exposed endpoints on open paths.
    pub cap: Property<StrokeCap>,
    /// Style of joins between adjacent segments.
    pub join: Property<StrokeJoin>,
    // Future blend_mode governs composition over lower layers.
}

impl Default for Fill {
    fn default() -> Self {
        Self {
            paint: Default::default(),
            material: Default::default(),
            opacity: Default::default(),
        }
    }
}

/// Plain drawing values captured before entering a rendering backend.
/// Backends never read live shared properties while recording a frame.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedStroke {
    pub paint: Paint,
    pub material: ResolvedMaterial,
    pub opacity: Opacity,
    pub width: Size,
    pub cap: StrokeCap,
    pub join: StrokeJoin,
}

impl Stroke {
    /// Resolves nested fields from the entered UI graph's settled projections.
    pub fn resolve_in_graph(&self) -> ResolvedStroke {
        ResolvedStroke {
            paint: self.paint.local().get(),
            material: self.material.local().get().resolve_in_graph(),
            opacity: self.opacity.local().get(),
            width: self.width.local().get(),
            cap: self.cap.local().get(),
            join: self.join.local().get(),
        }
    }

    /// Captures the latest published fields without entering a UI graph.
    /// Independently published fields are not a multi-property transaction.
    pub fn snapshot(&self) -> ResolvedStroke {
        ResolvedStroke {
            paint: self.paint.get(),
            material: self.material.get().snapshot(),
            opacity: self.opacity.get(),
            width: self.width.get(),
            cap: self.cap.get(),
            join: self.join.get(),
        }
    }
}

impl Default for Stroke {
    fn default() -> Self {
        Self {
            paint: Default::default(),
            material: Default::default(),
            opacity: Default::default(),
            width: Property::new(Size::Pixels(1.into())),
            cap: Default::default(),
            join: Default::default(),
        }
    }
}

impl From<Paint> for Fill {
    fn from(paint: Paint) -> Self {
        Self {
            paint: Property::new(paint),
            ..Self::default()
        }
    }
}
impl From<Color> for Fill {
    fn from(color: Color) -> Self {
        Paint::Solid(color).into()
    }
}
impl From<Paint> for Stroke {
    fn from(paint: Paint) -> Self {
        Self {
            paint: Property::new(paint),
            ..Self::default()
        }
    }
}
impl From<Color> for Stroke {
    fn from(color: Color) -> Self {
        Paint::Solid(color).into()
    }
}

impl Stroke {
    /// Resolves a finite, positive pixel width, or zero for an invisible stroke.
    pub fn width_pixels(&self) -> f64 {
        match self.width.get() {
            Size::Pixels(value) if value.to_float().is_finite() => value.to_float().max(0.0),
            _ => {
                log::warn!("Stroke width must be finite logical pixels");
                0.0
            }
        }
    }
}

impl ResolvedStroke {
    /// Resolves a finite, positive pixel width, or zero for an invisible stroke.
    pub fn width_pixels(&self) -> f64 {
        match self.width.clone() {
            Size::Pixels(value) if value.to_float().is_finite() => value.to_float().max(0.0),
            _ => {
                log::warn!("Stroke width must be finite logical pixels");
                0.0
            }
        }
    }
}

macro_rules! appearance_layer_traits {
    ($ty:ident, $($field:ident),+) => {
        impl PartialEq for $ty {
            fn eq(&self, other: &Self) -> bool { $(self.$field.get() == other.$field.get())&&+ }
        }
        impl Hash for $ty {
            fn hash<H: Hasher>(&self, state: &mut H) { $(self.$field.get().hash(state);)+ }
        }
        impl Interpolatable for $ty {
            fn interpolate(&self, other: &Self, t: f64) -> Self {
                Self { $($field: Property::new(self.$field.get().interpolate(&other.$field.get(), t))),+ }
            }
        }
    }
}
appearance_layer_traits!(Fill, paint, material, opacity);
appearance_layer_traits!(Stroke, paint, material, opacity, width, cap, join);

/// Describes where to open new windows or tabs when navigating to a URL from a `Link` node.
pub enum NavigationTarget {
    /// Navigate in the current window or tab.
    Current,
    /// Navigate in a new window or tab.
    New,
}

/// Describes how to fill vector geometry.
/// Solid fills interpolate their RGBA channels. Other pairs crossfade sampled
/// paints in premultiplied RGBA, preserving each gradient's geometry and stops.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(crate = "crate::serde")]
pub enum Paint {
    /// A single solid color.
    Solid(Color),
    /// A linear gradient.
    LinearGradient(LinearGradient),
    /// A radial gradient.
    RadialGradient(RadialGradient),
    /// A weighted paint mixture produced by interpolation. Weights are finite,
    /// nonnegative, and sum to one. Use [`Paint::blend`] to normalize weights,
    /// flatten nested mixtures, and combine repeated endpoints.
    Blend(Vec<(Paint, f64)>),
    /// A row-connected bicubic field with independently positioned colored anchors.
    MeshGradient(MeshGradient),
}

impl From<Color> for Paint {
    fn from(color: Color) -> Self {
        Self::Solid(color)
    }
}

impl Hash for Paint {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Paint::Solid(color) => {
                state.write_u8(0);
                color.hash(state);
            }
            Paint::LinearGradient(linear) => {
                state.write_u8(1);
                linear.start.hash(state);
                linear.end.hash(state);
                linear.stops.hash(state);
            }
            Paint::RadialGradient(radial) => {
                state.write_u8(2);
                radial.start.hash(state);
                radial.end.hash(state);
                radial.radius.to_bits().hash(state);
                radial.stops.hash(state);
            }
            Paint::Blend(terms) => {
                state.write_u8(3);
                terms.len().hash(state);
                for (fill, weight) in terms {
                    fill.hash(state);
                    weight.to_bits().hash(state);
                }
            }
            Paint::MeshGradient(mesh) => {
                state.write_u8(4);
                mesh.hash(state);
            }
        }
    }
}

/// Logical scene depth for lighting calculations.
///
/// `Depth` is expressed in logical pixels. Unlike [`Size`], it is not anchored
/// to a viewport or parent box, so percent and combined units are intentionally
/// rejected during value coercion.
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Default, PartialEq, PartialOrd)]
#[serde(crate = "crate::serde")]
pub struct Depth(pub Numeric);

impl Depth {
    /// Returns the depth as a floating-point logical pixel value.
    pub fn to_float(&self) -> f64 {
        self.0.to_float()
    }
}

impl From<Numeric> for Depth {
    fn from(value: Numeric) -> Self {
        Self(value)
    }
}

impl From<f64> for Depth {
    fn from(value: f64) -> Self {
        Self(Numeric::F64(value))
    }
}

impl Hash for Depth {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl Interpolatable for Depth {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        Self(self.0.interpolate(&other.0, t))
    }
}

impl HelperFunctions for Depth {}

/// A three-dimensional vector in logical scene space.
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq)]
#[serde(crate = "crate::serde")]
pub struct Vector3 {
    /// X component.
    pub x: f64,
    /// Y component.
    pub y: f64,
    /// Z component.
    pub z: f64,
}

impl Vector3 {
    /// Constructs a 3D vector.
    pub fn new(x: f64, y: f64, z: f64) -> Self {
        Self { x, y, z }
    }
}

impl Default for Vector3 {
    fn default() -> Self {
        Self {
            x: 0.0,
            y: 0.0,
            z: 0.0,
        }
    }
}

impl Hash for Vector3 {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.x.to_bits().hash(state);
        self.y.to_bits().hash(state);
        self.z.to_bits().hash(state);
    }
}

impl Interpolatable for Vector3 {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        Self {
            x: self.x.interpolate(&other.x, t),
            y: self.y.interpolate(&other.y, t),
            z: self.z.interpolate(&other.z, t),
        }
    }
}

impl HelperFunctions for Vector3 {
    fn register_all_functions() {
        register_function(
            "Vector3".to_string(),
            "new".to_string(),
            std::sync::Arc::new(|args| {
                if args.len() != 3 {
                    return Err("Expected 3 arguments for function Vector3::new".to_string());
                }
                let mut itr = args.into_iter();
                let x = f64::try_coerce(itr.next().unwrap())?;
                let y = f64::try_coerce(itr.next().unwrap())?;
                let z = f64::try_coerce(itr.next().unwrap())?;
                Ok(Vector3::new(x, y, z).to_pax_value())
            }),
        );
    }
}

/// Shape of a light contribution in logical scene space.
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Default, PartialEq, Eq, Hash)]
#[serde(crate = "crate::serde")]
pub enum LightShape {
    /// A positional light with radius-based attenuation.
    #[default]
    Point,
    /// A light with direction but no position or attenuation.
    Directional,
}

impl Interpolatable for LightShape {}
impl HelperFunctions for LightShape {}

/// Tunable response parameters for a light-reactive vector material.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(crate = "crate::serde")]
pub struct MaterialParams {
    /// Ambient contribution multiplier.
    pub ambient: Property<f64>,
    /// Diffuse contribution multiplier.
    pub diffuse: Property<f64>,
    /// Specular contribution multiplier.
    pub specular: Property<f64>,
    /// Surface roughness in the `[0.0, 1.0]` range.
    pub roughness: Property<f64>,
    /// Metallic response in the `[0.0, 1.0]` range.
    pub metallic: Property<f64>,
    /// Additive emissive color.
    pub emissive: Property<Color>,
    /// Additive emissive intensity.
    pub emissive_intensity: Property<f64>,
}

impl Default for MaterialParams {
    fn default() -> Self {
        Self {
            ambient: Property::new(1.0),
            diffuse: Property::new(0.82),
            specular: Property::new(0.08),
            roughness: Property::new(0.78),
            metallic: Property::new(0.0),
            emissive: Property::new(Color::BLACK),
            emissive_intensity: Property::new(0.0),
        }
    }
}

impl PartialEq for MaterialParams {
    fn eq(&self, other: &Self) -> bool {
        self.ambient.get() == other.ambient.get()
            && self.diffuse.get() == other.diffuse.get()
            && self.specular.get() == other.specular.get()
            && self.roughness.get() == other.roughness.get()
            && self.metallic.get() == other.metallic.get()
            && self.emissive.get() == other.emissive.get()
            && self.emissive_intensity.get() == other.emissive_intensity.get()
    }
}

impl Hash for MaterialParams {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.ambient.get().to_bits().hash(state);
        self.diffuse.get().to_bits().hash(state);
        self.specular.get().to_bits().hash(state);
        self.roughness.get().to_bits().hash(state);
        self.metallic.get().to_bits().hash(state);
        self.emissive.get().hash(state);
        self.emissive_intensity.get().to_bits().hash(state);
    }
}

impl Interpolatable for MaterialParams {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        Self {
            ambient: Property::new(self.ambient.get().interpolate(&other.ambient.get(), t)),
            diffuse: Property::new(self.diffuse.get().interpolate(&other.diffuse.get(), t)),
            specular: Property::new(self.specular.get().interpolate(&other.specular.get(), t)),
            roughness: Property::new(self.roughness.get().interpolate(&other.roughness.get(), t)),
            metallic: Property::new(self.metallic.get().interpolate(&other.metallic.get(), t)),
            emissive: Property::new(self.emissive.get().interpolate(&other.emissive.get(), t)),
            emissive_intensity: Property::new(
                self.emissive_intensity
                    .get()
                    .interpolate(&other.emissive_intensity.get(), t),
            ),
        }
    }
}

impl HelperFunctions for MaterialParams {}

/// Light-reactive surface response for vector primitives.
///
/// This is intentionally named `Material`; `texture` is reserved for future
/// bitmap-backed texture maps and pattern data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(crate = "crate::serde")]
pub enum Material {
    /// Responds to scene lighting using parameterized material coefficients.
    Lit(MaterialParams),
    /// Ignores scene lighting and preserves legacy unlit rendering behavior.
    Unlit,
}

/// Plain material coefficients for one settled drawing operation.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedMaterialParams {
    pub ambient: f64,
    pub diffuse: f64,
    pub specular: f64,
    pub roughness: f64,
    pub metallic: f64,
    pub emissive: Color,
    pub emissive_intensity: f64,
}

/// Material response with no live property handles.
#[derive(Clone, Debug, PartialEq)]
pub enum ResolvedMaterial {
    Lit(ResolvedMaterialParams),
    Unlit,
}

impl Material {
    /// Resolves nested coefficients from the entered UI graph's projections.
    pub fn resolve_in_graph(&self) -> ResolvedMaterial {
        match self {
            Self::Unlit => ResolvedMaterial::Unlit,
            Self::Lit(p) => ResolvedMaterial::Lit(ResolvedMaterialParams {
                ambient: p.ambient.local().get(),
                diffuse: p.diffuse.local().get(),
                specular: p.specular.local().get(),
                roughness: p.roughness.local().get(),
                metallic: p.metallic.local().get(),
                emissive: p.emissive.local().get(),
                emissive_intensity: p.emissive_intensity.local().get(),
            }),
        }
    }

    /// Captures published coefficients without evaluating the UI graph.
    pub fn snapshot(&self) -> ResolvedMaterial {
        match self {
            Self::Unlit => ResolvedMaterial::Unlit,
            Self::Lit(p) => ResolvedMaterial::Lit(ResolvedMaterialParams {
                ambient: p.ambient.get(),
                diffuse: p.diffuse.get(),
                specular: p.specular.get(),
                roughness: p.roughness.get(),
                metallic: p.metallic.get(),
                emissive: p.emissive.get(),
                emissive_intensity: p.emissive_intensity.get(),
            }),
        }
    }
}

impl Default for Material {
    fn default() -> Self {
        Self::matte()
    }
}

impl Material {
    /// A soft, low-specular material suitable as the default lit response.
    pub fn matte() -> Self {
        Self::Lit(MaterialParams::default())
    }

    /// A higher-specular material with lower roughness.
    pub fn glossy(specular: f64) -> Self {
        let mut params = MaterialParams::default();
        params.specular = Property::new(specular.clamp(0.0, 1.0));
        params.roughness = Property::new(0.28);
        Self::Lit(params)
    }

    /// A metallic material response.
    pub fn metallic(metallic: f64) -> Self {
        let mut params = MaterialParams::default();
        params.metallic = Property::new(metallic.clamp(0.0, 1.0));
        params.diffuse = Property::new(0.42);
        params.specular = Property::new(0.55);
        params.roughness = Property::new(0.36);
        Self::Lit(params)
    }

    /// An emissive material that adds color independent of lights.
    pub fn emissive(color: Color, intensity: f64) -> Self {
        let mut params = MaterialParams::default();
        params.emissive = Property::new(color);
        params.emissive_intensity = Property::new(intensity.max(0.0));
        Self::Lit(params)
    }

    /// Creates a lit material from explicit coefficients.
    pub fn custom(params: MaterialParams) -> Self {
        Self::Lit(params)
    }

    /// A material that ignores authored lights.
    pub fn unlit() -> Self {
        Self::Unlit
    }
}

impl Hash for Material {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Material::Lit(params) => {
                state.write_u8(0);
                params.hash(state);
            }
            Material::Unlit => {
                state.write_u8(1);
            }
        }
    }
}

impl Interpolatable for Material {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        match (self, other) {
            (Self::Lit(lhs), Self::Lit(rhs)) => Self::Lit(lhs.interpolate(rhs, t)),
            _ if t < 1.0 => self.clone(),
            _ => other.clone(),
        }
    }
}

impl HelperFunctions for Material {
    fn register_all_functions() {
        register_function(
            "Material".to_string(),
            "matte".to_string(),
            std::sync::Arc::new(|args| {
                if !args.is_empty() {
                    return Err("Expected 0 arguments for function Material::matte".to_string());
                }
                Ok(Material::matte().to_pax_value())
            }),
        );
        register_function(
            "Material".to_string(),
            "glossy".to_string(),
            std::sync::Arc::new(|args| {
                if args.len() != 1 {
                    return Err("Expected 1 argument for function Material::glossy".to_string());
                }
                let specular = f64::try_coerce(args.into_iter().next().unwrap())?;
                Ok(Material::glossy(specular).to_pax_value())
            }),
        );
        register_function(
            "Material".to_string(),
            "metallic".to_string(),
            std::sync::Arc::new(|args| {
                if args.len() != 1 {
                    return Err("Expected 1 argument for function Material::metallic".to_string());
                }
                let metallic = f64::try_coerce(args.into_iter().next().unwrap())?;
                Ok(Material::metallic(metallic).to_pax_value())
            }),
        );
        register_function(
            "Material".to_string(),
            "emissive".to_string(),
            std::sync::Arc::new(|args| {
                if args.len() != 2 {
                    return Err("Expected 2 arguments for function Material::emissive".to_string());
                }
                let mut itr = args.into_iter();
                let color = Color::try_coerce(itr.next().unwrap())?;
                let intensity = f64::try_coerce(itr.next().unwrap())?;
                Ok(Material::emissive(color, intensity).to_pax_value())
            }),
        );
        register_function(
            "Material".to_string(),
            "custom".to_string(),
            std::sync::Arc::new(|args| {
                if args.len() != 1 {
                    return Err("Expected 1 argument for function Material::custom".to_string());
                }
                let params = MaterialParams::try_coerce(args.into_iter().next().unwrap())?;
                Ok(Material::custom(params).to_pax_value())
            }),
        );
        register_function(
            "Material".to_string(),
            "unlit".to_string(),
            std::sync::Arc::new(|args| {
                if !args.is_empty() {
                    return Err("Expected 0 arguments for function Material::unlit".to_string());
                }
                Ok(Material::unlit().to_pax_value())
            }),
        );
    }
}

/// Resolved ambient light for one logical canvas layer.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(crate = "crate::serde")]
pub struct SceneAmbientLight {
    /// Ambient color.
    pub color: Color,
    /// Ambient intensity.
    pub intensity: f64,
}

impl Default for SceneAmbientLight {
    fn default() -> Self {
        Self {
            color: Color::WHITE,
            intensity: 1.0,
        }
    }
}

impl Interpolatable for SceneAmbientLight {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        Self {
            color: self.color.interpolate(&other.color, t),
            intensity: self.intensity.interpolate(&other.intensity, t),
        }
    }
}

impl HelperFunctions for SceneAmbientLight {}

/// Resolved light contribution for one logical canvas layer.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(crate = "crate::serde")]
pub struct SceneLight {
    /// Positional or directional light shape.
    pub shape: LightShape,
    /// Position in logical canvas pixels for point lights.
    pub position: Vector3,
    /// Direction in scene space for directional lights.
    pub direction: Vector3,
    /// Light color.
    pub color: Color,
    /// Light intensity.
    pub intensity: f64,
    /// Point light radius in logical pixels.
    pub radius: f64,
    /// Whether this light contributes.
    pub enabled: bool,
}

impl Default for SceneLight {
    fn default() -> Self {
        Self {
            shape: LightShape::Point,
            position: Vector3::default(),
            direction: Vector3::new(0.0, 0.0, -1.0),
            color: Color::WHITE,
            intensity: 1.0,
            radius: 240.0,
            enabled: true,
        }
    }
}

impl Interpolatable for SceneLight {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        Self {
            shape: if t < 1.0 { self.shape } else { other.shape },
            position: self.position.interpolate(&other.position, t),
            direction: self.direction.interpolate(&other.direction, t),
            color: self.color.interpolate(&other.color, t),
            intensity: self.intensity.interpolate(&other.intensity, t),
            radius: self.radius.interpolate(&other.radius, t),
            enabled: if t < 1.0 { self.enabled } else { other.enabled },
        }
    }
}

impl HelperFunctions for SceneLight {}

/// Resolved lighting state for one logical canvas layer.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(crate = "crate::serde")]
pub struct SceneLighting {
    /// Whether authored lights or ambient overrides are present.
    pub active: bool,
    /// Whether `ambient` came from an enabled authored `AmbientLight`.
    ///
    /// The default ambient is only applied to primitives with at least one
    /// eligible direct light. An authored ambient remains layer-wide.
    pub ambient_is_authored: bool,
    /// Singleton ambient contribution.
    pub ambient: SceneAmbientLight,
    /// Positional and directional light contributions.
    pub lights: Vec<SceneLight>,
}

impl Default for SceneLighting {
    fn default() -> Self {
        Self {
            active: false,
            ambient_is_authored: false,
            ambient: SceneAmbientLight::default(),
            lights: vec![],
        }
    }
}

impl SceneLighting {
    /// Maximum number of simultaneously enabled lights in one target canvas layer.
    pub const MAX_LIGHTS: usize = 8;

    /// Ambient intensity used when point/directional lights exist but no explicit ambient override exists.
    pub const DEFAULT_AMBIENT_INTENSITY: f64 = 0.35;

    /// Returns lighting that preserves unlit legacy rendering.
    pub fn identity() -> Self {
        Self::default()
    }

    /// Creates active lighting with Pax's default ambient term.
    pub fn with_default_ambient(lights: Vec<SceneLight>) -> Self {
        Self {
            active: !lights.is_empty(),
            ambient_is_authored: false,
            ambient: SceneAmbientLight {
                color: Color::WHITE,
                intensity: Self::DEFAULT_AMBIENT_INTENSITY,
            },
            lights,
        }
    }
}

impl Interpolatable for SceneLighting {}
impl HelperFunctions for SceneLighting {}

impl Interpolatable for Paint {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        if let (Self::Solid(from), Self::Solid(to)) = (self, other) {
            return Self::Solid(from.interpolate(to, t));
        }
        if t <= 0.0 || self == other {
            return self.clone();
        }
        if t >= 1.0 {
            return other.clone();
        }
        Self::blend(vec![(self.clone(), 1.0 - t), (other.clone(), t)])
    }
}

/// Describes a linear gradient fill with a start and end point, and a list of color stops.
///
/// Pax templates canonically author each point as `[x, y]`: magic index `0`
/// is the horizontal coordinate and index `1` is the vertical coordinate.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Hash)]
#[serde(crate = "crate::serde")]
pub struct LinearGradient {
    /// Gradient start point in the primitive's local coordinate space.
    pub start: (Size, Size),
    /// Gradient end point in the primitive's local coordinate space.
    pub end: (Size, Size),
    /// Ordered color stops along the gradient.
    pub stops: Vec<GradientStop>,
}

/// A colored anchor in a [`MeshGradient`]. Position uses ordinary pixels, percentages,
/// or combined units, relative to the complete consumer geometry's paint bounds.
/// Rows describe connectivity; anchors in a row may have different y coordinates.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Hash)]
#[serde(crate = "crate::serde")]
pub struct MeshPoint {
    /// Local x/y coordinates relative to the complete paint bounds.
    pub position: (Size, Size),
    /// Anchor color, including alpha.
    pub color: Color,
}

impl Interpolatable for MeshPoint {
    fn interpolate(&self, other: &Self, t: f64) -> Self {
        Self {
            position: self.position.interpolate(&other.position, t),
            color: self.color.interpolate(&other.color, t),
        }
    }
}

/// Smooth mesh paint with 2–8 equally sized rows, each containing 2–8 anchors.
/// Automatic shared Bézier controls interpolate the anchors and their premultiplied
/// encoded-sRGB colors. Outside the covered mesh the paint is transparent. Folded
/// patches replace earlier patches in row-major order. Supported by the WGPU renderer.
/// Animate positions/colors to morph; whole [`Paint`] transitions remain crossfades.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Hash)]
#[serde(crate = "crate::serde")]
pub struct MeshGradient {
    /// A rectangular lattice; adjacent entries and rows define shared patch edges.
    pub rows: Vec<Vec<MeshPoint>>,
}

impl Interpolatable for MeshGradient {}

impl MeshGradient {
    /// Checks connectivity and finite inputs. An invalid mesh paints nothing; it is never truncated.
    pub fn validate(&self) -> Result<(), String> {
        let width = self.rows.first().map_or(0, Vec::len);
        if !(2..=8).contains(&self.rows.len())
            || !(2..=8).contains(&width)
            || self.rows.iter().any(|row| row.len() != width)
        {
            return Err("mesh gradients require 2–8 equal-length rows of 2–8 anchors".into());
        }
        let finite_size = |size: &Size| match size {
            Size::Pixels(v) | Size::Percent(v) => v.to_float().is_finite(),
            Size::Combined(px, percent) => {
                px.to_float().is_finite() && percent.to_float().is_finite()
            }
        };
        if self.rows.iter().flatten().any(|p| {
            !finite_size(&p.position.0)
                || !finite_size(&p.position.1)
                || p.color.to_rgba_0_1().iter().any(|c| !c.is_finite())
        }) {
            return Err("mesh gradient positions and colors must be finite".into());
        }
        Ok(())
    }
}

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

    #[test]
    fn mesh_values_roundtrip_and_opacity_scales_the_sampled_field() {
        let point = MeshPoint {
            position: (
                Size::Combined(5.into(), 40.into()),
                Size::Percent(70.into()),
            ),
            color: Color::CYAN,
        };
        let mesh = MeshGradient {
            rows: vec![vec![point.clone(); 2]; 2],
        };
        assert!(mesh.validate().is_ok());
        let paint = Paint::MeshGradient(mesh.clone());
        assert_eq!(
            Paint::try_coerce(paint.clone().to_pax_value()).unwrap(),
            paint
        );
        assert_eq!(
            MeshPoint::try_coerce(point.clone().to_pax_value()).unwrap(),
            point
        );
        let Paint::Blend(terms) = paint.with_alpha_factor(0.25) else {
            panic!("post-sampling opacity")
        };
        assert_eq!(terms[0], (paint.clone(), 0.25));
        assert_eq!(paint.with_alpha_factor(0.0).max_alpha_0_1(), 0.0);
        assert_eq!(paint.interpolate(&Paint::Solid(Color::WHITE), 0.0), paint);
        assert!(matches!(
            paint.interpolate(&Paint::Solid(Color::WHITE), 0.5),
            Paint::Blend(_)
        ));
        let mut invalid = mesh;
        invalid.rows[0].pop();
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn malformed_mesh_coordinates_never_panic_or_truncate() {
        for coordinates in [
            vec![],
            vec![Size::Percent(0.into())],
            vec![Size::Percent(0.into()); 3],
        ] {
            let value = PaxValue::Object(vec![
                ("position".into(), coordinates.to_pax_value()),
                ("color".into(), Color::CYAN.to_pax_value()),
            ]);
            assert!(MeshPoint::try_coerce(value).is_err());
        }
    }
}

/// A focal radial gradient, growing from `start` to the circle at `end` with `radius`.
///
/// Pax templates canonically author each point as `[x, y]`: magic index `0`
/// is the horizontal coordinate and index `1` is the vertical coordinate.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(crate = "crate::serde")]
pub struct RadialGradient {
    /// Center of the outer circle in the primitive's local coordinate space.
    pub end: (Size, Size),
    /// Focal point (0% stop). Equal start/end points give concentric circles.
    pub start: (Size, Size),
    /// Outer radius in local logical pixels. Nonpositive/nonfinite radii paint nothing.
    pub radius: f64,
    /// Ordered color stops along the gradient.
    pub stops: Vec<GradientStop>,
}

/// Runtime geometry shared by radial color fills and painted alpha masks.
/// Coordinates are local logical pixels, before the element's affine transform.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ResolvedRadialGradient {
    /// Point corresponding to the 0% stop.
    pub focal_point: kurbo::Point,
    /// Center of the circle corresponding to the 100% stop.
    pub center: kurbo::Point,
    /// Radius of the 100% circle in local logical pixels.
    pub radius: f64,
}

impl RadialGradient {
    /// Resolves points against the actual shape bounds, including their origin.
    /// Invalid geometry paints nothing on all backends. The authored radius is
    /// independent of the distance between the focal point and the center.
    pub fn resolve_geometry(&self, rect: kurbo::Rect) -> Option<ResolvedRadialGradient> {
        let bounds = (rect.width(), rect.height());
        let resolve = |p: (Size, Size)| {
            kurbo::Point::new(
                rect.x0 + p.0.evaluate(bounds, Axis::X),
                rect.y0 + p.1.evaluate(bounds, Axis::Y),
            )
        };
        let focal_point = resolve(self.start);
        let center = resolve(self.end);
        if self.radius <= 0.0
            || ![
                self.radius,
                focal_point.x,
                focal_point.y,
                center.x,
                center.y,
            ]
            .into_iter()
            .all(f64::is_finite)
        {
            return None;
        }
        Some(ResolvedRadialGradient {
            focal_point,
            center,
            radius: self.radius,
        })
    }
}

/// A color stop for a gradient fill, defined by a position (% or px) and a color.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Hash)]
#[serde(crate = "crate::serde")]
pub struct GradientStop {
    /// Stop position, conventionally expressed as a percentage along the gradient.
    pub position: Size,
    /// Color at this stop.
    pub color: Color,
}

impl GradientStop {
    /// Constructs a gradient stop at `position`.
    pub fn get(color: Color, position: Size) -> GradientStop {
        GradientStop { position, color }
    }

    /// Returns a copy of this stop with alpha multiplied by `factor`.
    pub fn with_alpha_factor(&self, factor: f64) -> GradientStop {
        GradientStop {
            position: self.position.clone(),
            color: self.color.with_alpha_factor(factor),
        }
    }
}

impl Default for Paint {
    fn default() -> Self {
        Self::Solid(Color::default())
    }
}

impl Paint {
    /// Constructs a normalized mixture of paints. Nested mixtures are flattened
    /// and identical endpoints merged, so repeated interruptions between a fixed
    /// set of themes do not accumulate a history of blend nodes. Nonpositive or
    /// nonfinite weights are ignored; an empty mixture is transparent.
    ///
    /// Sampling cost grows with the number of distinct endpoints still visible.
    /// A completed interpolation returns its destination paint directly.
    pub fn blend(terms: Vec<(Paint, f64)>) -> Self {
        fn append(out: &mut Vec<(Paint, f64)>, terms: Vec<(Paint, f64)>, scale: f64) {
            let max = terms
                .iter()
                .map(|(_, w)| *w)
                .filter(|w| w.is_finite())
                .fold(0.0, f64::max);
            if max <= 0.0 {
                return;
            }
            let sum: f64 = terms
                .iter()
                .map(|(_, w)| *w)
                .filter(|w| w.is_finite() && *w > 0.0)
                .map(|w| w / max)
                .sum();
            for (fill, weight) in terms {
                if !weight.is_finite() || weight <= 0.0 {
                    continue;
                }
                let weight = scale * (weight / max) / sum;
                if weight == 0.0 {
                    continue;
                }
                if let Paint::Blend(terms) = fill {
                    append(out, terms, weight);
                } else if let Some((_, existing)) = out.iter_mut().find(|(f, _)| *f == fill) {
                    *existing += weight;
                } else {
                    out.push((fill, weight));
                }
            }
        }
        let mut result = Vec::new();
        append(&mut result, terms, 1.0);
        if result.is_empty() {
            return Paint::Solid(Color::from_rgba_0_1([0.0; 4]));
        }
        if result.len() == 1 {
            result.pop().unwrap().0
        } else {
            Paint::Blend(result)
        }
    }

    /// Representative solid color for native text, which currently uses the
    /// first stop of a gradient. Mixtures crossfade those representative colors.
    pub fn representative_color(&self) -> Color {
        match self {
            Self::Solid(color) => color.clone(),
            Self::LinearGradient(g) => g.stops.first().map(|s| s.color.clone()).unwrap_or_default(),
            Self::RadialGradient(g) => g.stops.first().map(|s| s.color.clone()).unwrap_or_default(),
            // Native text has no mesh paint support; do not substitute a corner color.
            Self::MeshGradient(_) => Color::TRANSPARENT,
            Self::Blend(terms) => Color::blend_premultiplied(
                terms
                    .iter()
                    .map(|(fill, weight)| (fill.representative_color(), *weight)),
            ),
        }
    }

    fn gradient_stop_position_0_1(position: &Size) -> Option<f64> {
        match position {
            Size::Percent(p) => Some((p.to_float() / 100.0).clamp(0.0, 1.0)),
            Size::Pixels(_) | Size::Combined(_, _) => None,
        }
    }

    fn integrated_gradient_alpha_0_1(stops: &[GradientStop]) -> f64 {
        if stops.is_empty() {
            return 0.0;
        }

        let mut positioned_stops = stops
            .iter()
            .filter_map(|stop| {
                Self::gradient_stop_position_0_1(&stop.position)
                    .map(|position| (position, stop.color.alpha_0_1()))
            })
            .collect::<Vec<_>>();

        if positioned_stops.is_empty() {
            return stops
                .iter()
                .map(|stop| stop.color.alpha_0_1())
                .fold(0.0, f64::max);
        }

        positioned_stops.sort_by(|lhs, rhs| lhs.0.total_cmp(&rhs.0));

        if positioned_stops
            .first()
            .map(|stop| stop.0 > 0.0)
            .unwrap_or(false)
        {
            let alpha = positioned_stops[0].1;
            positioned_stops.insert(0, (0.0, alpha));
        }

        if positioned_stops
            .last()
            .map(|stop| stop.0 < 1.0)
            .unwrap_or(false)
        {
            let alpha = positioned_stops.last().map(|stop| stop.1).unwrap_or(0.0);
            positioned_stops.push((1.0, alpha));
        }

        let mut integrated_alpha = 0.0;
        for window in positioned_stops.windows(2) {
            let [(start_pos, start_alpha), (end_pos, end_alpha)] = window else {
                continue;
            };
            let span = (end_pos - start_pos).clamp(0.0, 1.0);
            if span <= f64::EPSILON {
                continue;
            }
            integrated_alpha += (start_alpha + end_alpha) * 0.5 * span;
        }

        integrated_alpha.clamp(0.0, 1.0)
    }

    // Converts a Pax point into Piet's unit-gradient coordinate system.
    pub fn to_unit_point((x, y): (Size, Size), (width, height): (f64, f64)) -> UnitPoint {
        let normalized_x = match x {
            Size::Pixels(val) => val.to_float() / width,
            Size::Percent(val) => val.to_float() / 100.0,
            Size::Combined(pix, per) => (pix.to_float() / width) + (per.to_float() / 100.0),
        };

        let normalized_y = match y {
            Size::Pixels(val) => val.to_float() / height,
            Size::Percent(val) => val.to_float() / 100.0,
            Size::Combined(pix, per) => (pix.to_float() / width) + (per.to_float() / 100.0),
        };
        UnitPoint::new(normalized_x, normalized_y)
    }

    // Converts Pax gradient stops into Piet's gradient-stop representation.
    pub fn to_piet_gradient_stops(stops: Vec<GradientStop>) -> Vec<piet::GradientStop> {
        let mut ret = Vec::new();
        for gradient_stop in stops {
            match gradient_stop.position {
                Size::Pixels(_) => {
                    panic!("Gradient stops must be specified in percentages");
                }
                Size::Percent(p) => {
                    ret.push(piet::GradientStop {
                        pos: (p.to_float() / 100.0) as f32,
                        color: gradient_stop.color.to_piet_color(),
                    });
                }
                Size::Combined(_, _) => {
                    panic!("Gradient stops must be specified in percentages");
                }
            }
        }
        ret
    }

    #[allow(non_snake_case)]
    /// Constructs a linear gradient paint.
    ///
    /// Pax templates should normally use `@gradient`. When this helper is
    /// needed explicitly, pass `start` and `end` as `[x, y]` lists.
    pub fn linearGradient(
        start: (Size, Size),
        end: (Size, Size),
        stops: Vec<GradientStop>,
    ) -> Paint {
        Paint::LinearGradient(LinearGradient { start, end, stops })
    }

    /// Returns a copy of this paint with alpha multiplied by `factor`.
    pub fn with_alpha_factor(&self, factor: f64) -> Paint {
        match self {
            Paint::Blend(terms) => Paint::Blend(
                terms
                    .iter()
                    .map(|(fill, weight)| (fill.with_alpha_factor(factor), *weight))
                    .collect(),
            ),
            Paint::Solid(color) => Paint::Solid(color.with_alpha_factor(factor)),
            Paint::MeshGradient(_) => {
                // Scale the sampled field after cubic clamping. Scaling anchor alpha would
                // change overshoot regions and is not equivalent to paint opacity.
                let factor = factor.clamp(0.0, 1.0);
                Paint::blend(vec![
                    (self.clone(), factor),
                    (Paint::Solid(Color::TRANSPARENT), 1.0 - factor),
                ])
            }
            Paint::LinearGradient(gradient) => Paint::LinearGradient(LinearGradient {
                start: gradient.start.clone(),
                end: gradient.end.clone(),
                stops: gradient
                    .stops
                    .iter()
                    .map(|stop| stop.with_alpha_factor(factor))
                    .collect(),
            }),
            Paint::RadialGradient(gradient) => Paint::RadialGradient(RadialGradient {
                start: gradient.start.clone(),
                end: gradient.end.clone(),
                radius: gradient.radius,
                stops: gradient
                    .stops
                    .iter()
                    .map(|stop| stop.with_alpha_factor(factor))
                    .collect(),
            }),
        }
    }

    /// Returns a conservative upper bound for this paint's alpha. For mixtures,
    /// endpoint maxima need not occur at the same point.
    pub fn max_alpha_0_1(&self) -> f64 {
        match self {
            Paint::Blend(terms) => terms
                .iter()
                .map(|(fill, weight)| fill.max_alpha_0_1() * weight)
                .sum::<f64>()
                .clamp(0.0, 1.0),
            Paint::Solid(color) => color.alpha_0_1(),
            Paint::MeshGradient(mesh) => {
                // Cubics can overshoot anchor alpha. Only the all-transparent field is
                // certainly invisible; max(anchor alpha) is not a conservative bound.
                if mesh
                    .rows
                    .iter()
                    .flatten()
                    .any(|p| p.color.alpha_0_1() > 0.0)
                {
                    1.0
                } else {
                    0.0
                }
            }
            Paint::LinearGradient(gradient) => gradient
                .stops
                .iter()
                .map(|stop| stop.color.alpha_0_1())
                .fold(0.0, f64::max),
            Paint::RadialGradient(gradient) => gradient
                .stops
                .iter()
                .map(|stop| stop.color.alpha_0_1())
                .fold(0.0, f64::max),
        }
    }

    /// Estimates the alpha coverage contributed by this fill.
    pub fn coverage_alpha_0_1(&self) -> f64 {
        match self {
            Paint::Blend(terms) => terms
                .iter()
                .map(|(fill, weight)| fill.coverage_alpha_0_1() * weight)
                .sum::<f64>()
                .clamp(0.0, 1.0),
            Paint::Solid(color) => color.alpha_0_1(),
            Paint::LinearGradient(gradient) => Self::integrated_gradient_alpha_0_1(&gradient.stops),
            Paint::RadialGradient(gradient) => Self::integrated_gradient_alpha_0_1(&gradient.stops),
            Paint::MeshGradient(_) => self.max_alpha_0_1(),
        }
    }
}

#[cfg(test)]
mod fill_coverage_tests {
    fn gradient(color: Color) -> Paint {
        Paint::linearGradient(
            (Size::Percent(0.into()), Size::Percent(0.into())),
            (Size::Percent(100.into()), Size::Percent(100.into())),
            vec![GradientStop::get(color, Size::Percent(0.into()))],
        )
    }

    #[test]
    fn transparent_paint_crossfade_uses_premultiplied_color_and_alpha() {
        use super::*;
        let from = gradient(Color::from_rgba_0_1([1.0, 0.0, 0.0, 0.0]));
        let to = Paint::Solid(Color::from_rgba_0_1([0.0, 0.0, 1.0, 0.5]));
        let halfway = from.interpolate(&to, 0.5);
        assert_eq!(
            halfway.representative_color().to_rgba_0_1(),
            [0.0, 0.0, 1.0, 0.25]
        );
        assert_eq!(halfway.max_alpha_0_1(), 0.25);
        assert_eq!(halfway.with_alpha_factor(0.5).max_alpha_0_1(), 0.125);
        assert_eq!(from.interpolate(&to, 0.0), from);
        assert_eq!(from.interpolate(&to, 1.0), to);
    }

    #[test]
    fn interrupted_gradient_reversals_remain_flat_continuous_and_bounded() {
        use super::*;
        let dark = gradient(Color::BLACK);
        let light = gradient(Color::WHITE);
        let mut displayed = dark.clone();
        for i in 0..1000 {
            let target = if i % 2 == 0 { &light } else { &dark };
            assert_eq!(displayed.interpolate(target, 0.0), displayed);
            let before = displayed.representative_color().to_rgba_0_1();
            displayed = displayed.interpolate(target, 0.07);
            let after = displayed.representative_color().to_rgba_0_1();
            let expected = target.representative_color().to_rgba_0_1();
            for channel in 0..4 {
                assert!(
                    (after[channel] - (before[channel] * 0.93 + expected[channel] * 0.07)).abs()
                        < 1e-12
                );
            }
            let Paint::Blend(terms) = &displayed else {
                panic!("expected mixture");
            };
            assert_eq!(terms.len(), 2);
            assert!(terms
                .iter()
                .all(|(fill, _)| !matches!(fill, Paint::Blend(_))));
            let roundtrip = Paint::try_coerce(displayed.clone().to_pax_value()).unwrap();
            for (a, b) in roundtrip
                .representative_color()
                .to_rgba_0_1()
                .into_iter()
                .zip(after)
            {
                assert!((a - b).abs() < 1e-12);
            }
        }
        assert_eq!(displayed.interpolate(&light, 1.0), light);
    }

    #[test]
    fn crossfade_keeps_different_gradient_kinds_geometry_and_stop_lists() {
        use super::*;
        let from = gradient(Color::BLACK);
        let to = Paint::RadialGradient(RadialGradient {
            start: (Size::Pixels(12.into()), Size::Percent(50.into())),
            end: (Size::Percent(100.into()), Size::Percent(50.into())),
            radius: 0.5,
            stops: vec![
                GradientStop::get(Color::WHITE, Size::Percent(20.into())),
                GradientStop::get(Color::BLACK, Size::Percent(80.into())),
            ],
        });
        assert_eq!(
            from.interpolate(&to, 0.25),
            Paint::Blend(vec![(from, 0.75), (to, 0.25)])
        );
    }

    #[test]
    fn solid_fill_interpolates_rgba_channels() {
        use super::*;
        let from = Paint::Solid(Color::BLACK);
        let to = Paint::Solid(Color::WHITE);
        assert_eq!(
            from.interpolate(&to, 0.5),
            Paint::Solid(Color::BLACK.interpolate(&Color::WHITE, 0.5))
        );
    }
    use super::{Color, ColorChannel, GradientStop, LinearGradient, Numeric, Paint, Size};

    fn rgba_alpha(alpha: u8) -> Color {
        Color::rgba(
            ColorChannel::Integer(0),
            ColorChannel::Integer(0),
            ColorChannel::Integer(0),
            ColorChannel::Integer(alpha),
        )
    }

    #[test]
    fn coverage_alpha_matches_solid_alpha() {
        let fill = Paint::Solid(rgba_alpha(128));
        assert!((fill.coverage_alpha_0_1() - (128.0 / 255.0)).abs() < 1e-6);
    }

    #[test]
    fn coverage_alpha_integrates_gradient_stops() {
        let fill = Paint::LinearGradient(LinearGradient {
            start: (
                Size::Percent(Numeric::F64(0.0)),
                Size::Percent(Numeric::F64(50.0)),
            ),
            end: (
                Size::Percent(Numeric::F64(100.0)),
                Size::Percent(Numeric::F64(50.0)),
            ),
            stops: vec![
                GradientStop::get(rgba_alpha(0), Size::Percent(Numeric::F64(0.0))),
                GradientStop::get(rgba_alpha(255), Size::Percent(Numeric::F64(50.0))),
                GradientStop::get(rgba_alpha(0), Size::Percent(Numeric::F64(100.0))),
            ],
        });
        assert!((fill.coverage_alpha_0_1() - 0.5).abs() < 1e-6);
    }
}

/// Stable local reference frame for paint, independent of outline width and reveal.
/// A collapsed axis gets a centered one-logical-pixel span without adding coverage.
pub fn paint_bounds(mut rect: kurbo::Rect) -> Option<kurbo::Rect> {
    if ![rect.x0, rect.y0, rect.x1, rect.y1]
        .into_iter()
        .all(f64::is_finite)
    {
        log::warn!("Paint geometry must be finite");
        return None;
    }
    if rect.width() == 0.0 {
        rect.x0 -= 0.5;
        rect.x1 += 0.5;
    }
    if rect.height() == 0.0 {
        rect.y0 -= 0.5;
        rect.y1 += 0.5;
    }
    Some(rect)
}

impl Fill {
    pub(crate) fn validate_layer(&self) -> Result<(), String> {
        Ok(())
    }
}
impl Stroke {
    pub(crate) fn validate_layer(&self) -> Result<(), String> {
        if matches!(self.width.get(), Size::Pixels(_)) {
            Ok(())
        } else {
            Err("Stroke.width: expected logical pixels; percentage widths are unsupported".into())
        }
    }
}

#[cfg(test)]
mod appearance_tests {
    use super::*;
    use crate::properties::drain_effects;

    #[test]
    fn appearance_defaults_shorthand_and_errors() {
        let red = Color::RED.to_pax_value();
        let fills = Vec::<Fill>::try_coerce(red.clone()).unwrap();
        let strokes = Vec::<Stroke>::try_coerce(red).unwrap();
        assert_eq!(fills[0].paint.get(), Paint::Solid(Color::RED));
        assert_eq!(strokes[0].width_pixels(), 1.0);
        assert_eq!(fills[0].material.get(), Material::default());
        assert_eq!(fills[0].opacity.get().to_float_0_1(), 1.0);
        assert!(Vec::<Fill>::try_coerce(PaxValue::Vec(vec![]))
            .unwrap()
            .is_empty());
        assert!(Vec::<Numeric>::try_coerce(1.to_pax_value()).is_err());
        for invalid in [
            Stroke::default().to_pax_value(),
            PaxValue::Vec(vec![]),
            PaxValue::Option(Box::new(None)),
            PaxValue::Object(vec![("color".into(), Color::RED.to_pax_value())]),
        ] {
            let error =
                Vec::<Fill>::try_coerce(PaxValue::Vec(vec![Color::RED.to_pax_value(), invalid]))
                    .unwrap_err();
            assert!(error.contains("[1]"), "{error}");
        }
        assert!(Stroke::try_coerce(PaxValue::Object(vec![(
            "width".into(),
            Size::Percent(10.into()).to_pax_value()
        )]))
        .is_err());
    }

    #[test]
    fn layers_interpolate_by_position_and_switch_lengths_immediately() {
        let a = vec![Fill::from(Color::RED)];
        let b = vec![Fill::from(Color::BLUE)];
        assert_eq!(
            a.interpolate(&b, 0.5)[0].paint.get(),
            Paint::Solid(Color::RED.interpolate(&Color::BLUE, 0.5))
        );
        let longer = vec![Fill::from(Color::BLUE), Fill::from(Color::GREEN)];
        assert_eq!(a.interpolate(&longer, 0.1), longer);
        let a = Stroke::default();
        let b = Stroke::default();
        b.cap.set(StrokeCap::Round);
        assert_eq!(a.interpolate(&b, 0.99).cap.get(), StrokeCap::Butt);
        assert_eq!(a.interpolate(&b, 1.0).cap.get(), StrokeCap::Round);
    }

    #[test]
    fn expression_adapter_observes_nested_edits_and_releases_removed_layers() {
        let graph = crate::properties::PropertyGraph::new(|| {});
        let _entered = graph.enter();
        let first = Fill::from(Color::RED);
        let source = Property::new(vec![first.clone()]);
        let variable = Variable::new_from_typed_property(source.clone());
        let read = || Vec::<Fill>::try_coerce(variable.get_as_pax_value()).unwrap();
        assert_eq!(read()[0].paint.get(), Paint::Solid(Color::RED));
        first.paint.local().set(Paint::Solid(Color::BLUE));
        assert!(drain_effects(100) < 100);
        assert_eq!(read()[0].paint.get(), Paint::Solid(Color::BLUE));
        source.local().set(vec![]);
        assert!(read().is_empty());
        first.paint.local().set(Paint::Solid(Color::WHITE));
        assert!(drain_effects(100) < 100);
        assert!(read().is_empty());
    }

    #[test]
    fn nested_appearance_subscriptions_retire_after_replacement_and_disposal() {
        let graph = crate::properties::PropertyGraph::new(|| {});
        let _entered = graph.enter();
        use crate::properties::property_table_total_properties_count;
        let baseline = property_table_total_properties_count();
        for _ in 0..30 {
            let scope = graph.binding_scope();
            let _scope = scope.enter();
            let source = Property::new(vec![Fill::from(Color::RED)]);
            let variable = Variable::new_from_typed_property(source.clone());
            variable.get_as_pax_value();
            source.local().get()[0]
                .opacity
                .local()
                .set(Opacity::from(0.25));
            drain_effects(100);
            variable.get_as_pax_value();
            source
                .local()
                .set(vec![Fill::from(Color::BLUE), Fill::from(Color::GREEN)]);
            variable.get_as_pax_value();
            source.local().set(vec![]);
            variable.get_as_pax_value();
            // A mounted view owns its shared projections until final unmount.
            scope.close();
        }
        drain_effects(100);
        graph.collect();
        assert_eq!(property_table_total_properties_count(), baseline);
    }

    #[test]
    fn degenerate_paint_domain_and_nonfinite_opacity_are_finite() {
        let rect = paint_bounds(kurbo::Rect::new(25.0, 40.0, 125.0, 40.0)).unwrap();
        assert_eq!(rect, kurbo::Rect::new(25.0, 39.5, 125.0, 40.5));
        assert!(paint_bounds(kurbo::Rect::new(f64::NAN, 0.0, 1.0, 1.0)).is_none());
        for alpha in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            assert_eq!(Opacity::from(alpha).to_float_0_1(), 0.0);
        }
    }
}