drawland-core 0.5.0

Maps drawn for pen plotters: OSM features to a layered SVG. No I/O.
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
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
//! Running a v3 grammar: the def DAG in, SVG groups out.
//!
//! [`crate::grammar`] validates the profile; this module gives it meaning. Every
//! def evaluates to one of three things, decided by its section:
//!
//! - `$features` → a set of features, from Overpass (`osm_select`) or the
//!   vector tiles (`tiles_select`)
//! - `$areas`    → a [`MultiPolygon`] in output millimetres
//! - `$lines`    → a [`Lines`] in output millimetres
//! - `$fills`    → a `Lines` too, but produced by penfill
//!
//! Evaluation is in waves over the def DAG, so a def that references another
//! simply reads the value already computed. Fills run last, when every area is
//! known. Nothing here recomputes geometry: `$areas.dissolved` used by six defs
//! is evaluated once.
//!
//! Draw order and occlusion come from `compose`: each mask subtracts only from
//! the group ids it lists in `occludes`, so an output can draw a dotted schools
//! layer on top of everything and not cut it.

use crate::fill::{self, FillError, Sources};
use crate::geom::{self, Lines};
use crate::output::Output;
use crate::grammar::{Clip, Def, Grammar, LineBufferCap, Mask, Name, Op, Section, UnionRules};
use crate::osm::Feature;
use crate::progress::{thousands, Level, Task};
use crate::select::Selector;
use geo::{Coord, LineString, MultiPolygon, Polygon};
use rayon::prelude::*;
use std::collections::{BTreeMap, BTreeSet};

#[derive(Debug, thiserror::Error)]
pub enum RunError {
    #[error("{0}")]
    Plan(String),
    #[error("{0}")]
    Fill(#[from] FillError),
    #[error("def {def}: {source}")]
    Def { def: String, source: FillError },
    /// A fill that would not fit the host's memory, with what to do about it.
    #[error("{0}")]
    TooLarge(String),
}

/// One evaluated def, or one named output published by a module.
#[derive(Clone)]
enum Value {
    Features(Vec<Feature>),
    Area(MultiPolygon<f64>),
    Lines(Lines),
    /// `tools_labels`: the letters' strokes, read as lines, and what they cover.
    Labels(crate::labels::Placed),
    /// `module_roads` output, carrying all of them at once.
    Module {
        area: MultiPolygon<f64>,
        outlines: Lines,
        details: Lines,
        trails: Lines,
        centerlines: Lines,
        seams: Lines,
        rails: Lines,
    },
}

impl Value {
    fn area(&self, def: &Name) -> Result<&MultiPolygon<f64>, RunError> {
        match self {
            Value::Area(a) | Value::Module { area: a, .. } => Ok(a),
            _ => Err(RunError::Plan(format!("{def} is not an area"))),
        }
    }

    fn lines(&self, def: &Name) -> Result<&Lines, RunError> {
        match self {
            Value::Lines(l) | Value::Labels(crate::labels::Placed { lines: l, .. }) => Ok(l),
            _ => Err(RunError::Plan(format!("{def} is not a line set"))),
        }
    }

    fn features(&self, def: &Name) -> Result<&[Feature], RunError> {
        match self {
            Value::Features(f) => Ok(f),
            _ => Err(RunError::Plan(format!("{def} is not a feature set"))),
        }
    }
}

pub struct Rendered {
    pub svg: String,
    /// `(group id, stroke count)` in draw order.
    pub groups: Vec<(String, usize)>,
    /// `(name, svg)` per sheet when the output is cut (`output.slices`).
    pub slices: Vec<(String, String)>,
}

pub struct Inputs<'a> {
    /// Features in lon/lat, as `osm::features_from_overpass` returns them.
    pub features: Vec<Feature>,
    /// Vector tile features in lon/lat, as `tiles::Tiles::features` returns
    /// them: what `tiles_select` picks from.
    pub tiles: Vec<Feature>,
    /// SVG text of every file named by a fill `source`.
    pub sources: &'a BTreeMap<String, String>,
    /// The elevation under the output, read by the host when a def draws
    /// terrain; `None` when none does, so a document that never asks costs
    /// nothing.
    pub terrain: Option<crate::terrain::Grid>,
    /// Bytes the filling may use at most; `None` draws without a ceiling.
    pub memory_budget: Option<u64>,
    /// TTF bytes for `modules.labels` Google fonts, keyed by `text::google_font_key`.
    pub google_fonts: BTreeMap<String, Vec<u8>>,
    /// SVG/JHF bytes for single-stroke fonts, keyed by URL (see `text::LabelFont::stroke_font_key`).
    pub stroke_fonts: BTreeMap<String, Vec<u8>>,
    /// GeoJSON text of every `data_select` source, keyed as written
    /// (`Grammar::datasets`).
    pub data: BTreeMap<String, String>,
    /// What each of `grammar.views` reads, in the same order: every view is
    /// another place, so it has its own features, tiles, terrain and fonts.
    pub views: Vec<Inputs<'a>>,
}

/// A view's groups, made but not written: `(id, stroke, lines)` in order.
type Collected = Vec<(String, Option<crate::profile::StrokeSpec>, Lines)>;

/// Evaluate `grammar` against `inputs`, project to `output`, compose and write.
pub fn run(grammar: &Grammar, output: &Output, inputs: Inputs) -> Result<Rendered, RunError> {
    let draw = Task::begin(&(), "draw", None, "draw", 0, "");
    let out = run_with(grammar, output, inputs, &draw)?;
    draw.ok("");
    Ok(out)
}

/// Whether to note resident memory at each step: `DRAWLAND_MEM` in the
/// environment. Off by default; the notes go into the same progress log the
/// terminal already shows.
fn probing() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *ON.get_or_init(|| std::env::var_os("DRAWLAND_MEM").is_some())
}

/// One line of memory at a named step, when probing.
fn probe(draw: &Task, what: &str) {
    if probing() {
        draw.log(Level::Info, &format!("mem {what}: {}", crate::progress::human_bytes(crate::progress::resident_bytes())));
    }
}

struct CoverCacheGuard;

impl Drop for CoverCacheGuard {
    fn drop(&mut self) {
        crate::fill::clear_cover_cache();
    }
}


/// [`run`], with every step a task under `draw`: projecting, the defs, each
/// fill, composing, writing.
pub fn run_with(grammar: &Grammar, output: &Output, inputs: Inputs, draw: &Task) -> Result<Rendered, RunError> {
    let mut parts: Vec<String> = Vec::new();
    let drawn = run_into(grammar, output, inputs, draw, &mut |k, text| {
        if parts.len() <= k {
            parts.resize(k + 1, String::new());
        }
        parts[k].push_str(text);
    })?;
    let mut parts = parts.into_iter();
    let svg = parts.next().unwrap_or_default();
    Ok(Rendered { svg, groups: drawn.groups, slices: drawn.slices.into_iter().zip(parts).collect() })
}

/// What [`run_into`] drew, beside the text it wrote.
pub struct Drawn {
    /// `(group id, stroke count)` in draw order.
    pub groups: Vec<(String, usize)>,
    /// The sheets' names when the output is cut: part `k` of the text is
    /// sheet `k - 1`.
    pub slices: Vec<String>,
}

/// [`run_with`], the SVG text handed to `out` in pieces as it is written:
/// part 0 the whole output, part `k` the `k`th sheet. Every group is
/// generated, masked, cut and written a batch of strokes at a time, so the
/// drawing is never in memory whole, as lines or as text.
pub fn run_into(grammar: &Grammar, output: &Output, inputs: Inputs, draw: &Task, out: &mut crate::sheets::Out) -> Result<Drawn, RunError> {
    run_graph(grammar, output, inputs, draw, out, Want::Write)
}

/// One `paint` entry evaluated: its geometry, in output units, and its look
/// as written, expressions and all; [`resolve`] makes it the layers of a
/// frame.
#[derive(Debug, Clone)]
pub struct Layer {
    pub id: String,
    pub style: crate::paint::Style,
    pub shown: crate::paint::Shown,
    pub halo: crate::paint::Halo,
    pub shape: PaintShape,
    /// The named features' tags, by `Named::feature`, when the look or the
    /// filter reads them (empty otherwise).
    pub tags: std::sync::Arc<Vec<crate::osm::Tags>>,
}

impl Layer {
    /// The layer with no geometry: its look, its showing, its tags, to be
    /// given other geometry (`Layer { shape, ..l.clone_bare() }`).
    pub fn clone_bare(&self) -> Layer {
        Layer { id: self.id.clone(), style: self.style.clone(), shown: self.shown.clone(), halo: self.halo, shape: PaintShape::Lines(Vec::new()), tags: self.tags.clone() }
    }
}

impl From<Painted> for Layer {
    /// A layer of one look, shown always.
    fn from(p: Painted) -> Layer {
        Layer { id: p.id, style: crate::paint::Style::fixed(p.look), shown: Default::default(), halo: p.halo, shape: p.shape, tags: Default::default() }
    }
}

/// The layers as a frame shows them: those its zoom hides left out, each
/// look resolved for the frame, the features a filter drops dropped. A
/// layer of names whose look reads their tags becomes one layer for each
/// look its names take, in its place, the larger letters over (and placed
/// before) the smaller.
pub fn resolve(layers: Vec<Layer>, frame: crate::expr::Frame) -> Vec<Painted> {
    use crate::expr::Context;
    use crate::paint::Look;
    let mut out = Vec::new();
    for layer in layers {
        if !layer.shown.at(frame.zoom) {
            continue;
        }
        let at = Context { frame, tags: None };
        let per_feature = layer.style.reads().or(layer.shown.reads()).feature;
        let upper = |look: &Look, n: &mut crate::labels::Named| {
            if matches!(look, Look::Text(t) if t.upper) {
                n.text = n.text.to_uppercase();
            }
        };
        match layer.shape {
            PaintShape::Names(names) if per_feature => {
                let mut groups: Vec<(Look, Vec<crate::labels::Named>)> = Vec::new();
                for mut n in names {
                    let cx = Context { frame, tags: layer.tags.get(n.feature) };
                    if !layer.shown.keeps(&cx) {
                        continue;
                    }
                    let Some(look) = layer.style.resolve(&cx) else { continue };
                    upper(&look, &mut n);
                    match groups.iter_mut().find(|(l, _)| *l == look) {
                        Some((_, g)) => g.push(n),
                        None => groups.push((look, vec![n])),
                    }
                }
                // The larger letters last: over the others, and placed first.
                groups.sort_by_key(|(l, _)| match l {
                    Look::Text(t) => crate::paint::FONTS.iter().position(|f| *f == t.font).unwrap_or(0),
                    _ => 0,
                });
                for (look, names) in groups {
                    out.push(Painted { id: layer.id.clone(), look, halo: layer.halo, shape: PaintShape::Names(names) });
                }
            }
            shape => {
                if !layer.shown.keeps(&at) {
                    continue;
                }
                let Some(look) = layer.style.resolve(&at) else { continue };
                let shape = match shape {
                    PaintShape::Names(mut names) => {
                        names.iter_mut().for_each(|n| upper(&look, n));
                        PaintShape::Names(names)
                    }
                    other => other,
                };
                out.push(Painted { id: layer.id, look, halo: layer.halo, shape });
            }
        }
    }
    out
}

/// One layer of a frame: its geometry, in output units, and the look it is
/// painted in.
#[derive(Debug, Clone)]
pub struct Painted {
    pub id: String,
    pub look: crate::paint::Look,
    pub halo: crate::paint::Halo,
    pub shape: PaintShape,
}

#[derive(Debug, Clone)]
pub enum PaintShape {
    Area(MultiPolygon<f64>),
    Lines(Lines),
    /// The names of the features, most important first (`labels::named`),
    /// the text already read from the entry's `keys`.
    Names(Vec<crate::labels::Named>),
}

/// The graph's `paint` entries evaluated against `inputs`, bottom first: the
/// layers a screen is covered with, to be [`resolve`]d for a frame
/// (`drawland-grid` paints them).
pub fn paint(grammar: &Grammar, output: &Output, inputs: Inputs, draw: &Task) -> Result<Vec<Layer>, RunError> {
    if grammar.output.screen.is_none() {
        return Err(RunError::Plan("paint: the output is paper; give it a screen, output({ screen: { kind, width, height } })".into()));
    }
    if !grammar.views.is_empty() {
        return Err(RunError::Plan("views are drawn on paper; a screen has none yet".into()));
    }
    let mut painted = Vec::new();
    run_graph(grammar, output, inputs, draw, &mut |_, _| {}, Want::Paint(&mut painted))?;
    Ok(painted)
}

/// What a run makes of the evaluated graph.
enum Want<'a> {
    /// The SVG, written.
    Write,
    /// A view's groups, handed back for its page to write.
    Collect(&'a mut Collected),
    /// The paint entries' geometry, for a screen.
    Paint(&'a mut Vec<Layer>),
}

/// Each paint entry's geometry, read from the evaluated graph.
fn painted(grammar: &Grammar, values: &BTreeMap<Name, Value>, page: f64) -> Result<Vec<Layer>, RunError> {
    use crate::paint::Look;
    let mut out = Vec::new();
    for p in &grammar.paint {
        let mut tags = Vec::new();
        let shape = match (&p.from.module, p.look.base()) {
            (Some(module), Look::Line(_)) => {
                let value = module_output(module, &p.from.name.name, values, grammar)?;
                let mut unused = BTreeMap::new();
                match module_lines(module, &p.from.name.name, value, &p.id, &mut unused)? {
                    Some(lines) => PaintShape::Lines(lines.clone()),
                    None => return Err(RunError::Plan(format!("paint {:?}: {module}.{} is an area", p.id, p.from.name.name))),
                }
            }
            (None, look) => {
                let value = values
                    .get(&p.from.name)
                    .ok_or_else(|| RunError::Plan(format!("paint {:?}: {} was not evaluated", p.id, p.from.name)))?;
                match look {
                    Look::Fill(_) => PaintShape::Area(value.area(&p.from.name)?.clone()),
                    Look::Line(_) => PaintShape::Lines(value.lines(&p.from.name)?.clone()),
                    Look::Text(t) => {
                        let features = value.features(&p.from.name)?;
                        if p.look.reads().or(p.shown.reads()).feature {
                            tags = features.iter().map(|f| f.tags.clone()).collect();
                        }
                        PaintShape::Names(crate::labels::named(features, &t.keys, page))
                    }
                }
            }
            (Some(module), _) => return Err(RunError::Plan(format!("paint {:?}: {module}.{} is lines", p.id, p.from.name.name))),
        };
        out.push(Layer { id: p.id.clone(), style: p.look.clone(), shown: p.shown.clone(), halo: p.halo, shape, tags: std::sync::Arc::new(tags) });
    }
    Ok(out)
}

/// [`run_into`], or as `want` says: the groups handed back instead of
/// written (a view, which its page writes), or a screen's paint entries.
fn run_graph(
    grammar: &Grammar,
    output: &Output,
    mut inputs: Inputs,
    draw: &Task,
    out: &mut crate::sheets::Out,
    want: Want,
) -> Result<Drawn, RunError> {
    // Fills fixed to the ground anchored at its point on this output, once,
    // so `fills.cover` and the fill still share one run.
    let grounded = grounded(grammar, output);
    let grammar = grounded.as_ref().unwrap_or(grammar);
    let view_inputs = std::mem::take(&mut inputs.views);
    let mut sources = Sources::new();
    for (file, text) in inputs.sources {
        let drawing =
            penfill::svg::parse_svg(text).map_err(|msg| RunError::Plan(format!("source {file:?}: {msg}")))?;
        sources.insert(file.clone(), drawing);
    }

    // Every dataset read once, keyed by how it is read (a JSON source is its
    // URL and paths, so two readings of one reply stay apart).
    let mut data: BTreeMap<String, Vec<Feature>> = BTreeMap::new();
    for def in grammar.all_defs() {
        let Op::DataSelect(source) = &def.op else { continue };
        let (Some(url), key) = (source.url(), data_key(source)) else { continue };
        if data.contains_key(&key) {
            continue;
        }
        let text = inputs.data.get(url).ok_or_else(|| RunError::Plan(format!("dataset {url:?} was not given")))?;
        let found = match source {
            crate::grammar::DataSource::Json(j) => crate::geojson::features_from_json(text, &j.items, &j.lat, &j.lng),
            _ => crate::geojson::features(text),
        }
        .map_err(|e| RunError::Plan(format!("dataset {url:?}: {e}")))?;
        data.insert(key, found);
    }
    let data_n: usize = data.values().map(Vec::len).sum();
    let project = draw.child("project", "project", (inputs.features.len() + inputs.tiles.len() + data_n) as u64, "features");
    let projector = crate::projection::Projector::new(output);
    probe(draw, "start");
    let warp = &grammar.output.warp;
    let (w, h) = (output.width_mm, output.height_mm);
    let pole = output.pole_on_page(&projector);
    let projected = |features: Vec<Feature>| -> Vec<Feature> {
        features
            .into_par_iter()
            .map(|mut f| {
                // A globe shows its near side: the rest is cut off first.
                let seen = projector.visible(&f.geometry);
                let mut g = projector.project_geometry(seen.as_ref().unwrap_or(&f.geometry));
                // Round a pole, an area meets itself along the antimeridian
                // once projected; a globe's cut areas are whole already, and
                // a lake cut at the rim lies along the sea's own rim there,
                // which a union would fill.
                if pole.is_some() && seen.is_none() {
                    g = mended(g);
                }
                f.geometry = warp.bend(w, h, &g);
                project.tick();
                f
            })
            .collect()
    };
    let features = projected(inputs.features);
    let mut tiles = projected(inputs.tiles);
    if pole == Some(90.0) {
        tiles.extend(arctic_cap(&tiles, &projector));
    }
    let data: BTreeMap<String, Vec<Feature>> = data.into_iter().map(|(k, v)| (k, projected(v))).collect();
    probe(draw, "projected");
    let frame = MultiPolygon::new(vec![Polygon::new(
        LineString::new(vec![
            Coord { x: 0.0, y: 0.0 },
            Coord { x: w, y: 0.0 },
            Coord { x: w, y: h },
            Coord { x: 0.0, y: h },
            Coord { x: 0.0, y: 0.0 },
        ]),
        vec![],
    )]);
    let mut decompressed_fonts: BTreeMap<String, Vec<u8>> = BTreeMap::new();
    for (k, raw) in &inputs.google_fonts {
        // Every file of the face (subsets) decoded once, kept as a bundle.
        let faces = crate::google_fonts::faces_of(raw).map_err(RunError::Plan)?;
        let decoded = if faces.len() == 1 { faces.into_iter().next().unwrap() } else { crate::google_fonts::bundle(&faces) };
        decompressed_fonts.insert(k.clone(), decoded);
    }
    let spec = &grammar.output;
    let drawable = crate::sheets::drawable_area(w, h, spec.padding, &spec.slices);
    // A mesh may carry the page's edge anywhere: what is drawn is the page's
    // ground where the mesh puts it, and the paper clips the rest.
    let bent = |a: &MultiPolygon<f64>| {
        let b = warp.bend_area(w, h, a);
        if warp.moves_edge() { geo::BooleanOps::intersection(&b, a) } else { b }
    };
    let engine = Engine {
        of: output,
        output: bent(&frame),
        drawable: bent(&drawable),
        terrain: inputs.terrain.as_ref(),
        projector: &projector,
        google_fonts: &decompressed_fonts,
        stroke_fonts: &inputs.stroke_fonts,
        warp,
        sources: &sources,
        smoothed: Default::default(),
    };
    project.ok("");
    // Past the bent frame a mesh is only carried on (its edge move held), so
    // nothing is drawn there: the paper outside it masks every group.
    let beyond = if warp.moves_edge() { geom::difference(&frame, &engine.output) } else { geom::empty() };

    crate::fill::clear_cover_cache();
    let _cover_guard = CoverCacheGuard;
    let unmerged = unmerged(grammar, matches!(want, Want::Paint(_)));
    let found = Found { osm: &features, tiles: &tiles, by_layer: crate::tiles::by_layer(&tiles), data: &data };
    let values = evaluate(grammar, &found, &engine, draw, &unmerged)?;
    probe(draw, "areas+lines");
    let collect = match want {
        Want::Write => None,
        Want::Collect(c) => Some(c),
        Want::Paint(into) => {
            *into = painted(grammar, &values, w * h)?;
            return Ok(Drawn { groups: Vec::new(), slices: Vec::new() });
        }
    };

    // The views first, under the page's own groups, and before the page
    // opens its own rows (a view has rows of the same names).
    let spec = &grammar.output;
    let mut layout = crate::sheets::Layout::new(output.width_mm, output.height_mm, spec.padding, &spec.slices);
    let mut written = 0usize;
    let mut counted = |k: usize, text: &str| {
        if k == 0 {
            written += text.len();
        }
        out(k, text);
    };
    if collect.is_none() {
        draw_views(grammar, &values, view_inputs, draw, &mut layout, &mut counted)?;
    }

    // Fills are not made here but in their group, as it is written: one
    // batch of strokes alive at a time.
    let fill_count = grammar.defs(Section::Fills).iter().filter(|d| matches!(d.op, Op::Fill(_))).count();
    let fills_task = draw.child("fills", "fills", fill_count as u64, "fills");
    let compose_task = draw.child("compose", "compose", 0, "");
    let fills = Fills { values: &values, sources: &sources, budget: inputs.memory_budget, task: &fills_task };
    if let Some(collect) = collect {
        compose(grammar, &values, &fills, &beyond, &compose_task, &mut layout, &mut counted, Some(collect))?;
        fills_task.ok("");
        compose_task.ok("");
        return Ok(Drawn { groups: Vec::new(), slices: Vec::new() });
    }
    compose(grammar, &values, &fills, &beyond, &compose_task, &mut layout, &mut counted, None)?;
    let (groups, slices) = layout.finish(&mut counted);
    fills_task.ok("");
    compose_task.ok(&format!("{} groups", groups.len()));
    probe(draw, "composed");

    let strokes: usize = groups.iter().map(|(_, n)| n).sum();
    let cut = if slices.is_empty() { String::new() } else { format!(" · {} slices", slices.len()) };
    draw.child("svg", "svg", 0, "").ok(&format!("{} strokes · {:.1} MB{cut}", thousands(strokes as u64), written as f64 / 1e6));
    Ok(Drawn { groups, slices })
}

/// How a read dataset is kept: a GeoJSON URL by itself, a JSON source by its
/// URL and the paths it reads.
fn data_key(source: &crate::grammar::DataSource) -> String {
    match source {
        crate::grammar::DataSource::Json(j) => format!("json\u{1}{}\u{1}{}\u{1}{}\u{1}{}", j.url, j.items, j.lat, j.lng),
        other => other.url().unwrap_or_default().to_string(),
    }
}

/// The features a selection picks from, in output millimetres.
struct Found<'a> {
    osm: &'a [Feature],
    tiles: &'a [Feature],
    /// Where each tile layer's features are in `tiles`, so a selection reads
    /// only its own layers: a city's million buildings are not passed over
    /// for its rivers.
    by_layer: BTreeMap<&'a str, Vec<usize>>,
    /// Each dataset's features, by source.
    data: &'a BTreeMap<String, Vec<Feature>>,
}

/// The output, and the `engine_*` areas in output millimetres like everything
/// evaluated.
struct Engine<'a> {
    of: &'a Output,
    output: MultiPolygon<f64>,
    /// The area actually drawn after `output.padding` and `output.slices.gutter`.
    drawable: MultiPolygon<f64>,
    /// The elevation under the output, when a def draws terrain; `None` when
    /// none does, so nothing is fetched for a document that never asks.
    terrain: Option<&'a crate::terrain::Grid>,
    /// The projection, so terrain pixels land in the same millimetres.
    projector: &'a crate::projection::Projector,
    google_fonts: &'a crate::labels::GoogleFonts,
    stroke_fonts: &'a crate::labels::StrokeFonts,
    /// The output's warp, for features read after projecting (inline GeoJSON).
    warp: &'a crate::warp::Warps,
    /// The SVG files fills may draw from, for a fill made early.
    sources: &'a Sources,
    /// The elevation smoothed by each blur (px) asked, made once: an atlas's
    /// bands all cut the same smoothed heights.
    smoothed: std::sync::Mutex<BTreeMap<usize, std::sync::Arc<std::sync::OnceLock<crate::terrain::Grid>>>>,
}

impl Engine<'_> {
    /// `grid` (the elevation) smoothed by `blur`, the first band to ask
    /// making it for the rest.
    fn smoothed(&self, grid: &crate::terrain::Grid, blur: f64) -> std::sync::Arc<std::sync::OnceLock<crate::terrain::Grid>> {
        let cell = self.smoothed.lock().unwrap().entry(blur.round().max(0.0) as usize).or_default().clone();
        cell.get_or_init(|| crate::terrain::smoothed(grid, blur));
        cell
    }

    /// lon/lat → output mm, warped: what every host feature went through.
    fn warp_project(&self, g: &geo::Geometry<f64>) -> geo::Geometry<f64> {
        let seen = self.projector.visible(g);
        self.warp.bend(self.of.width_mm, self.of.height_mm, &self.projector.project_geometry(seen.as_ref().unwrap_or(g)))
    }
}

/// An area projected round a pole on the page, made valid: its own union.
fn mended(g: geo::Geometry<f64>) -> geo::Geometry<f64> {
    use geo::Geometry;
    match g {
        Geometry::Polygon(p) => Geometry::MultiPolygon(geom::union_multi([&MultiPolygon::new(vec![p])])),
        Geometry::MultiPolygon(m) => Geometry::MultiPolygon(geom::union_multi([&m])),
        other => other,
    }
}

/// The sea round the North Pole above web Mercator's edge (85.05°), where the
/// tiles end: all of it the Arctic Ocean (the northernmost land is at 83.7°),
/// as one more of the tiles' ocean features. Round the South Pole that cap
/// is Antarctica's land, and nothing is added.
fn arctic_cap(tiles: &[Feature], projector: &crate::projection::Projector) -> Option<Feature> {
    let ocean = tiles.iter().find(|f| {
        f.tags.get(crate::tiles::LAYER_TAG).is_some_and(|l| l == "water") && f.tags.get("class").is_some_and(|c| c == "ocean")
    })?;
    // A little past the tiles' edge, so the cap overlaps the sea it joins.
    const EDGE: f64 = 85.0;
    // In lon/lat, then as every feature is: a globe cuts it at its horizon.
    // The band from the edge to the pole, east along the edge and back west
    // along the pole: an area in lon/lat too, so whoever reads its turn
    // (a globe's cut) reads it right. The edge alone, out and back, has none,
    // and a globe seen from near the equator took it for all but the cap.
    let mut ring: Vec<Coord<f64>> = (0..=720).map(|i| Coord { x: -180.0 + i as f64 * 0.5, y: EDGE }).collect();
    ring.extend([Coord { x: 180.0, y: 90.0 }, Coord { x: -180.0, y: 90.0 }, Coord { x: -180.0, y: EDGE }]);
    let cap = geo::Geometry::Polygon(Polygon::new(LineString::new(ring), vec![]));
    let seen = projector.visible(&cap);
    let projected = projector.project_geometry(seen.as_ref().unwrap_or(&cap));
    let geometry = if seen.is_some() { projected } else { mended(projected) };
    Some(Feature {
        geometry,
        id: -1,
        ..ocean.clone()
    })
}

/// A profile's shape on the page, in output mm.
fn shape_points(s: &crate::grammar::Shape, engine: &Engine) -> Vec<Coord<f64>> {
    use crate::grammar::{PagePos, ShapeAt};
    let page = |p: &PagePos, size: f64| match p {
        PagePos::Mm(m) => m.0,
        PagePos::Percent(t) => crate::grammar::percent(t).unwrap_or(0.0) * size,
    };
    let (ax, ay) = match &s.at {
        // Where the drawn (warped) map puts the place.
        ShapeAt::Geo { lat, lng } => {
            let (x, y) = engine.projector.project(*lng, *lat);
            let c = engine.warp.point_at(engine.of.width_mm, engine.of.height_mm, Coord { x, y });
            (c.x, c.y)
        }
        ShapeAt::Page([x, y]) => (page(x, engine.of.width_mm), page(y, engine.of.height_mm)),
    };
    let (sin, cos) = s.rotate.to_radians().sin_cos();
    s.points
        .iter()
        .map(|[dx, dy]| Coord { x: ax + dx * cos - dy * sin, y: ay + dx * sin + dy * cos })
        .collect()
}

/// A profile's text on the page: the pen strokes, and the letters' silhouette.
fn text_on_page(t: &crate::grammar::Text, engine: &Engine) -> Result<(geom::Lines, MultiPolygon<f64>), String> {
    let bytes = match t.font.google_key() {
        Some(k) => Some(
            engine
                .google_fonts
                .get(&k)
                .map(Vec::as_slice)
                .ok_or_else(|| format!("text: google font {k} was not loaded"))?,
        ),
        None => None,
    };
    let stroke = t.font.stroke_font_key().and_then(|k| engine.stroke_fonts.get(&k).map(Vec::as_slice));
    let layout = crate::text::layout(&t.font, bytes, stroke, &t.text)?;
    let k = t.size.0 / layout.cap_height;
    let (cx, cy) = (layout.width / 2.0, (layout.top + layout.bottom) / 2.0);
    let shape = crate::grammar::Shape { at: t.at.clone(), points: vec![], rotate: t.rotate, closed: false };
    let strokes: geom::Lines = layout
        .glyphs
        .iter()
        .flat_map(|g| g.strokes.iter().map(move |s| (g.x, s)))
        .map(|(gx, s)| {
            let s = crate::grammar::Shape { points: s.iter().map(|&(x, y)| [(gx + x - cx) * k, (y - cy) * k]).collect(), ..shape.clone() };
            LineString::new(shape_points(&s, engine))
        })
        .collect();
    if layout.outline {
        let silhouette = crate::text::glyph_silhouette(&strokes);
        let area = if t.open_counters { silhouette.clone() } else { geom::fill_holes(&silhouette) };
        Ok((geom::rings(&silhouette), area))
    } else {
        let parts: Vec<MultiPolygon<f64>> = strokes.iter().map(|l| geom::buffer_line_round(l, t.size.0 * 0.08)).collect();
        Ok((strokes, geom::union_multi(&parts)))
    }
}

/// An atlas graticule's part, round the bounds of `within`: its lines (cut
/// to `within`), its degree labels (pen strokes and what they cover), or the
/// border's inked keys.
fn graticule_on_page(g: &crate::grammar::Graticule, within: &MultiPolygon<f64>, as_area: bool, engine: &Engine) -> Result<Value, String> {
    use crate::grammar::{GraticulePart, PagePos, ShapeAt, Text};
    use crate::graticule as gr;
    use geo::BoundingRect;
    let Some(r) = within.bounding_rect() else {
        return Ok(if as_area { Value::Area(MultiPolygon::new(vec![])) } else { Value::Lines(vec![]) });
    };
    let plate = gr::Plate { x0: r.min().x, y0: r.min().y, x1: r.max().x, y1: r.max().y };
    let p = &engine.projector;
    let look = &g.look;
    Ok(match look.part {
        GraticulePart::Grid => {
            let paths: geom::Lines = gr::lines(p, &plate, look.step).into_iter().map(|l| l.path).collect();
            Value::Lines(geom::clip_lines(&paths, within, false))
        }
        GraticulePart::Keys => Value::Area(gr::keys(p, &plate, look.ticks, look.band.0)),
        GraticulePart::Labels => {
            let mut strokes = geom::Lines::new();
            let mut cover: Vec<MultiPolygon<f64>> = Vec::new();
            for m in gr::marks(p, &plate, look.step, look.band.0 + look.gap.0, look.size.0) {
                let t = Text {
                    at: ShapeAt::Page([PagePos::Mm(crate::units::Mm(m.at.x)), PagePos::Mm(crate::units::Mm(m.at.y))]),
                    text: m.text,
                    size: look.size,
                    font: look.font.clone(),
                    rotate: m.rotate,
                    // Filled solid, the holes of 0, 8 and ° stay open.
                    open_counters: true,
                };
                let (lines, area) = text_on_page(&t, engine)?;
                // A label that would run into the one before it is left out.
                if cover.last().is_some_and(|prev| geo::Intersects::intersects(prev, &area)) {
                    continue;
                }
                strokes.extend(lines);
                cover.push(area);
            }
            if as_area { Value::Area(geom::union_multi(&cover)) } else { Value::Lines(strokes) }
        }
    })
}

/// The features' polygons (`areas.polygons`) that need not be merged on
/// their own, left as they come (each oriented), overlapping: those read only
/// as the base of a difference (`areas.difference`), which cuts them and
/// merges them in one pass (nonzero), and on a `screen` those only filled,
/// since a screen scans each polygon on its own (`drawland_grid::raster`).
/// The same area, the same dots, without a union of every building of a
/// dense city, or every wood of a region, done twice.
fn unmerged(grammar: &Grammar, screen: bool) -> BTreeSet<Name> {
    use crate::paint::Look;
    let mut read: BTreeSet<Name> = BTreeSet::new();
    for d in grammar.all_defs() {
        match &d.op {
            Op::Difference(diff) if !diff.cut.is_empty() => read.extend(diff.cut.iter().cloned()),
            op => read.extend(op.refs()),
        }
    }
    read.extend(grammar.draw.iter().map(|d| d.from.name.clone()));
    read.extend(grammar.compose.masks.iter().map(|(_, m)| m.from.name.clone()));
    for clip in grammar.compose.clip.values().chain([&grammar.compose.clip_default]) {
        if let crate::grammar::Clip::Areas(names) = clip {
            read.extend(names.iter().cloned());
        }
    }
    for p in &grammar.paint {
        if !screen || p.from.module.is_some() || !matches!(p.look.base(), Look::Fill(_)) {
            read.insert(p.from.name.clone());
        }
    }
    grammar.all_defs().filter(|d| matches!(d.op, Op::Polygons(_))).map(Def::reference).filter(|n| !read.contains(n)).collect()
}

/// Evaluate every non-fill def, in dependency order (waves); the polygons in
/// `unmerged` (see [`unmerged`]) are gathered, not merged.
fn evaluate(
    grammar: &Grammar,
    features: &Found,
    engine: &Engine,
    draw: &Task,
    unmerged: &BTreeSet<Name>,
) -> Result<BTreeMap<Name, Value>, RunError> {
    let eval = |name: &Name, op: &Op, done: &BTreeMap<Name, Value>| match op {
        Op::Polygons(of) if unmerged.contains(name) => {
            let feats = done.get(of).ok_or_else(|| format!("{of} is missing"))?.features(of).map_err(|e| e.to_string())?;
            Ok(Value::Area(geom::gathered(feats.iter().flat_map(|f| geom::polygons(&f.geometry)))))
        }
        Op::Difference(d) if unmerged.contains(&d.base) => {
            let area = |n: &Name| done.get(n).ok_or_else(|| format!("{n} is missing"))?.area(n).map_err(|e| e.to_string());
            let mut base = geom::difference_unmerged(area(&d.base)?, area(&d.cut[0])?);
            for cut in &d.cut[1..] {
                base = geom::difference(&base, area(cut)?);
            }
            Ok(Value::Area(base))
        }
        _ => eval_op(op, done, features, engine),
    };
    let mut done: BTreeMap<Name, Value> = BTreeMap::new();
    // Fills are made later, in their group, a batch at a time; only a fill
    // another def reads (a clearance buffered round a hatch) is made here too.
    let read: Vec<Name> = grammar.all_defs().flat_map(|d| d.op.refs()).collect();
    let mut pending: Vec<Name> = grammar
        .all_defs()
        .filter(|d| d.op.section() != Section::Fills || read.contains(&d.reference()))
        .map(|d| d.reference())
        .collect();
    let task = draw.child("evaluate", "evaluate", pending.len() as u64, "defs");

    while !pending.is_empty() {
        let ready: Vec<Name> = pending
            .iter()
            .filter(|n| {
                grammar
                    .find(n)
                    .map(|d| d.op.refs().iter().all(|r| done.contains_key(r)))
                    .unwrap_or(false)
            })
            .cloned()
            .collect();
        if ready.is_empty() {
            let stuck: Vec<String> = pending.iter().map(Name::to_string).collect();
            return Err(RunError::Plan(format!("defs depend on each other: {}", stuck.join(", "))));
        }
        // Deterministic order: the profile's own order, within a wave.
        // When a wave has multiple independent defs, evaluate them in parallel.
        if ready.len() == 1 {
            let name = ready.into_iter().next().unwrap();
            let def = grammar.find(&name).expect("ready names come from the grammar");
            task.step(done.len() as u64, &name.to_string());
            let value = eval(&name, &def.op, &done).map_err(|e| {
                task.log(Level::Error, &format!("{name}: {e}"));
                RunError::Plan(format!("{}: {e}", def.label()))
            })?;
            done.insert(name.clone(), value);
            pending.retain(|n| n != &name);
        } else {
            let base_done = done.len() as u64;
            task.step(base_done, &ready[0].to_string());
            let evaluated: Vec<(Name, Result<Value, (String, String)>)> = ready
                .par_iter()
                .map(|name| {
                    let def = grammar.find(name).expect("ready names come from the grammar");
                    let res = eval(name, &def.op, &done).map_err(|e| (e, def.label()));
                    (name.clone(), res)
                })
                .collect();
            for (name, res) in evaluated {
                match res {
                    Ok(value) => {
                        done.insert(name, value);
                    }
                    Err((e, label)) => {
                        task.log(Level::Error, &format!("{name}: {e}"));
                        return Err(RunError::Plan(format!("{label}: {e}")));
                    }
                }
            }
            pending.retain(|n| !done.contains_key(n));
        }
    }
    task.ok("");
    Ok(done)
}

fn label_placed<'a>(done: &'a BTreeMap<Name, Value>, of: &Name) -> Result<&'a crate::labels::Placed, String> {
    match done.get(of) {
        Some(Value::Labels(placed)) => Ok(placed),
        _ => Err(format!("{of} is not a labels def")),
    }
}

fn label_pick(done: &BTreeMap<Name, Value>, pick: &crate::grammar::LabelPick) -> Result<MultiPolygon<f64>, String> {
    let placed = label_placed(done, &pick.of)?;
    Ok(if pick.dots { placed.dots_for(pick.rule.as_deref()) } else { placed.area_for(pick.rule.as_deref()) })
}

fn label_lines(done: &BTreeMap<Name, Value>, pick: &crate::grammar::LabelPick) -> Result<Lines, String> {
    Ok(label_placed(done, &pick.of)?.lines_for(pick.rule.as_deref()))
}

fn eval_op<'a>(
    op: &Op,
    done: &'a BTreeMap<Name, Value>,
    features: &Found,
    engine: &Engine,
) -> Result<Value, String> {
    let area = |n: &Name| -> Result<&'a MultiPolygon<f64>, String> {
        done.get(n).ok_or_else(|| format!("{} is missing", n))?.area(n).map_err(|e| e.to_string())
    };
    let lines = |n: &Name| -> Result<&'a Lines, String> {
        done.get(n).ok_or_else(|| format!("{} is missing", n))?.lines(n).map_err(|e| e.to_string())
    };
    let feats = |n: &Name| -> Result<&'a [Feature], String> {
        done.get(n)
            .ok_or_else(|| format!("{} is missing", n))?
            .features(n)
            .map_err(|e| e.to_string())
    };

    Ok(match op {
        // ---- features ------------------------------------------------------
        Op::Select(sel) => Value::Features(select(sel, features.osm)),
        Op::TileSelect(t) => {
            let mut at: Vec<usize> = crate::tiles::layers_kept(&t.filter).filter_map(|l| features.by_layer.get(l)).flatten().copied().collect();
            at.sort_unstable();
            Value::Features(at.into_iter().map(|i| &features.tiles[i]).filter(|f| crate::tiles::keeps(&t.filter, f)).cloned().collect())
        }
        Op::DataSelect(source @ (crate::grammar::DataSource::Url(_) | crate::grammar::DataSource::Json(_))) => {
            Value::Features(features.data.get(&data_key(source)).cloned().unwrap_or_default())
        }
        Op::DataSelect(crate::grammar::DataSource::Inline(gj)) => {
            let found = crate::geojson::features_of(gj).map_err(|e| format!("inline GeoJSON: {e}"))?;
            Value::Features(found.into_iter().map(|mut f| {
                f.geometry = engine.warp_project(&f.geometry);
                f
            }).collect())
        }
        Op::TerrainSelect(t) => {
            let grid = engine.terrain.ok_or("the terrain's features need the elevation, which was not read")?;
            Value::Features(crate::contours::features(t, grid, &grid.placed(engine.projector), &engine.output))
        }
        Op::Where(w) => Value::Features(
            feats(&w.of)?.iter().filter(|f| crate::select::passes(&w.tags, f)).cloned().collect(),
        ),

        // ---- areas ---------------------------------------------------------
        Op::Polygons(n) => Value::Area(union_features(feats(n)?)),
        Op::Union(rules) => {
            let parts: Vec<&MultiPolygon<f64>> = refs_of(rules).iter().map(&area).collect::<Result<_, _>>()?;
            Value::Area(geom::union_multi(parts))
        }
        Op::Difference(d) => {
            let mut base = area(&d.base)?.clone();
            for cut in &d.cut {
                base = geom::difference(&base, area(cut)?);
            }
            Value::Area(base)
        }
        Op::Intersect(i) => {
            let base = area(&i.base)?;
            let keep = match &i.keep {
                Some(n) => area(n)?,
                None => return Err("tools_intersect needs a keep".into()),
            };
            Value::Area(geom::intersection(base, keep))
        }
        Op::FillHoles(n) => Value::Area(geom::fill_holes(area(n)?)),
        Op::FillCover(f) => {
            let spec = with_motif(f, |n| lines(n))?;
            Value::Area(crate::fill::cover(area(&f.in_area)?, &spec).map_err(|e| e.to_string())?)
        }
        Op::LabelArea(p) => Value::Area(label_pick(done, p)?),
        Op::LabelLines(p) => Value::Lines(label_lines(done, p)?),
        Op::Grow(g) => Value::Area(geom::buffer(area(&g.of)?, g.by.0)),
        Op::Move(m) => Value::Area(geo::Translate::translate(area(&m.of)?, m.by[0].0, m.by[1].0)),
        Op::Around(a) => {
            let discs: Vec<MultiPolygon<f64>> = feats(&a.of)?
                .iter()
                .flat_map(|f| geom::points_of(&f.geometry))
                .map(|c| geom::disc(c, a.by.0))
                .collect();
            Value::Area(geom::union_multi(&discs))
        }
        Op::Shape(s) => {
            let ring = LineString::new(shape_points(s, engine));
            Value::Area(geom::union_multi(&[MultiPolygon::new(vec![Polygon::new(ring, vec![])])]))
        }
        Op::TextArea(t) => Value::Area(text_on_page(t, engine)?.1),
        Op::GraticuleArea(g) => graticule_on_page(g, area(&g.in_area)?, true, engine)?,
        Op::BufferLines(b) => {
            let ls = lines(&b.lines)?;
            let radius = b.by.0;
            let parts: Vec<MultiPolygon<f64>> = ls
                .par_iter()
                .map(|l| match b.cap {
                    LineBufferCap::Round => geom::buffer_line_round(l, radius),
                    LineBufferCap::Flat => geom::buffer_line_flat(l, radius),
                })
                .collect();
            Value::Area(geom::union_multi(&parts))
        }
        Op::Frame => Value::Area(engine.output.clone()),
        Op::ExtendToFrame(e) => {
            let of = area(&e.of)?;
            let within = area(&e.within)?;
            let reach = e.gap_mm.map(|m| m.0).unwrap_or(1.0);
            Value::Area(geom::extend_to_frame_edges(of, within, reach))
        }

        // ---- lines ---------------------------------------------------------
        Op::Path(s) => {
            let mut pts = shape_points(s, engine);
            if s.closed {
                pts.push(pts[0]);
            }
            Value::Lines(vec![LineString::new(pts)])
        }
        Op::Text(t) => Value::Lines(text_on_page(t, engine)?.0),
        Op::Graticule(g) => graticule_on_page(g, area(&g.in_area)?, false, engine)?,
        Op::Rings(r) => {
            let a = area(&r.of)?;
            Value::Lines(if r.exterior_only { geom::exterior_rings(a) } else { geom::rings(a) })
        }
        Op::Lines(n) => {
            let f = feats(n)?;
            Value::Lines(f.iter().filter(|f| geom::polygons(&f.geometry).is_empty()).flat_map(|f| geom::lines_of(&f.geometry)).collect())
        }
        Op::Segments(n) => {
            // Every edge of every polygon, plus the linear features.
            let f = feats(n)?;
            Value::Lines(f.iter().flat_map(|f| geom::lines_of(&f.geometry)).collect())
        }
        Op::Dedupe(n) => Value::Lines(geom::dedupe_segments(lines(n)?)),
        Op::Merge(n) => Value::Lines(geom::linemerge(lines(n)?)),
        Op::Join(rules) => {
            let parts: Vec<&Lines> = refs_of(rules).iter().map(&lines).collect::<Result<_, _>>()?;
            Value::Lines(parts.into_iter().flat_map(|p| p.iter().cloned()).collect())
        }
        Op::ClipLines(c) => {
            let within = area(&c.within)?;
            Value::Lines(geom::clip_lines(lines(&c.lines)?, within, c.invert))
        }

        // Handled in the fill pass, so `values` never holds one.
        Op::Terrain(t) => {
            let grid = engine.terrain.ok_or("tools_terrain needs the elevation, which was not read")?;
            let drawing = crate::terrain::draw(grid, t)?;
            let drawn = crate::terrain::lines(&drawing, &grid.placed(engine.projector));
            // The elevation is read a margin past the frame so the ink reaches
            // the border (see `terrain::bounds_of`); clip it back to the page,
            // or to `in_area` when the profile asks for one.
            Value::Lines(match &t.in_area {
                Some(n) => geom::clip_lines(&drawn, area(n)?, false),
                None => geom::clip_lines(&drawn, &engine.output, false),
            })
        }
        Op::TerrainBand(t) => {
            let grid = engine.terrain.ok_or("areas.band needs the elevation, which was not read")?;
            // Cut the band from the heights smoothed once, by `blur` (px), here:
            // burin is told not to blur again, so a band's edge is exactly the
            // contour `features.contours` traces at that height with the same blur.
            let blur = t.style.get("input_blur").and_then(|v| v.as_f64()).unwrap_or(0.0);
            let smooth = engine.smoothed(grid, blur);
            let smooth = smooth.get().expect("made by Engine::smoothed");
            let mut once = t.clone();
            once.style.insert("input_blur".into(), serde_json::json!(0));
            let drawing = crate::terrain::draw(smooth, &once)?;
            let band = crate::terrain::fill_area(&drawing, &grid.placed(engine.projector));
            let keep = match &t.in_area {
                Some(n) => area(n)?.clone(),
                None => engine.output.clone(),
            };
            Value::Area(geo::BooleanOps::intersection(&band, &keep))
        }
        Op::Burin(b) => {
            use burin_map_core::Region;
            let grid = engine.terrain.ok_or("tools_burin needs the elevation, which was not read")?;
            let placed = grid.placed(engine.projector);
            let regions: Vec<(&str, Region)> = b
                .regions
                .iter()
                .map(|(name, a)| Ok((name.as_str(), crate::terrain::region_from_area(area(a)?, &placed))))
                .collect::<Result<_, String>>()?;
            let water = match &b.water {
                Some(n) => Some(crate::terrain::coverage_of(area(n)?, grid, &placed)),
                None => None,
            };
            let drawing = crate::terrain::draw_burin(grid, b, &regions, water.as_deref())?;
            let drawn = crate::terrain::lines(&drawing, &placed);
            Value::Lines(match &b.in_area {
                Some(n) => geom::clip_lines(&drawn, area(n)?, false),
                None => geom::clip_lines(&drawn, &engine.output, false),
            })
        }
        Op::Labels(l) => {
            let mut named = Vec::new();
            for n in &l.from {
                named.extend_from_slice(feats(n)?);
            }
            let bounds = match &l.in_area {
                Some(n) => geom::intersection(area(n)?, &engine.drawable),
                None => engine.drawable.clone(),
            };
            let avoid = l.avoid.as_ref().map(|n| area(n)).transpose()?;
            Value::Labels(crate::labels::place_avoiding(&named, &bounds, avoid, &l.style, engine.google_fonts, engine.stroke_fonts)?)
        }
        // A fill another def reads, made whole (see `evaluate`).
        Op::Fill(f) => {
            let region = area(&f.in_area)?;
            let spec = with_motif(f, |n| lines(n))?;
            let made = if let Some(content) = &f.content {
                Ok(fill::fill_with(region, lines(content)?))
            } else if f.per_feature {
                region
                    .0
                    .par_iter()
                    .map(|p| fill::fill_polygon(p, &spec, engine.sources))
                    .collect::<Result<Vec<Lines>, _>>()
                    .map(|v| v.into_iter().flatten().collect())
            } else {
                fill::fill(region, &spec, engine.sources)
            };
            Value::Lines(made.map_err(|e| e.to_string())?)
        }
        Op::Module(m) => match &m.from {
            Some(from) => eval_module(m, feats(from)?, engine.of)?,
            None => eval_module(m, features.osm, engine.of)?,
        },
    })
}

/// The four sections of the toolkit, as values.
fn eval_module(module: &crate::grammar::Module, features: &[Feature], output: &Output) -> Result<Value, String> {
    match module.name.as_str() {
        "roads" => {
            let roads = crate::themes::roads_render(&crate::themes::Context { output, features }, &module.roads);
            let parts = roads.parts;
            Ok(Value::Module {
                area: parts.mask,
                outlines: parts.outlines,
                details: parts.details,
                trails: parts.trails,
                centerlines: roads.centerlines,
                seams: roads.seams,
                rails: roads.rails,
            })
        }
        other => Err(format!("module_{other} is not known")),
    }
}


/// A module output as draw lines (`outlines` / `details`), or as an area
/// (`area`), which is recorded as a mask instead: modules mask, they do not
/// stroke.
fn module_lines<'a>(
    module: &str,
    name: &str,
    value: &'a Value,
    group: &str,
    masks_by_id: &mut BTreeMap<String, MultiPolygon<f64>>,
) -> Result<Option<&'a Lines>, RunError> {
    let Value::Module { area, outlines, details, trails, centerlines, seams, rails } = value else {
        return Err(RunError::Plan(format!("module_{module} did not produce module outputs")));
    };
    Ok(match name {
        "area" => {
            masks_by_id.insert(group.to_string(), area.clone());
            None
        }
        "outlines" => Some(outlines),
        "details" => Some(details),
        "trails" => Some(trails),
        "centerlines" => Some(centerlines),
        "seams" => Some(seams),
        "rails" => Some(rails),
        other => {
            return Err(RunError::Plan(format!(
                "module {module}: unknown output {other:?} (area, outlines, details, trails, centerlines, seams, rails)"
            )))
        }
    })
}

/// The value of one module output (`roads` → `area` / `outlines` / `details`),
/// looked up through the def that calls the module.
fn module_output<'a>(
    module: &str,
    name: &str,
    values: &'a BTreeMap<Name, Value>,
    grammar: &Grammar,
) -> Result<&'a Value, RunError> {
    let def = grammar
        .module(module)
        .ok_or_else(|| RunError::Plan(format!("nothing calls module_{module}")))?;
    let _ = name;
    values
        .get(&def.reference())
        .ok_or_else(|| RunError::Plan(format!("module_{module} was not evaluated")))
}

/// Paper area of a region, square millimetres, for the fill cost estimate.
fn area_area(mp: &MultiPolygon<f64>) -> f64 {
    use geo::Area;
    mp.unsigned_area()
}

fn refs_of(rules: &UnionRules) -> Vec<Name> {    match rules {
        UnionRules::Refs(ns) => ns.clone(),
        UnionRules::Ref(n) => vec![n.clone()],
    }
}

/// The polygon parts of a feature set, unioned.
fn union_features(features: &[Feature]) -> MultiPolygon<f64> {
    let polys: Vec<geo::Polygon<f64>> = features.iter().flat_map(|f| geom::polygons(&f.geometry)).collect();
    geom::union_all(&polys)
}

fn select(sel: &Selector, features: &[Feature]) -> Vec<Feature> {
    features.iter().filter(|f| sel.keeps(f)).cloned().collect()
}

/// `grammar` with every fill that asks for the ground (`anchor: "ground"`)
/// anchored at its point under `output` ([`fill::grounded`]); `None` when
/// none asks.
fn grounded(grammar: &Grammar, output: &Output) -> Option<Grammar> {
    let asks = |op: &Op| matches!(op, Op::Fill(f) | Op::FillCover(f) if fill::grounded(&f.spec, output).is_some());
    if !grammar.sections.iter().flat_map(|(_, defs)| defs).any(|d| asks(&d.op)) {
        return None;
    }
    let mut g = grammar.clone();
    for def in g.sections.iter_mut().flat_map(|(_, defs)| defs) {
        if let Op::Fill(f) | Op::FillCover(f) = &mut def.op {
            if let Some(spec) = fill::grounded(&f.spec, output) {
                f.spec = spec;
            }
        }
    }
    Some(g)
}

/// `f`'s spec with its `motif` reference, if any, resolved into polylines
/// around the origin.
fn with_motif<'a>(
    f: &crate::grammar::Fill,
    lines: impl Fn(&Name) -> Result<&'a Lines, String>,
) -> Result<crate::profile::FillSpec, String> {
    let mut spec = f.spec.clone();
    if let Some(m) = &f.motif {
        spec.options.insert("motif".into(), fill::motif_polylines(lines(m)?));
    }
    Ok(spec)
}

/// What the fills need to be made in their group: the evaluated defs, the
/// SVG sources, the host's memory ceiling, and the task their rows go under.
struct Fills<'a> {
    values: &'a BTreeMap<Name, Value>,
    sources: &'a Sources,
    budget: Option<u64>,
    task: &'a Task<'a>,
}

/// How many buildings `per: feature` fills at once, in parallel: enough to
/// keep the cores busy, few enough that their strokes stay small.
const PIECES_AT_ONCE: usize = 256;

/// Make the fill `def` into `sink`: one pass, or one per feature for
/// `per: feature`.
fn run_fill(def: &Def, spec: &crate::grammar::Fill, fills: &Fills, sink: &mut GroupSink) -> Result<(), RunError> {
    let name = def.reference();
    let resolved;
    let spec = if spec.motif.is_some() {
        let s = with_motif(spec, |n| fills.values.get(n).ok_or_else(|| format!("missing motif {n}"))?.lines(n).map_err(|e| e.to_string()))
            .map_err(RunError::Plan)?;
        resolved = crate::grammar::Fill { spec: s, motif: None, ..spec.clone() };
        &resolved
    } else {
        spec
    };
    let task = fills.task.child(&format!("fill:{name}"), &name.to_string(), 0, "pieces");
    let area = fills
        .values
        .get(&spec.in_area)
        .ok_or_else(|| RunError::Plan(format!("{name}: missing input {}", spec.in_area)))?
        .area(&spec.in_area)?;
    let failed = |source| RunError::Def { def: def.label(), source };
    let start = sink.fed;
    let check_budget = |generator: &str| -> Result<(), String> {
        if let Some(budget) = fills.budget {
            let spacing = fill::spacing_mm(&spec.spec).unwrap_or(0.5);
            // A fill drawn in tiles holds one tile's strokes (and the seams
            // of a row) at a time, whatever its area.
            let held = if fill::streams(&spec.spec) { area_area(area).min(2.0 * fill::TILE_MM * fill::TILE_MM) } else { area_area(area) };
            let estimate = crate::budget::cost(held, &spec.spec);
            if estimate.bytes > budget {
                return Err(format!(
                    "{name}: this fill needs {}, more than the {} the page has. It covers {} mm² of paper \
                     with {generator} at {spacing} mm. Widen the spacing, use a sparser pattern, shrink the \
                     output, or draw it with the command line.",
                    crate::progress::human_bytes(estimate.bytes),
                    crate::progress::human_bytes(budget),
                    thousands(estimate.area_mm2 as u64),
                ));
            }
        }
        Ok(())
    };
    if let Some(content) = &spec.content {
        let lines = fills
            .values
            .get(content)
            .ok_or_else(|| RunError::Plan(format!("{name}: missing content {content}")))?
            .lines(content)?;
        task.set_total(1);
        for l in fill::fill_with(area, lines) {
            sink.line(l);
        }
    } else if spec.per_feature {
        let generator = spec.spec.generator.clone().unwrap_or_else(|| "dots".into());
        if let Err(detail) = check_budget(&generator) {
            task.fail(&detail);
            return Err(RunError::TooLarge(detail));
        }
        // One penfill run per polygon of the input area, so neighbouring
        // buildings keep their own hatching instead of merging.
        task.set_total(area.0.len() as u64);
        for chunk in area.0.chunks(PIECES_AT_ONCE) {
            let filled: Result<Vec<Lines>, FillError> = chunk
                .par_iter()
                .map(|p| {
                    let lines = fill::fill_polygon(p, &spec.spec, fills.sources);
                    task.tick();
                    lines
                })
                .collect();
            for l in filled.map_err(failed)?.into_iter().flatten() {
                sink.line(l);
            }
        }
    } else {
        // A generator that cannot stream holds its whole fill at once:
        // inside a page, one that would not fit is refused before it starts,
        // since the WASM allocator traps rather than failing. From the
        // command line `budget` is `None` and this is skipped.
        let generator = spec.spec.generator.clone().unwrap_or_else(|| "dots".into());
        if let Err(detail) = check_budget(&generator) {
            task.fail(&detail);
            return Err(RunError::TooLarge(detail));
        }
        task.set_total(1);
        fill::fill_into(area, &spec.spec, fills.sources, sink).map_err(failed)?;
    }
    sink.flush();
    task.tick();
    task.ok(&format!("{} lines", thousands((sink.fed - start) as u64)));
    fills.task.tick();
    Ok(())
}

/// Flat fill: paint the area (minus masks), no pen strokes.
fn run_solid_fill(
    def: &Def,
    spec: &crate::grammar::Fill,
    fills: &Fills,
    mask: &MultiPolygon<f64>,
    layout: &mut crate::sheets::Layout,
    out: &mut crate::sheets::Out<'_>,
    under_hatch: bool,
) -> Result<(), RunError> {
    if spec.content.is_some() {
        return Err(RunError::Plan(format!("{}: solid fill cannot use content", def.reference())));
    }
    let name = def.reference();
    let task_id = if under_hatch {
        format!("fill:{name}:under")
    } else {
        format!("fill:{name}")
    };
    let task = fills.task.child(&task_id, &name.to_string(), 0, "pieces");
    let area = fills
        .values
        .get(&spec.in_area)
        .ok_or_else(|| RunError::Plan(format!("{name}: missing input {}", spec.in_area)))?
        .area(&spec.in_area)?;
    let mut paint = |painted: &MultiPolygon<f64>| {
        if under_hatch {
            let bg = crate::profile::StrokeSpec {
                color: spec.spec.background.clone(),
                ..Default::default()
            };
            layout.fill_under(&crate::svg::fill_color(Some(&bg)), painted, out);
        } else {
            layout.solids(painted, out);
        }
    };
    if spec.per_feature {
        task.set_total(area.0.len() as u64);
        for p in &area.0 {
            let piece = MultiPolygon::new(vec![p.clone()]);
            let painted = fill::solid_regions(&piece, mask);
            paint(&painted);
            task.tick();
        }
    } else {
        task.set_total(1);
        let painted = fill::solid_regions(area, mask);
        paint(&painted);
        task.tick();
    }
    task.ok("solid");
    if !under_hatch {
        fills.task.tick();
    }
    Ok(())
}

enum SinkDest<'a, 'o> {
    Stream(&'a mut crate::sheets::Layout, &'a mut crate::sheets::Out<'o>),
    Collect(&'a crate::sheets::Layout, &'a mut Lines),
}

/// One group on its way to the paper: strokes come in, are styled, gathered
/// into a batch, cut by the masks over the group, and written (or collected
/// when `compose.optimize` is active). Only the batch is ever held when
/// streaming.
struct GroupSink<'a, 'o> {
    stroke: Option<&'a crate::profile::StrokeSpec>,
    /// What the masks over this group cover; empty when none does.
    mask: &'a MultiPolygon<f64>,
    pending: Lines,
    points: usize,
    /// Strokes taken in, before styling and masking: for the progress row.
    fed: usize,
    dest: SinkDest<'a, 'o>,
}

impl GroupSink<'_, '_> {
    fn line(&mut self, line: geo::LineString<f64>) {
        self.fed += 1;
        match self.stroke {
            None => self.push(line),
            Some(s) => {
                for l in fill::stroke(vec![line], s) {
                    self.push(l);
                }
            }
        }
    }

    fn push(&mut self, line: geo::LineString<f64>) {
        self.points += line.0.len();
        self.pending.push(line);
        if self.points >= geom::BATCH_POINTS {
            self.flush();
        }
    }

    fn flush(&mut self) {
        if self.pending.is_empty() {
            return;
        }
        let batch = std::mem::take(&mut self.pending);
        self.points = 0;
        let kept = if self.mask.0.is_empty() { batch } else { geom::clip_lines(&batch, self.mask, true) };
        match &mut self.dest {
            SinkDest::Stream(layout, out) => layout.lines(&kept, out),
            SinkDest::Collect(layout, acc) => acc.extend(layout.crop(&kept)),
        }
    }
}

impl penfill::Sink for GroupSink<'_, '_> {
    fn stroke(&mut self, pts: Vec<(f64, f64)>) {
        if pts.len() >= 2 {
            self.line(geo::LineString::new(pts.into_iter().map(|(x, y)| geo::Coord { x, y }).collect()));
        }
    }
}

/// What a draw entry draws: lines already made, a fill still to make, or
/// nothing (a module's `area`, which masks instead).
enum Drawing<'a> {
    Lines(&'a Lines),
    Fill(&'a Def, &'a crate::grammar::Fill),
    Nothing,
}

/// Write `draw` + `compose` onto `layout`, group by group in order, each
/// made as it is written.
fn compose(
    grammar: &Grammar,
    values: &BTreeMap<Name, Value>,
    fills: &Fills,
    beyond: &MultiPolygon<f64>,
    task: &Task,
    layout: &mut crate::sheets::Layout,
    out: &mut crate::sheets::Out,
    mut collect: Option<&mut Collected>,
) -> Result<(), RunError> {
    // 1. What each draw entry draws, and with what stroke.
    let mut drawn: BTreeMap<String, (Drawing, Option<&crate::profile::StrokeSpec>)> = BTreeMap::new();
    let mut masks_by_id: BTreeMap<String, MultiPolygon<f64>> = BTreeMap::new();

    let strokes_task = task.child("compose:strokes", "strokes", grammar.draw.len() as u64, "draws");
    for draw in &grammar.draw {
        let what = match &draw.from.module {
            Some(module) => {
                let value = module_output(module, &draw.from.name.name, values, grammar)?;
                module_lines(module, &draw.from.name.name, value, &draw.group(), &mut masks_by_id)?
                    .map_or(Drawing::Nothing, Drawing::Lines)
            }
            None => match draw.from.name.section {
                Section::Lines => match values.get(&draw.from.name) {
                    Some(v) => Drawing::Lines(v.lines(&draw.from.name)?),
                    None => Drawing::Nothing,
                },
                Section::Fills => match grammar.find(&draw.from.name) {
                    Some(def @ Def { op: Op::Fill(spec), .. }) => Drawing::Fill(def, spec),
                    _ => Drawing::Nothing,
                },
                other => {
                    return Err(RunError::Plan(format!(
                        "draw from ${other}.{}: need $lines or $fills",
                        draw.from.name.name
                    )))
                }
            },
        };
        drawn.insert(draw.group(), (what, draw.stroke.as_ref()));
        strokes_task.tick();
    }
    strokes_task.ok("");

    // 2. Evaluate the masks: an area per mask name.
    let masks_task = task.child("compose:masks", "masks", grammar.compose.masks.len() as u64, "masks");
    for (name, mask) in &grammar.compose.masks {
        let area = mask_area(mask, values, grammar)
            .map_err(|e| RunError::Plan(format!("masks.{name}: {e}")))?;
        masks_by_id.insert(name.clone(), area);
        masks_task.tick();
    }
    masks_task.ok("");

    // 3. Order: bottom-most first. Without `order`, the draw order.
    let order: Vec<String> = if grammar.compose.order.is_empty() {
        grammar.groups()
    } else {
        let mut ids: Vec<String> = grammar.compose.order.iter().map(|i| i.0.clone()).collect();
        // Draw entries the order leaves out go on top, in listed order.
        for id in grammar.groups() {
            if !ids.contains(&id) {
                ids.push(id);
            }
        }
        ids
    };

    // 4. Each group made, masked and written (or collected for optimize). A mask
    // cuts exactly the groups it lists, wherever they sit in the order: the
    // order is only the sequence the groups are drawn in.
    // Groups mostly share their masks, and a union over the whole card is
    // the slow part of a group: one union per set of masks.
    let mut unions: BTreeMap<Vec<&str>, MultiPolygon<f64>> = BTreeMap::new();
    let occlude_task = task.child("compose:occlude", "occlusion", order.len() as u64, "groups");

    enum BufferedGroup<'a> {
        SolidFill {
            id: String,
            stroke: Option<&'a crate::profile::StrokeSpec>,
            def: &'a Def,
            spec: &'a crate::grammar::Fill,
            above: MultiPolygon<f64>,
        },
        Strokes {
            id: String,
            stroke: Option<&'a crate::profile::StrokeSpec>,
            under_hatch: Option<(&'a Def, &'a crate::grammar::Fill, MultiPolygon<f64>)>,
        },
    }

    // Collecting (a view) goes the buffered way too: every group's strokes
    // held, then handed back rather than written.
    let has_optimize = !grammar.compose.optimize.is_empty() || collect.is_some();
    let mut buffered_meta: Vec<BufferedGroup> = Vec::new();
    let mut buffered_lines: Vec<(String, Lines)> = Vec::new();

    for id in &order {
        occlude_task.tick();
        let Some((what, stroke)) = drawn.remove(id) else { continue };
        let above = match clip_for(grammar, id) {
            Clip::None => geom::empty(),
            Clip::Auto => {
                let names: Vec<&str> = grammar
                    .compose
                    .masks
                    .iter()
                    .filter(|(name, mask)| mask.occludes.iter().any(|o| &o.0 == id) && masks_by_id.contains_key(name.as_str()))
                    .map(|(name, _)| name.as_str())
                    .collect();
                unions
                    .entry(names)
                    .or_insert_with_key(|names| geom::union_multi(names.iter().map(|n| &masks_by_id[*n])))
                    .clone()
            }
            Clip::Areas(names) => {
                let parts: Vec<MultiPolygon<f64>> = names
                    .iter()
                    .filter_map(|n| values.get(n))
                    .filter_map(|v| match v {
                        Value::Area(a) => Some(a.clone()),
                        _ => None,
                    })
                    .collect();
                geom::union_multi(&parts)
            }
        };
        let above = if beyond.0.is_empty() { above } else { geom::union_multi([&above, beyond]) };
        if !has_optimize {
            match what {
                Drawing::Fill(def, spec) if fill::is_solid(&spec.spec) => {
                    layout.begin_fill(id, stroke);
                    run_solid_fill(def, spec, fills, &above, layout, out, false)?;
                    layout.end();
                }
                Drawing::Fill(def, spec) if spec.spec.background.is_some() => {
                    layout.begin_with_style(id, stroke);
                    run_solid_fill(def, spec, fills, &above, layout, out, true)?;
                    let mut sink = GroupSink { stroke, mask: &above, pending: Vec::new(), points: 0, fed: 0, dest: SinkDest::Stream(layout, out) };
                    run_fill(def, spec, fills, &mut sink)?;
                    sink.flush();
                    layout.end();
                }
                other => {
                    layout.begin_with_style(id, stroke);
                    let mut sink = GroupSink { stroke, mask: &above, pending: Vec::new(), points: 0, fed: 0, dest: SinkDest::Stream(layout, out) };
                    match other {
                        Drawing::Lines(lines) => {
                            for l in lines {
                                sink.line(l.clone());
                            }
                        }
                        Drawing::Fill(def, spec) => run_fill(def, spec, fills, &mut sink)?,
                        Drawing::Nothing => {}
                    }
                    sink.flush();
                    layout.end();
                }
            }
        } else {
            match what {
                Drawing::Fill(def, spec) if fill::is_solid(&spec.spec) => {
                    buffered_meta.push(BufferedGroup::SolidFill {
                        id: id.clone(),
                        stroke,
                        def,
                        spec,
                        above,
                    });
                }
                other => {
                    let under_hatch = match &other {
                        Drawing::Fill(def, spec) if spec.spec.background.is_some() => Some((*def, *spec, above.clone())),
                        _ => None,
                    };
                    let mut acc = Lines::new();
                    {
                        let mut sink = GroupSink {
                            stroke,
                            mask: &above,
                            pending: Vec::new(),
                            points: 0,
                            fed: 0,
                            dest: SinkDest::Collect(layout, &mut acc),
                        };
                        match other {
                            Drawing::Lines(lines) => {
                                for l in lines {
                                    sink.line(l.clone());
                                }
                            }
                            Drawing::Fill(def, spec) => run_fill(def, spec, fills, &mut sink)?,
                            Drawing::Nothing => {}
                        }
                        sink.flush();
                    }
                    buffered_lines.push((id.clone(), acc));
                    buffered_meta.push(BufferedGroup::Strokes {
                        id: id.clone(),
                        stroke,
                        under_hatch,
                    });
                }
            }
        }
        if probing() {
            occlude_task.log(Level::Info, &format!("mem group {id}: {}", crate::progress::human_bytes(crate::progress::resident_bytes())));
        }
    }
    occlude_task.ok("");

    if has_optimize {
        crate::optimize::run_pipeline(&grammar.compose.optimize, &order, &mut buffered_lines, task);
        let mut by_id: BTreeMap<String, Lines> = buffered_lines.into_iter().collect();
        if let Some(collect) = collect.as_deref_mut() {
            for item in buffered_meta {
                match item {
                    BufferedGroup::SolidFill { id, .. } => {
                        task.log(Level::Warn, &format!("{id}: flat colour fills are not drawn inside a view"));
                    }
                    BufferedGroup::Strokes { id, stroke, under_hatch } => {
                        if under_hatch.is_some() {
                            task.log(Level::Warn, &format!("{id}: a fill's background is not drawn inside a view"));
                        }
                        let lines = by_id.remove(&id).unwrap_or_default();
                        collect.push((id, stroke.cloned(), lines));
                    }
                }
            }
            return Ok(());
        }
        for item in buffered_meta {
            match item {
                BufferedGroup::SolidFill { id, stroke, def, spec, above } => {
                    layout.begin_fill(&id, stroke);
                    run_solid_fill(def, spec, fills, &above, layout, out, false)?;
                    layout.end();
                }
                BufferedGroup::Strokes { id, stroke, under_hatch } => {
                    layout.begin_with_style(&id, stroke);
                    if let Some((def, spec, above)) = under_hatch {
                        run_solid_fill(def, spec, fills, &above, layout, out, true)?;
                    }
                    if let Some(lines) = by_id.remove(&id) {
                        layout.lines(&lines, out);
                    }
                    layout.end();
                }
            }
        }
    }
    Ok(())
}


/// Every view of `grammar`, each made from its own inputs, moved to its
/// rectangle, cut by the page masks that name it, and written under the
/// page's groups. Groups with the same id in several views are one group:
/// the same pen.
fn draw_views(
    grammar: &Grammar,
    values: &BTreeMap<Name, Value>,
    inputs: Vec<Inputs>,
    draw: &Task,
    layout: &mut crate::sheets::Layout,
    out: &mut crate::sheets::Out,
) -> Result<(), RunError> {
    if grammar.views.is_empty() {
        return Ok(());
    }
    if inputs.is_empty() {
        return Err(RunError::Plan("this page has views, but the host gave no inputs for them (each view is downloaded on its own)".into()));
    }
    if inputs.len() != grammar.views.len() {
        return Err(RunError::Plan(format!("{} views but inputs for {}", grammar.views.len(), inputs.len())));
    }
    let mut merged: Collected = Vec::new();
    for (view, input) in grammar.views.iter().zip(inputs) {
        let task = draw.child(&format!("view:{}", view.id), &format!("view {}", view.id), 0, "");
        let output = Output::new(&view.grammar.output, view.center());
        let mut got = Collected::new();
        run_graph(&view.grammar, &output, input, &task, &mut |_, _| {}, Want::Collect(&mut got))
            .map_err(|e| RunError::Plan(format!("view {}: {e}", view.id)))?;
        let over: Vec<MultiPolygon<f64>> = grammar
            .compose
            .masks
            .iter()
            .filter(|(_, m)| m.occludes.iter().any(|o| o.0 == view.id))
            .map(|(name, m)| mask_area(m, values, grammar).map_err(|e| RunError::Plan(format!("masks.{name}: {e}"))))
            .collect::<Result<_, _>>()?;
        let mask = geom::union_multi(&over);
        let (dx, dy) = view.at;
        let mut strokes = 0usize;
        for (id, stroke, lines) in got {
            // An inked view is a pen of its own: all its strokes one group,
            // named after the view, in its colour (already styled and cut).
            let (id, stroke) = match &view.ink {
                Some(ink) => {
                    let mut s = stroke.unwrap_or_default();
                    s.color = Some(ink.clone());
                    s.style = None;
                    s.dash = None;
                    s.gap = None;
                    s.mark = None;
                    (view.id.clone(), Some(s))
                }
                None => (id, stroke),
            };
            let moved: Lines = lines
                .into_iter()
                .map(|l| LineString::new(l.0.into_iter().map(|c| Coord { x: c.x + dx, y: c.y + dy }).collect()))
                .collect();
            let kept = if mask.0.is_empty() { moved } else { geom::clip_lines(&moved, &mask, true) };
            strokes += kept.len();
            match merged.iter_mut().find(|(m, _, _)| *m == id) {
                Some((_, _, acc)) => acc.extend(kept),
                None => merged.push((id, stroke, kept)),
            }
        }
        task.ok(&format!("{} strokes", thousands(strokes as u64)));
    }
    for (id, stroke, lines) in &merged {
        layout.begin_with_style(id, stroke.as_ref());
        layout.lines(lines, out);
        layout.end();
    }
    Ok(())
}

/// The area a mask subtracts: `$areas.*` or a module output.
fn mask_area(mask: &Mask, values: &BTreeMap<Name, Value>, grammar: &Grammar) -> Result<MultiPolygon<f64>, String> {
    if let Some(module) = &mask.from.module {
        let value = module_output(module, &mask.from.name.name, values, grammar)
            .map_err(|e| e.to_string())?;
        return match value {
            Value::Module { area, .. } => Ok(area.clone()),
            Value::Area(a) => Ok(a.clone()),
            _ => Err(format!("module {module}.{} is not an area", mask.from.name.name)),
        };
    }
    let name = &mask.from.name;
    values.get(name).ok_or_else(|| format!("{name} is missing"))?.area(name).cloned().map_err(|e| e.to_string())
}

fn clip_for(grammar: &Grammar, id: &str) -> Clip {
    grammar
        .compose
        .clip
        .get(&crate::grammar::Id(id.to_string()))
        .cloned()
        .unwrap_or_else(|| grammar.compose.clip_default.clone())
}


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

    /// A layer of place names in a hierarchy: a city large, a suburb
    /// smaller and only near, a hamlet never; by Mapbox expressions.
    #[test]
    fn a_layer_of_names_resolves_by_zoom_and_class() {
        use crate::expr::Frame;
        use crate::labels::{Named, Shape};
        use crate::paint::{Look, Shown, Style};
        let style = Style::new(
            "text",
            serde_json::json!({
                "font": ["match", ["get", "class"], "city", ["step", ["zoom"], "spleen-8x16", 12, "spleen-12x24"], "spleen-5x8"],
                "upper": ["==", ["get", "class"], "city"],
            }),
        )
        .unwrap();
        let shown = Shown::new(Some(4.0), None, Some(serde_json::json!(["any", ["==", ["get", "class"], "city"], ["all", ["==", ["get", "class"], "suburb"], [">=", ["zoom"], 12]]]))).unwrap();
        let tags: Vec<crate::osm::Tags> = ["city", "suburb", "hamlet"].iter().map(|c| [("class".to_string(), c.to_string())].into_iter().collect()).collect();
        let named = |text: &str, feature: usize| Named { text: text.into(), rank: 1.0, extent: 1.0, shape: Shape::Pin((0.0, 0.0).into()), feature };
        let layer = Layer {
            id: "places".into(),
            style,
            shown,
            halo: Default::default(),
            shape: PaintShape::Names(vec![named("Roma", 0), named("Monti", 1), named("Borgo", 2)]),
            tags: std::sync::Arc::new(tags),
        };
        let fonts = |zoom: f64| -> Vec<(String, Vec<String>)> {
            resolve(vec![layer.clone()], Frame::at_zoom(zoom))
                .into_iter()
                .map(|p| match (p.look, p.shape) {
                    (Look::Text(t), PaintShape::Names(ns)) => (t.font, ns.into_iter().map(|n| n.text).collect()),
                    _ => unreachable!(),
                })
                .collect()
        };
        assert!(fonts(3.0).is_empty(), "below minzoom");
        assert_eq!(fonts(8.0), vec![("spleen-8x16".to_string(), vec!["ROMA".to_string()])]);
        // Near, the suburb comes in, smaller: two layers in the one's place,
        // the larger letters over (last).
        assert_eq!(
            fonts(13.0),
            vec![("spleen-5x8".to_string(), vec!["Monti".to_string()]), ("spleen-12x24".to_string(), vec!["ROMA".to_string()])]
        );
    }

    #[test]
    fn a_style_is_checked_as_written() {
        use crate::paint::Style;
        let err = Style::new("text", serde_json::json!({ "font": ["step", ["zoom"], "spleen-5x8", 10, "spleen-99"] })).unwrap_err();
        assert!(err.contains("spleen-99"), "{err}");
        assert!(Style::new("text", serde_json::json!({ "keys": ["get", "name"] })).unwrap_err().contains("read once"));
        // A number from a ramp is rounded where pixels are counted.
        let line = Style::new("line", serde_json::json!({ "width": ["interpolate", ["linear"], ["zoom"], 10, 1, 20, 4] })).unwrap();
        let cx = crate::expr::Context { frame: crate::expr::Frame::at_zoom(15.0), tags: None };
        assert!(matches!(line.resolve(&cx), Some(crate::paint::Look::Line(l)) if l.width == 3));
    }

    use crate::profile::OutputSpec;
    use crate::grammar::from_yaml;
    use crate::units::{Mm, Scale};

    fn output() -> Output {
        let map = OutputSpec {
            address: None,
            lat: None,
            lng: None,
            width: Mm(100.0),
            height: Mm(50.0),
            scale: Scale(10000.0),
            bearing: 0.0,
            projection: crate::profile::ProjectionMode::default(),
            warp: Default::default(),
            padding: Default::default(),
            slices: Default::default(),
            tile_zoom: None,
            screen: None,
        };
        Output::new(&map, (0.0, 0.0))
    }

    /// A grammar with no OSM data: only the parts that need no fetch.
    fn run_yaml(yaml: &str) -> Result<Rendered, RunError> {
        let text = format!("output: {{ width: 100mm, height: 50mm }}\n{yaml}");
        let grammar = from_yaml(&text).expect("profile loads");
        run(
            &grammar,
            &output(),
            Inputs { features: vec![], tiles: vec![], sources: &BTreeMap::new(), terrain: None, memory_budget: None, google_fonts: BTreeMap::new(), stroke_fonts: BTreeMap::new(), data: BTreeMap::new(), views: Vec::new() },
        )
    }

    #[test]
    fn an_outline_label_is_filled_through_its_area() {
        // A system TrueType face stands in for the downloaded one; skipped
        // where there is none.
        let Some(bytes) = ["/System/Library/Fonts/Supplemental/Arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"]
            .iter()
            .find_map(|p| std::fs::read(p).ok())
        else {
            return;
        };
        let grammar = from_yaml(
            "output: { width: 100mm, height: 50mm }\n\
             $features:\n  parks: { osm_select: { leisure: park } }\n\
             $lines:\n  names: { tools_labels: { from: $features.parks, size: 5mm, min_size: 5mm, font: { origin: google, family: Arial } } }\n\
             $areas:\n  letters: { tools_label_area: $lines.names }\n\
             $fills:\n  ink: { tools_fill: { in: $areas.letters, pattern: lines, spacing: 0.3mm, angle: 45 } }\n\
             draw:\n  - { id: fill, from: $fills.ink }\n  - { id: labels, from: $lines.names }\n",
        )
        .expect("profile loads");
        let ring = vec![(-0.01, -0.005), (0.01, -0.005), (0.01, 0.005), (-0.01, 0.005), (-0.01, -0.005)];
        let park = Feature {
            element: crate::osm::Element::Way,
            id: 1,
            tags: [("leisure", "park"), ("name", "Golden Gate Park")].into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            geometry: geo::Geometry::Polygon(geo::Polygon::new(geo::LineString::from(ring), vec![])),
        };
        let fonts = BTreeMap::from([("Arial:400".to_string(), bytes)]);
        let out = run(
            &grammar,
            &output(),
            Inputs { features: vec![park], tiles: vec![], sources: &BTreeMap::new(), terrain: None, memory_budget: None, google_fonts: fonts, stroke_fonts: BTreeMap::new(), data: BTreeMap::new(), views: Vec::new() },
        )
        .unwrap();
        let count = |id: &str| out.groups.iter().find(|(g, _)| g == id).map_or(0, |(_, n)| *n);
        assert!(count("labels") > 0, "the letters are drawn");
        assert!(count("fill") > 0, "the letters are filled");

        let bad = "output: { width: 100mm, height: 50mm }\n$areas:\n  f: { engine_frame: {} }\n  x: { tools_label_area: $areas.f }\n";
        assert!(from_yaml(bad).is_err(), "tools_label_area reads a labels def only");
    }

    #[test]
    fn a_screen_hands_each_paint_entry_its_geometry() {
        let grammar = from_yaml(
            "output: { screen: { kind: bitmap, width: 40, height: 20 } }\n\
             $areas:\n  page: { engine_frame: {} }\n  inner: { tools_grow: { of: $areas.page, by: -2mm } }\n\
             $lines:\n  ring: { tools_rings: $areas.inner }\n\
             paint:\n  - { id: ground, from: $areas.page, fill: { tone: 0.5 } }\n  - { id: edge, from: $lines.ring, halo: 1 }\n",
        )
        .unwrap();
        let output = Output::new(&grammar.output, (0.0, 0.0));
        let empty = BTreeMap::new();
        let inputs = Inputs { features: vec![], tiles: vec![], sources: &empty, terrain: None, memory_budget: None, google_fonts: BTreeMap::new(), stroke_fonts: BTreeMap::new(), data: BTreeMap::new(), views: Vec::new() };
        let layers = paint(&grammar, &output, inputs, &Task::begin(&(), "t", None, "t", 0, "")).unwrap();
        assert_eq!(layers.iter().map(|l| l.id.as_str()).collect::<Vec<_>>(), ["ground", "edge"]);
        assert!(matches!(&layers[0].shape, PaintShape::Area(a) if !a.0.is_empty()));
        assert!(matches!(&layers[1].shape, PaintShape::Lines(l) if l.len() == 1));
        assert_eq!(layers[1].halo, crate::paint::Halo(1, 1));
    }

    #[test]
    fn polygons_only_filled_or_cut_are_left_unmerged() {
        let grammar = from_yaml(
            "output: { screen: { kind: bitmap, width: 40, height: 20 } }\n\
             $features:\n  b: { osm_select: { building: yes } }\n\
             $areas:\n  page: { engine_frame: {} }\n  filled: { tools_polygons: $features.b }\n  cut: { tools_polygons: $features.b }\n  \
             rest: { tools_difference: { base: $areas.page, cut: [$areas.cut] } }\n\
             paint:\n  - { id: filled, from: $areas.filled, fill: { pattern: solid } }\n  - { id: cut, from: $areas.cut, fill: { pattern: solid } }\n  \
             - { id: rest, from: $areas.rest, fill: { tone: 0.5 } }\n",
        )
        .unwrap();
        let square = |x: f64| Feature {
            element: crate::osm::Element::Way,
            id: 1,
            tags: [("building", "yes")].into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            geometry: geo::Geometry::Polygon(geo::Polygon::new(
                geo::LineString::from(vec![(x, -0.0001), (x + 0.0002, -0.0001), (x + 0.0002, 0.0001), (x, 0.0001), (x, -0.0001)]),
                vec![],
            )),
        };
        let output = Output::new(&grammar.output, (0.0, 0.0));
        let empty = BTreeMap::new();
        let inputs = Inputs { features: vec![square(0.0), square(0.0001)], tiles: vec![], sources: &empty, terrain: None, memory_budget: None, google_fonts: BTreeMap::new(), stroke_fonts: BTreeMap::new(), data: BTreeMap::new(), views: Vec::new() };
        let layers = paint(&grammar, &output, inputs, &Task::begin(&(), "t", None, "t", 0, "")).unwrap();
        let parts = |id: &str| match &layers.iter().find(|l| l.id == id).unwrap().shape {
            PaintShape::Area(a) => a.0.len(),
            _ => panic!("{id} is an area"),
        };
        assert_eq!(parts("filled"), 2, "only filled: the two overlapping squares as they are");
        assert_eq!(parts("cut"), 1, "read by a difference too: merged");
    }

    #[test]
    fn an_area_and_its_ring_reach_draw() {
        let out = run_yaml(
            "$areas:\n  block: { engine_frame: {} }\n\
             $lines:\n  ring: { tools_rings: { of: $areas.block, exterior_only: true } }\n\
             draw:\n  - { from: $lines.ring, stroke: solid }\n",
        )
        .unwrap();
        assert_eq!(out.groups, vec![("lines_ring".to_string(), 1)]);
        assert!(out.svg.contains(r#"<g id="lines_ring">"#));
    }

    #[test]
    fn a_mask_cuts_what_it_occludes_and_leaves_the_rest() {
        // The output is 100x50; `inner` is it inset by 20mm (60x10). The frame
        // ring (the output border) is entirely outside `inner`, so listing it in
        // `occludes` cannot delete it — but the two groups must differ, because
        // the half drawn over the mask is cut.
        let out = run_yaml(
            "$areas:\n  frame: { engine_frame: {} }\n  inner: { tools_grow: { of: $areas.frame, by: -20mm } }\n\
             $lines:\n  ring: { tools_rings: $areas.frame }\n\
             draw:\n  - { id: clipped, from: $lines.ring, stroke: solid }\n  - { id: whole, from: $lines.ring, stroke: solid }\n\
             compose:\n  masks:\n    cover: { from: $areas.inner, occludes: [clipped] }\n",
        )
        .unwrap();
        let strokes = |id: &str| out.groups.iter().find(|(g, _)| g == id).map(|(_, n)| *n).unwrap_or(0);
        // Both rings are the same geometry, so `occludes` is what differs.
        assert!(strokes("whole") >= 1);
        assert!(strokes("clipped") >= 1, "the border ring survives an interior mask");
    }

    #[test]
    fn a_mask_cuts_what_it_lists_wherever_it_sits_in_the_order() {
        // `inner`'s own ring is drawn first, the hatch over it; the mask made of
        // `inner` lists the hatch, so the hatch is cut although it is on top.
        let yaml = |masks: &str| {
            format!(
                "$areas:\n  frame: {{ engine_frame: {{}} }}\n  inner: {{ tools_grow: {{ of: $areas.frame, by: -20mm }} }}\n\
                 $lines:\n  edge: {{ tools_rings: $areas.inner }}\n\
                 $fills:\n  hatch: {{ tools_fill: {{ in: $areas.frame, pattern: lines, spacing: 5mm, angle: 0 }} }}\n\
                 draw:\n  - {{ id: edge, from: $lines.edge, stroke: solid }}\n  - {{ id: hatch, from: $fills.hatch }}\n{masks}"
            )
        };
        let strokes = |out: &Rendered, id: &str| out.groups.iter().find(|(g, _)| g == id).map_or(0, |(_, n)| *n);
        let whole = run_yaml(&yaml("")).unwrap();
        let cut = run_yaml(&yaml("compose:\n  masks:\n    cover: { from: $areas.inner, occludes: [hatch] }\n")).unwrap();
        assert!(strokes(&cut, "hatch") > strokes(&whole, "hatch"), "the lines across `inner` are split in two");
        assert_eq!(strokes(&cut, "edge"), strokes(&whole, "edge"), "a group the mask does not list is left alone");
    }

    #[test]
    fn clip_none_disables_the_masks() {
        let yaml = |clip: &str| {
            format!(
                "$areas:\n  frame: {{ engine_frame: {{}} }}\n  inner: {{ tools_grow: {{ of: $areas.frame, by: -20mm }} }}\n\
                 $lines:\n  ring: {{ tools_rings: $areas.frame }}\n\
                 draw:\n  - {{ id: ring, from: $lines.ring, stroke: solid }}\n\
                 compose:\n  masks:\n    cover: {{ from: $areas.inner, occludes: [ring] }}\n  clip:\n    default: {clip}\n"
            )
        };
        // `auto` cuts the ring halves that fall inside the mask; `none` keeps
        // every stroke. Same profile, one word apart.
        let auto = run_yaml(&yaml("auto")).unwrap();
        let none = run_yaml(&yaml("none")).unwrap();
        assert!(none.groups[0].1 >= auto.groups[0].1);
    }

    #[test]
    fn an_id_falls_back_and_order_is_honoured() {
        let out = run_yaml(
            "$areas:\n  a: { engine_frame: {} }\n\
             $lines:\n  one: { tools_rings: $areas.a }\n\
             draw:\n  - { id: top, from: $lines.one, stroke: solid }\n  - { from: $lines.one }\n\
             compose:\n  order: [lines_one, top]\n",
        )
        .unwrap();
        assert_eq!(out.groups.iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), vec!["lines_one", "top"]);
    }

    #[test]
    fn extend_to_frame_reaches_the_card_edges() {
        let text = "$areas:\n  frame: { engine_frame: {} }\n  inner: { tools_grow: { of: $areas.frame, by: -5mm } }\n  wet: { tools_extend_to_frame: { of: $areas.inner, within: $areas.frame, gap_mm: 6mm } }\n\
             $lines:\n  ring: { tools_rings: $areas.frame }\n\
             $fills:\n  waves: { tools_fill: { in: $areas.wet, pattern: lines, spacing: 1mm } }\n\
             draw:\n  - { id: sea, from: $fills.waves }\n  - { id: ring, from: $lines.ring, stroke: solid }\n";
        let out = run_yaml(text).unwrap();
        let strokes = |id: &str| out.groups.iter().find(|(g, _)| g == id).map_or(0, |(_, n)| *n);
        assert!(strokes("sea") >= 40, "one line per mm across the output, got {}", strokes("sea"));
        assert_eq!(strokes("ring"), 1);
    }

    #[test]
    fn solid_fill_paints_the_area_in_svg() {
        let yaml = "$areas:\n  a: { engine_frame: {} }\n$fills:\n  bg: { tools_fill: { in: $areas.a, pattern: solid } }\ndraw:\n  - { id: bg, from: $fills.bg, stroke: { color: \"#aabbcc\" } }\n";
        let out = run_yaml(yaml).unwrap();
        assert!(out.svg.contains("fill:#aabbcc"));
        assert!(out.svg.contains("fill=\"#aabbcc\""));
        assert!(out.svg.contains("<path"));
    }

    #[test]
    fn patterned_fill_can_paint_a_background_under_the_hatch() {
        let yaml = "$areas:\n  a: { engine_frame: {} }\n$fills:\n  hatch: { tools_fill: { in: $areas.a, pattern: lines, spacing: 1mm, background: \"#ddeeff\" } }\ndraw:\n  - { id: hatch, from: $fills.hatch, stroke: solid }\n";
        let out = run_yaml(yaml).unwrap();
        assert!(out.svg.contains("fill:#ddeeff"), "{}", out.svg);
        assert!(out.groups.iter().any(|(g, n)| g == "hatch" && *n > 0));
    }

    #[test]
    fn a_fill_takes_other_lines_as_its_content_cut_to_the_area() {
        // The ring of a 60x10 box inset in the frame, as the content of two
        // fills: kept whole in the frame, gone from a smaller box inside it.
        let out = run_yaml(
            "$areas:\n  frame: { engine_frame: {} }\n  inner: { tools_grow: { of: $areas.frame, by: -20mm } }\n  core: { tools_grow: { of: $areas.frame, by: -22mm } }\n\
             $lines:\n  ring: { tools_rings: $areas.inner }\n\
             $fills:\n  core: { tools_fill: { in: $areas.core, content: $lines.ring } }\n  all: { tools_fill: { in: $areas.frame, content: $lines.ring } }\n\
             draw:\n  - { id: core, from: $fills.core }\n  - { id: all, from: $fills.all }\n",
        )
        .unwrap();
        let strokes = |id: &str| out.groups.iter().find(|(g, _)| g == id).map_or(0, |(_, n)| *n);
        assert_eq!(strokes("core"), 0, "the ring is outside the smaller box");
        assert!(strokes("all") >= 1, "and inside the frame");
    }

    #[test]
    fn a_loop_is_reported_rather_than_hung() {
        // Grammar validation rejects loops already; keep the executor honest.
        let text = "output: { width: 100mm, height: 50mm }\n$areas:\n  a: { tools_union: [$areas.b] }\n  b: { tools_grow: { of: $areas.a, by: 1mm } }\n";
        let grammar = from_yaml(text);
        assert!(grammar.is_err(), "a loop must not load");
    }
}