mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
//! The drapes: a texture for each terrain tile and stack of draped layers,
//! which the stack's layers draw into, flat, as a small frame of their own,
//! and which the tile's draw of the stack samples.
//!
//! A drape draws the frame's layers with the map's camera, so zoom, bearing and
//! line widths are the map's, through a projection of the tile's square of the
//! world onto its texture ([`TransformParameters::for_drape`]). On the globe
//! the camera is the map's on Mercator ([`View::mercator`]), so the layers draw
//! as flat as on a Mercator map, but size what they size in pixels at the
//! globe's pixel scale, as the globe shows it at the equator
//! ([`LayerFrame::pixel_scale`]). A drape draws the tiles over its own tile: on
//! Mercator those of its world copy; on the globe, which has no copies, those
//! of any, in its own, so that near the antimeridian it holds the tiles that
//! the cover puts in the next copy. Each draped layer has draws of its own in
//! each drape of its stack, which the layer makes as it makes the frame's, for
//! the drape's frame ([`RenderLayer::update_drape_draws`]), and which the
//! engine draws with the drape's uniforms, clip masks and stencil. The drapes
//! draw the layer's values of its tiles, which it keeps once for the frame and
//! every drape a tile overlaps.
//!
//! A drape draws again only when what its layers would draw it from differs
//! from what they last drew it from ([`DrapeKey`]), or its side changes;
//! otherwise it keeps its texels. A drape whose layers make no draw has no
//! texture, so a stack that draws nothing in a tile holds no memory there.
//!
//! A drape's side is twice its tile's, or the device's largest texture where
//! that is smaller ([`drape_size`]). Where the map sets a byte cap
//! ([`TerrainOptions::drape_memory_limit`]), it lowers the sides of the tiles
//! farthest from the view's center, last in the cover, where the drapes'
//! textures and the depth and stencil they draw with would hold more; it never
//! drops a tile. The sides are settled before the layers update their draws, so
//! a drape that changes takes its tile's side at once. The cap counts as
//! holding a texture every drape that does, and every drape whose layers draw
//! from something new, which may draw something.
//!
//! A draped layer with a layer opacity below 1 or a layer blend other than
//! `normal` draws as a whole inside each drape, as in 2D
//! ([`LayerComposite`]): into a texture of the drape's side, composited onto
//! the drape. The drapes of a side share one such composite, which each
//! drape's pass uses in turn and which holds textures only in a frame where
//! such a drape draws. A drape with a layer that blends in the shader draws
//! into the composite's frame texture, which is copied into the drape before
//! its mips, so a blend's backdrop is the drape's own texels.
//!
//! [`RenderLayer::update_drape_draws`]: crate::layer::render_layer::RenderLayer::update_drape_draws
//! [`TerrainOptions::drape_memory_limit`]: crate::map::TerrainOptions::drape_memory_limit

use std::sync::Arc;
use std::time::Duration;

use mln_gfx::gpu::{ColorAttachment, DepthStencilAttachment, Gpu, LoadOp, TargetFormats, TextureFormat};
use mln_gfx::shaders::layer_ubo::GlobalPaintParamsUBO;
use mln_gfx::texture2d::SamplerState;
use mln_gfx::types::{TextureFilterType, TextureWrapType};
use mln_gfx::{Rgba, Size};
use mln_style::expression::GlobalStateMap;
use mln_style::layer::ErasedLayerStyle;
use mln_style::sort;
use mln_style::time::Instant;
use smallvec::SmallVec;

use super::TerrainCover;
use crate::camera::View;
use crate::draw::context::Context;
use crate::draw::draws::{DrawGroups, DrawOrder, Draws};
use crate::draw::resources::{GpuTexture, attachment_bytes};
use crate::draw::store::Texture;
use crate::layer::layer_drawing::ChangedBuckets;
use crate::layer::layer_type::ErasedEvaluatedLayer;
use crate::layer::render_layer::{DrapeTile, FrameSourceTiles, RenderLayer};
use crate::render::clip_masks::ClipMasks;
use crate::render::layer_composite::LayerComposite;
use crate::render::paint_parameters::{OpenPass, PaintParameters, TransformParameters};
use crate::render::pass::RenderPass;
use crate::render::tile::TileStamp;
use crate::tile::OverscaledTileID;

/// The format of a drape's texture.
const COLOR: TextureFormat = TextureFormat::Rgba8Unorm;
/// The format of the depth and stencil the drapes draw with.
const DEPTH_STENCIL: TextureFormat = TextureFormat::Depth24PlusStencil8;
/// The most samples the terrain takes of a drape along a pixel's footprint.
const MAX_ANISOTROPY: u8 = 16;
/// How far the map's zoom may drift from a drape's last drawn zoom while
/// actively zooming before the drape redraws; once zoom stops changing, a
/// follow-up frame refines any deferred drapes to the exact zoom.
const ZOOM_DRAPE_STEP: f64 = 0.5;
/// How long zoom may remain unchanged during ongoing camera motion before
/// zoom-deferred drapes treat zoom as settled and refine. Keeps input gaps
/// (e.g. a display refreshing faster than input events arrive) from flushing
/// all deferred drapes mid-motion while still refining when motion pauses.
const ZOOM_SETTLE_DELAY: Duration = Duration::from_millis(100);
/// Maximum number of staggerable drapes (already-textured stale drapes during
/// motion/refinement, and brand-new child drapes backed by a retired ancestor
/// stand-in) to render in one frame, nearest-tile-first.
const MAX_DRAPES_PER_FRAME: usize = 2;

/// Follow-up repaint requested by deferred drapes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum DrapeRepaint {
    #[default]
    None,
    /// Staggered drapes are queued behind the per-frame budget and should
    /// continue draining on the very next frame.
    Immediate,
    /// Zoom-deferred drapes are waiting for zoom to settle before refining.
    At(Instant),
}

#[derive(Clone, Copy, PartialEq)]
struct CameraStamp {
    zoom: f64,
    angle: f64,
    pitch: f64,
    center: [f64; 2],
}

impl CameraStamp {
    fn of(view: &View) -> Self {
        let center = view.center(mln_style::geo::WrapMode::Unwrapped);
        CameraStamp {
            zoom: view.zoom(),
            angle: view.angle(),
            pitch: view.pitch(),
            center: [center.latitude(), center.longitude()],
        }
    }
}

const IDENTITY_DRAPE_COORDS: [f32; 4] = [1.0, 0.0, 0.0, 0.0];

/// UV transform `[scale, offset_x, offset_y, 0.0]` mapping `child`'s `[0, 1]`
/// tile UVs into `parent`'s drape texture when `child` is a strict descendant
/// of `parent` (in the same world copy on Mercator, or any copy on the globe).
fn ancestor_drape_coords(child: OverscaledTileID, parent: OverscaledTileID, globe: bool) -> Option<[f32; 4]> {
    if (!globe && child.wrap != parent.wrap) || child.canonical.z <= parent.canonical.z {
        return None;
    }
    if !child.canonical.is_child_of(&parent.canonical) {
        return None;
    }
    let dz = child.canonical.z - parent.canonical.z;
    let factor = 1u32.checked_shl(u32::from(dz))?;
    let scale = 1.0 / factor as f32;
    let offset_x = (child.canonical.x - (parent.canonical.x << dz)) as f32 * scale;
    let offset_y = (child.canonical.y - (parent.canonical.y << dz)) as f32 * scale;
    Some([scale, offset_x, offset_y, 0.0])
}

/// Squared distance in normalized world coordinates from `center` to `tile`'s
/// center, putting mixed-LOD zooms and wrapped copies in a common coordinate
/// space so the redraw budget always prefers nearer tiles.
fn tile_distance_sq(tile: OverscaledTileID, center: (f64, f64), globe: bool) -> f64 {
    let tiles = f64::from(1u32 << tile.canonical.z);
    let tx = f64::from(tile.wrap) + (f64::from(tile.canonical.x) + 0.5) / tiles;
    let ty = (f64::from(tile.canonical.y) + 0.5) / tiles;
    let mut dx = tx - center.0;
    if globe {
        dx = (dx + 0.5).rem_euclid(1.0) - 0.5;
    }
    let dy = ty - center.1;
    dx * dx + dy * dy
}

/// The most texels a side of the drapes of terrain tiles of `tile_size`
/// pixels, on a device whose textures have at most `max_texture_size`
/// texels a side: twice as wide, whatever the pixel ratio, or the device's
/// largest.
pub(crate) fn drape_size(tile_size: u16, max_texture_size: u32) -> u32 {
    (u32::from(tile_size) * 2).min(max_texture_size).max(1)
}

/// The bytes of a drape's texture of `side` texels a side, with its mips,
/// as [`Texture2D::bytes`](crate::draw::texture2d::Texture2D::bytes)
/// counts them.
fn texture_bytes(side: u32) -> u64 {
    let bytes = attachment_bytes(Size::new(side, side), COLOR);
    bytes + bytes / 3
}

/// The bytes that the drapes of tiles whose drapes take `sizes` hold, where
/// `held` drapes of each tile have a texture, with a depth and stencil of
/// each side they have.
fn held_bytes(sizes: &[u32], held: &[usize]) -> u64 {
    let mut sides: SmallVec<[u32; 8]> = SmallVec::new();
    let mut bytes = 0;
    for (&size, &held) in sizes.iter().zip(held).filter(|&(_, &held)| held > 0) {
        bytes += held as u64 * texture_bytes(size);
        if !sides.contains(&size) {
            sides.push(size);
        }
    }
    bytes + sides.iter().map(|&side| attachment_bytes(Size::new(side, side), DEPTH_STENCIL)).sum::<u64>()
}

/// Lowers `sizes`, each the side of the drapes of a tile of which `held`
/// have a texture, nearest the view's center first, until they hold at
/// most `cap` bytes ([`held_bytes`]): the largest side allowed halves a
/// step at a time, for the tiles farthest from the center first, down to a
/// texel.
fn cap_sizes(sizes: &mut [u32], held: &[usize], cap: u64) {
    let mut limit = sizes.iter().copied().max().unwrap_or(0);
    while held_bytes(sizes, held) > cap && limit > 1 {
        let lower = limit / 2;
        for tile in (0..sizes.len()).rev() {
            if sizes[tile] > lower {
                sizes[tile] = lower;
                if held_bytes(sizes, held) <= cap {
                    return;
                }
            }
        }
        limit = lower;
    }
}

/// What a drape keeps of a layer: its draws there, with the style they
/// were made for.
struct DrapeLayer {
    style: Arc<dyn ErasedLayerStyle>,
    draws: Draws,
}

/// What a draped layer draws a drape with: its style, evaluated values, and
/// passes.
struct LayerKey {
    style: Arc<dyn ErasedLayerStyle>,
    evaluated: Arc<dyn ErasedEvaluatedLayer>,
    passes: RenderPass,
    /// The number of the layer's tiles among the key's.
    tiles: usize,
}

/// What a drape's layers draw it from, but for its side: their values,
/// what they draw of their tiles, the global paint values their draws read
/// if a layer draws by zoom, and the map's bearing if a layer draws by it.
/// A drape drawn from the same at the same side would get the same texels.
///
/// The images of the style, and the feature state of the tiles' buckets,
/// aren't in it: a change of them makes the drapes they show in draw again
/// ([`Drapes::redraw`], [`Drapes::mark_changed`]).
#[derive(Default)]
struct DrapeKey {
    /// The draped layers, in drawing order.
    layers: Vec<LayerKey>,
    /// The layers' tiles, each layer's after the one before's.
    tiles: Vec<TileStamp>,
    /// The style's global state when keyed, so a state edit while zooming
    /// never defers.
    global_state: Option<Arc<GlobalStateMap>>,
    /// The global paint values of the drape's draws, without its side, or
    /// `None` when no layer in the stack draws by zoom.
    paint: Option<GlobalPaintParamsUBO>,
    /// The map zoom when keyed; ignored by [`same`](Self::same), used by
    /// [`same_except_zoom`](Self::same_except_zoom) to bound zoom drift while
    /// actively zooming.
    zoom: f64,
    /// The map's bearing, which a layer draws by, or `None`.
    bearing: Option<f64>,
    /// Whether the terrain surface shades this stack's drapes (slopes rather
    /// than shaded colors).
    lit: bool,
    /// Whether any layer in this stack had an active paint transition or
    /// continuous/scheduled repaint when keyed.
    has_transition: bool,
}

impl DrapeKey {
    fn same_global_state(&self, drawn: &DrapeKey) -> bool {
        match (&self.global_state, &drawn.global_state) {
            (Some(a), Some(b)) => Arc::ptr_eq(a, b),
            (None, None) => true,
            _ => false,
        }
    }

    /// Whether a drape drawn from `drawn` holds what this key would draw:
    /// the same layers' values, from the same tiles, with the same lighting
    /// mode, the same global paint values if a layer draws by zoom, and at
    /// the same bearing if a layer draws by it.
    fn same(&self, drawn: &DrapeKey) -> bool {
        let same_paint = match (&self.paint, &drawn.paint) {
            (Some(a), Some(b)) => bytemuck::bytes_of(a) == bytemuck::bytes_of(b),
            (None, None) => true,
            _ => false,
        };
        self.lit == drawn.lit
            && self.tiles == drawn.tiles
            && self.bearing == drawn.bearing
            && same_paint
            && self.layers.len() == drawn.layers.len()
            && self
                .layers
                .iter()
                .zip(&drawn.layers)
                .all(|(layer, drawn)| Arc::ptr_eq(&layer.evaluated, &drawn.evaluated) && layer.tiles == drawn.tiles)
    }

    /// Whether `drawn` has the same stack structure (lighting mode, bearing,
    /// global state, layer styles, render passes, non-zoom paint parameters,
    /// and no transitions on either key).
    fn can_stand_in(&self, drawn: &DrapeKey) -> bool {
        let same_non_zoom_paint = match (&self.paint, &drawn.paint) {
            (Some(a), Some(b)) => {
                a.aspect_ratio.to_bits() == b.aspect_ratio.to_bits()
                    && a.pixel_ratio.to_bits() == b.pixel_ratio.to_bits()
                    && a.camera_to_center_distance.to_bits() == b.camera_to_center_distance.to_bits()
                    && a.symbol_fade_change.to_bits() == b.symbol_fade_change.to_bits()
                    && a.shows_horizon == b.shows_horizon
            }
            (None, None) => true,
            _ => false,
        };
        self.lit == drawn.lit
            && !self.has_transition
            && !drawn.has_transition
            && self.bearing == drawn.bearing
            && self.same_global_state(drawn)
            && same_non_zoom_paint
            && self.layers.len() == drawn.layers.len()
            && self
                .layers
                .iter()
                .zip(&drawn.layers)
                .all(|(layer, drawn)| Arc::ptr_eq(&layer.style, &drawn.style) && layer.passes == drawn.passes)
    }

    /// Whether a drape drawn from `drawn` differs only by a zoom change within
    /// [`ZOOM_DRAPE_STEP`].
    fn same_except_zoom(&self, drawn: &DrapeKey) -> bool {
        (self.zoom - drawn.zoom).abs() < ZOOM_DRAPE_STEP
            && self.tiles == drawn.tiles
            && self.can_stand_in(drawn)
            && self.layers.iter().zip(&drawn.layers).all(|(layer, drawn)| layer.tiles == drawn.tiles)
    }

    /// Whether a bucket in `changed` is among the key's.
    fn holds(&self, changed: &ChangedBuckets) -> bool {
        self.tiles.iter().any(|tile| tile.bucket.is_some_and(|bucket| changed.contains(bucket)))
    }
}

/// A drape texture from a recently retired ancestor tile, kept only while
/// active child drapes sample it as a stand-in while rendering their own.
struct RetiredStack {
    texture: Texture,
    side: u32,
    drawn: DrapeKey,
}

struct RetiredDrape {
    tile: OverscaledTileID,
    stacks: Vec<Option<RetiredStack>>,
}

/// The drape of a terrain tile for one stack of draped layers.
#[derive(Default)]
struct StackDrape {
    /// The texture, and its side in texels, while the stack's layers draw
    /// something in the tile.
    texture: Option<(Texture, u32)>,
    /// An ancestor's texture, UV transform, and tile id used as a temporary
    /// stand-in while this brand-new drape waits for its turn to render.
    stand_in: Option<(Texture, [f32; 4], OverscaledTileID)>,
    /// What the drape keeps of the stack's layers, in drawing order.
    layers: Vec<DrapeLayer>,
    /// What it kept of the layers in the last frame that this frame's
    /// layers haven't taken yet, which goes once it has updated them.
    previous: Vec<DrapeLayer>,
    /// The groups of the layers' draws, which set the pass's depths and the
    /// masks it clips to.
    groups: DrawGroups,
    /// What the layers last drew it from, or found nothing to draw in it
    /// from; `None` before they first do, and once it must draw again.
    drawn: Option<DrapeKey>,
    /// What the frame's layers would draw it from.
    key: DrapeKey,
    /// Whether any layer in this stack draws by the map's zoom in this frame.
    by_zoom: bool,
    /// Whether this drape deferred a redraw because zoom is within
    /// [`ZOOM_DRAPE_STEP`].
    zoom_deferred: bool,
    /// Whether this drape deferred a redraw due to the per-frame budget
    /// (stale redraw or brand-new drape using a parent stand-in).
    budget_deferred: bool,
    /// Whether the frame's layers update its draws, and it draws again
    /// if they draw something.
    updated: bool,
}

/// The drapes of a terrain tile, one for each stack, which share the clip
/// masks of the tile's projection.
struct Drape {
    tile: OverscaledTileID,
    transform: TransformParameters,
    /// The side in texels of its drapes in the frame.
    size: u32,
    clip_masks: ClipMasks,
    stacks: Vec<StackDrape>,
}

/// What the drapes of one side draw with, one after another: a depth and
/// stencil, and what their layers drawn as a whole draw into and composite
/// with.
struct Targets {
    side: u32,
    depth_stencil: Option<GpuTexture>,
    layer_composite: LayerComposite,
}

/// The drapes of the terrain tiles of a frame, in the cover's order.
#[derive(Default)]
pub(crate) struct Drapes {
    drapes: Vec<Drape>,
    /// The drapes' tiles, in id order.
    tiles: Vec<OverscaledTileID>,
    /// Whether the frame's view is on the globe, where a drape draws the
    /// tiles over its own whatever their world copy.
    globe: bool,
    /// The most texels a side of a drape ([`drape_size`]).
    largest: u32,
    /// The most bytes the drapes' textures and depths and stencils hold
    /// before the tiles farthest from the view's center take fewer texels.
    byte_cap: u64,
    /// What the drapes draw with, for each side that a drape's texture has.
    targets: Vec<Targets>,
    /// Recently dropped ancestor drapes retained only while active child
    /// drapes sample them as temporary stand-ins.
    retired: Vec<RetiredDrape>,
    /// Camera state of the previous frame and motion tracking, to detect
    /// continuous camera/zoom movement even when driven by `jump_to`.
    last_camera: Option<CameraStamp>,
    was_camera_moving: bool,
    camera_changing: bool,
    zoom_changing: bool,
    last_zoom_moved_at: Option<Instant>,
    /// Follow-up repaint needed for any deferred drapes from the last frame.
    repaint: DrapeRepaint,
}

impl Drapes {
    /// Starts a frame's update of the drapes, those of `cover`'s tiles in
    /// `view`, and of `stacks` stacks: keeps the drapes of the tiles and stacks
    /// it had, with what they keep of their layers and what they were drawn
    /// from, and drops the others. Each tile's drapes take twice the tile's
    /// side, at most `max_texture_size` ([`drape_size`]), lowered where they
    /// would hold more than `byte_cap` bytes ([`choose`](Self::choose)). The
    /// frame's draped layers then give their keys
    /// ([`key_layer`](Self::key_layer)), from which `choose` picks the drapes
    /// whose draws they update ([`update_layer`](Self::update_layer)). The
    /// layers draw into the drapes as on Mercator, on the globe too
    /// ([`View::mercator`]).
    pub(crate) fn begin(
        &mut self,
        view: &View,
        cover: &TerrainCover,
        stacks: usize,
        (byte_cap, max_texture_size): (u64, u32),
    ) {
        self.largest = drape_size(cover.tile_size, max_texture_size);
        self.globe = view.is_globe();
        self.byte_cap = byte_cap;
        let prev_stacks = self.stacks();
        if prev_stacks != stacks {
            self.retired.clear();
        }
        let mut kept = std::mem::take(&mut self.drapes);
        self.drapes.reserve(cover.tiles.len());
        let flat = view.mercator();
        let pixel_scale = view.projection().pixel_scale(view);
        for tile in &cover.tiles {
            let unwrapped = tile.id.to_unwrapped();
            let transform = TransformParameters::for_drape(&flat, pixel_scale, &unwrapped);
            let mut drape = match kept.iter().position(|drape| drape.tile == tile.id) {
                Some(index) => Drape { transform, ..kept.swap_remove(index) },
                None => {
                    Drape { tile: tile.id, transform, size: 0, clip_masks: ClipMasks::default(), stacks: Vec::new() }
                }
            };
            drape.stacks.resize_with(stacks, StackDrape::default);
            for drape in &mut drape.stacks {
                drape.key.layers.clear();
                drape.key.tiles.clear();
                drape.key.global_state = None;
                drape.key.paint = None;
                drape.key.bearing = None;
                drape.key.lit = false;
                drape.key.has_transition = false;
                drape.by_zoom = false;
                drape.zoom_deferred = false;
                drape.budget_deferred = false;
                drape.stand_in = None;
            }
            self.drapes.push(drape);
        }
        // Keep dropped tiles' textured drapes in `retired` as candidate
        // ancestor stand-ins for any newly entered child tiles this frame.
        if prev_stacks == stacks {
            for dropped in kept {
                let mut retired_stacks: Vec<Option<RetiredStack>> = Vec::with_capacity(dropped.stacks.len());
                let mut any = false;
                for stack in dropped.stacks {
                    if let (Some((texture, side)), Some(drawn)) = (stack.texture, stack.drawn) {
                        retired_stacks.push(Some(RetiredStack { texture, side, drawn }));
                        any = true;
                    } else {
                        retired_stacks.push(None);
                    }
                }
                if any {
                    if let Some(existing) = self.retired.iter_mut().find(|r| r.tile == dropped.tile) {
                        existing.stacks = retired_stacks;
                    } else {
                        self.retired.push(RetiredDrape { tile: dropped.tile, stacks: retired_stacks });
                    }
                }
            }
        }
        self.tiles.clear();
        self.tiles.extend(self.drapes.iter().map(|drape| drape.tile));
        self.tiles.sort();
        self.tiles.dedup();
    }

    /// Follow-up repaint needed for any deferred drapes from the last frame.
    pub(crate) fn repaint(&self) -> DrapeRepaint {
        self.repaint
    }

    /// How many stacks the drapes of each tile are of.
    pub(crate) fn stacks(&self) -> usize {
        self.drapes.first().map_or(0, |drape| drape.stacks.len())
    }

    /// Adds `layer`, a layer of `stack` that drapes, which draws from
    /// `source`, to the key of every drape of the stack. The stack's layers
    /// come in drawing order. A stack that the surface `lit` holds what
    /// doesn't turn with the map.
    pub(crate) fn key_layer(
        &mut self,
        stack: usize,
        layer: &dyn RenderLayer,
        source: Option<FrameSourceTiles<'_>>,
        lit: bool,
    ) {
        let base = layer.base();
        let by_bearing = !lit && base.evaluation.drapes_by_bearing;
        let by_zoom = !lit && base.evaluation.drapes_by_zoom;
        let transitioning = layer.has_transition() || layer.needs_repaint() || layer.repaint_at().is_some();
        let found = source.zip(layer.found());
        for drape in &mut self.drapes {
            let Some(StackDrape { key, by_zoom: stack_by_zoom, .. }) = drape.stacks.get_mut(stack) else {
                continue;
            };
            let start = key.tiles.len();
            // What the layer draws of each tile it draws the drape from.
            if let Some((source, found)) = &found {
                key.tiles.extend(source.stamps(found.clone(), drape.tile.to_unwrapped(), self.globe));
            }
            if by_bearing {
                key.bearing = Some(drape.transform.view.angle());
            }
            key.lit = lit;
            key.has_transition |= transitioning;
            *stack_by_zoom |= by_zoom;
            key.layers.push(LayerKey {
                style: Arc::clone(&base.style),
                evaluated: Arc::clone(&base.evaluated_properties),
                passes: base.passes,
                tiles: key.tiles.len() - start,
            });
        }
    }

    /// Settles the side of each tile's drapes and chooses the drapes whose
    /// draws the frame's layers update, once every draped layer gave its
    /// key, with the frame's `parameters`.
    ///
    /// Each tile's drapes take the largest side, lowered where the drapes
    /// that hold a texture, and the depth and stencil of each side, would
    /// hold more than the byte cap ([`cap_sizes`]). The cap counts the
    /// drapes that have a texture and keep their key, and those whose key
    /// changed, which may draw something. A drape updates where its key
    /// differs from the one it was drawn from, or it has a texture of another
    /// side than its tile's.
    pub(crate) fn choose(
        &mut self,
        parameters: &mut PaintParameters<'_>,
        global_state: &Arc<GlobalStateMap>,
        time_point: Option<Instant>,
        allow_defer: bool,
    ) {
        let camera = CameraStamp::of(parameters.view);
        let zoom = camera.zoom;
        let zoom_moved = self.last_camera.is_some_and(|prev| prev.zoom != zoom);
        let camera_moved = self.last_camera.is_some_and(|prev| prev != camera);
        if zoom_moved {
            self.last_zoom_moved_at = time_point;
        }
        // Keep zoom-deferred drapes deferred across brief gaps between input
        // updates (< ZOOM_SETTLE_DELAY), unless `camera_moving` just dropped
        // from true to false (gesture/animation ended — refine immediately).
        let motion_ended = self.was_camera_moving && !parameters.camera_moving;
        let within_settle = !motion_ended
            && self.zoom_changing
            && time_point
                .zip(self.last_zoom_moved_at)
                .is_some_and(|(now, last)| now.saturating_duration_since(last) < ZOOM_SETTLE_DELAY);
        let active_zoom =
            !motion_ended && if zoom_moved { parameters.camera_moving || self.zoom_changing } else { within_settle };
        if !active_zoom {
            self.last_zoom_moved_at = None;
        }
        let zooming = allow_defer && active_zoom;
        let stagger = allow_defer
            && (parameters.camera_moving
                || self.camera_changing
                || self.zoom_changing
                || self.repaint != DrapeRepaint::None);
        self.was_camera_moving = parameters.camera_moving;
        self.zoom_changing = (zoom_moved && !motion_ended) || within_settle;
        self.camera_changing = camera_moved;
        self.last_camera = Some(camera);
        self.repaint = DrapeRepaint::None;

        // Rank tiles nearest-to-view-center in normalized world coordinates so
        // the per-frame budget favors nearer tiles even on mixed-LOD or wrapped
        // covers, while leaving `self.drapes` in `cover.tiles` order.
        let center = parameters.view.center_world();
        let center = (center.x, center.y);
        let globe = self.globe;
        let mut order: SmallVec<[usize; 16]> = (0..self.drapes.len()).collect();
        sort::sort_indices_by(&mut order, |a, b| {
            tile_distance_sq(self.drapes[a].tile, center, globe).total_cmp(&tile_distance_sq(
                self.drapes[b].tile,
                center,
                globe,
            ))
        });

        let mut budget = MAX_DRAPES_PER_FRAME;
        let retired = &self.retired;
        let mut held = vec![0usize; self.drapes.len()];
        let mut live_held = vec![0usize; self.drapes.len()];
        for &tile_idx in &order {
            let Drape { tile, transform, stacks, .. } = &mut self.drapes[tile_idx];
            let paint = stacks.iter().any(|drape| drape.by_zoom).then(|| {
                let (clip_masks, composite) = (&mut ClipMasks::default(), &mut LayerComposite::default());
                let drape = parameters.drape(transform, clip_masks, composite, Size::new(0, 0), tile.to_unwrapped());
                drape.global_paint_params()
            });
            let mut tile_held = 0;
            let mut tile_live_held = 0;
            for (stack_idx, drape) in stacks.iter_mut().enumerate() {
                drape.key.global_state = Some(Arc::clone(global_state));
                drape.key.paint = if drape.by_zoom { paint } else { None };
                drape.key.zoom = zoom;
                let exact = drape.drawn.as_ref().is_some_and(|drawn| drape.key.same(drawn));
                let zoom_defer =
                    !exact && zooming && drape.drawn.as_ref().is_some_and(|drawn| drape.key.same_except_zoom(drawn));
                let budget_defer = if exact || zoom_defer {
                    false
                } else if allow_defer && drape.texture.is_none() && drape.drawn.is_none() {
                    // Brand-new drape with a compatible retired ancestor:
                    // render progressively while sampling the ancestor sub-rect.
                    let best_ancestor = retired
                        .iter()
                        .filter_map(|ancestor| {
                            let coords = ancestor_drape_coords(*tile, ancestor.tile, globe)?;
                            let stack = ancestor.stacks.get(stack_idx)?.as_ref()?;
                            drape.key.can_stand_in(&stack.drawn).then_some((
                                ancestor.tile,
                                stack.texture.clone(),
                                coords,
                            ))
                        })
                        .max_by_key(|(ancestor_tile, _, _)| ancestor_tile.canonical.z);
                    if let Some((ancestor_tile, texture, coords)) = best_ancestor {
                        if budget > 0 {
                            budget -= 1;
                            false
                        } else {
                            drape.stand_in = Some((texture, coords, ancestor_tile));
                            true
                        }
                    } else {
                        false
                    }
                } else if stagger
                    && drape.texture.is_some()
                    && drape.drawn.as_ref().is_some_and(|drawn| drape.key.can_stand_in(drawn))
                {
                    if budget > 0 {
                        budget -= 1;
                        false
                    } else {
                        true
                    }
                } else {
                    false
                };
                drape.zoom_deferred = zoom_defer;
                drape.budget_deferred = budget_defer;
                let kept = exact || zoom_defer || budget_defer;
                drape.updated = !kept;
                let live = !kept || drape.texture.is_some();
                tile_live_held += usize::from(live);
                // Count waiting stand-in children in `tile_held` too so
                // `cap_sizes` stays stable as they drain instead of shrinking
                // active drapes on later frames.
                tile_held += usize::from(live || drape.stand_in.is_some());
            }
            held[tile_idx] = tile_held;
            live_held[tile_idx] = tile_live_held;
        }
        let mut sizes = vec![self.largest; self.drapes.len()];
        cap_sizes(&mut sizes, &held, self.byte_cap);
        // Prune retired stacks not referenced by any stand-in, and drop all
        // stand-ins only if the textures and attachments that actually coexist
        // this frame (`live_held` + `retired_bytes`) would exceed `byte_cap`.
        // `held` already counts waiting children, so `sizes` remains unchanged.
        let mut retired_bytes = 0u64;
        for ancestor in &mut self.retired {
            for (stack_idx, slot) in ancestor.stacks.iter_mut().enumerate() {
                let referenced = self.drapes.iter().any(|drape| {
                    drape
                        .stacks
                        .get(stack_idx)
                        .is_some_and(|stack| stack.stand_in.as_ref().is_some_and(|(_, _, tile)| *tile == ancestor.tile))
                });
                if !referenced {
                    *slot = None;
                } else if let Some(stack) = slot {
                    retired_bytes = retired_bytes.saturating_add(texture_bytes(stack.side));
                }
            }
        }
        if self.byte_cap < u64::MAX
            && retired_bytes > 0
            && held_bytes(&sizes, &live_held).saturating_add(retired_bytes) > self.byte_cap
        {
            for drape in &mut self.drapes {
                for stack in &mut drape.stacks {
                    if stack.stand_in.take().is_some() {
                        stack.budget_deferred = false;
                        stack.updated = true;
                    }
                }
            }
            self.retired.clear();
        } else {
            self.retired.retain(|ancestor| ancestor.stacks.iter().any(Option::is_some));
        }
        let mut any_budget_deferred = false;
        let mut any_zoom_deferred = false;
        for (drape, size) in self.drapes.iter_mut().zip(sizes) {
            drape.size = size;
            for drape in &mut drape.stacks {
                drape.updated |= drape.texture.as_ref().is_some_and(|&(_, side)| side != size);
                if drape.updated {
                    drape.zoom_deferred = false;
                    drape.budget_deferred = false;
                    drape.stand_in = None;
                    drape.previous = std::mem::take(&mut drape.layers);
                }
                any_budget_deferred |= drape.budget_deferred;
                any_zoom_deferred |= drape.zoom_deferred;
            }
        }
        self.repaint = if any_budget_deferred {
            DrapeRepaint::Immediate
        } else if any_zoom_deferred {
            match time_point {
                Some(now) => DrapeRepaint::At(self.last_zoom_moved_at.unwrap_or(now) + ZOOM_SETTLE_DELAY),
                None => DrapeRepaint::Immediate,
            }
        } else {
            DrapeRepaint::None
        };
    }

    /// Makes the draws of `layer`, a layer of `stack` that drapes, in every
    /// drape of the stack that [`choose`](Self::choose) chose, with the
    /// drape's `parameters`, from its `source`, for the surface to shade if
    /// it `lit` the stack ([`PaintParameters::drape_lit`]). The stack's
    /// layers update in drawing order.
    pub(crate) fn update_layer(
        &mut self,
        stack: usize,
        gpu: &mut dyn Gpu,
        parameters: &mut PaintParameters<'_>,
        layer: &mut dyn RenderLayer,
        source: Option<FrameSourceTiles<'_>>,
        lit: bool,
    ) {
        let (globe, tiles) = (self.globe, &self.tiles);
        let style = Arc::clone(&layer.base().style);
        // The draws' updates don't read what the layers composite with, which
        // the upload makes.
        let layer_composite = &mut LayerComposite::default();
        for Drape { tile, transform, size, clip_masks, stacks, .. } in &mut self.drapes {
            let Some(StackDrape { layers, previous, .. }) = stacks.get_mut(stack).filter(|drape| drape.updated) else {
                continue;
            };
            // What was made for another style of the layer goes, as the
            // layer's own draws do.
            let kept = previous.iter().position(|kept| Arc::ptr_eq(&kept.style, &style));
            let mut kept = match kept {
                Some(index) => previous.swap_remove(index),
                None => DrapeLayer { style: Arc::clone(&style), draws: Draws::default() },
            };
            let (unwrapped, size) = (tile.to_unwrapped(), Size::new(*size, *size));
            let mut parameters = parameters.drape(transform, clip_masks, layer_composite, size, unwrapped);
            parameters.drape_lit = lit;
            let drape = DrapeTile { tile: *tile, globe, tiles };
            layer.update_drape_draws(gpu, &mut parameters, source, drape, &mut kept.draws);
            layers.push(kept);
        }
    }

    /// Ends the frame's update of the drapes: what they kept of layers that
    /// no longer drape in their stack goes. An updated drape whose layers draw
    /// something has a texture of its tile's side, made in the stores of
    /// `context`, which it draws again; one whose layers draw nothing lets
    /// go of its texture and draws no pass.
    pub(crate) fn finish_update(&mut self, context: &mut Context) {
        for Drape { size, stacks, .. } in &mut self.drapes {
            for drape in stacks.iter_mut() {
                drape.previous.clear();
                if !drape.updated {
                    continue;
                }
                let mut draws = false;
                for layer in &drape.layers {
                    layer.draws.visit_groups(&mut |group| draws |= group.draws());
                }
                if !draws {
                    drape.texture = None;
                    drape.updated = false;
                    drape.drawn = Some(std::mem::take(&mut drape.key));
                } else if drape.texture.as_ref().is_none_or(|&(_, side)| side != *size) {
                    drape.texture = Some((drape_texture(context, *size), *size));
                }
            }
        }
    }

    /// The meshes that the draws of each drape of `stack` that has a
    /// texture draw, by their order ([`Mesh::seq`]), in the cover's order.
    ///
    /// [`Mesh::seq`]: crate::draw::objects::Mesh::seq
    #[cfg(test)]
    pub(crate) fn meshes(&self, stack: usize) -> Vec<(OverscaledTileID, Vec<i64>)> {
        let drapes = self.drapes.iter().filter_map(|drape| Some((drape.tile, drape.stacks.get(stack)?)));
        let textured = drapes.filter(|(_, drape)| drape.texture.is_some());
        textured
            .map(|(tile, drape)| {
                let mut meshes = Vec::new();
                for layer in &drape.layers {
                    layer
                        .draws
                        .visit_groups(&mut |group| meshes.extend(group.meshes().map(crate::draw::objects::Mesh::seq)));
                }
                (tile, meshes)
            })
            .collect()
    }

    /// The tile and stack of each drape that has a texture, in the cover's
    /// order.
    #[cfg(test)]
    pub(crate) fn textured(&self) -> Vec<(OverscaledTileID, usize)> {
        let stacks = |drape: &Drape| {
            let tile = drape.tile;
            let textured = drape.stacks.iter().enumerate().filter(|(_, stack)| stack.texture.is_some());
            textured.map(move |(stack, _)| (tile, stack)).collect::<Vec<_>>()
        };
        self.drapes.iter().flat_map(stacks).collect()
    }

    /// The tile and stack of each drape that the last frame drew, in the
    /// cover's order.
    #[cfg(test)]
    pub(crate) fn drawn(&self) -> Vec<(OverscaledTileID, usize)> {
        let stacks = |drape: &Drape| {
            let tile = drape.tile;
            let drawn = (drape.stacks.iter().enumerate())
                .filter(|(_, stack)| stack.updated && stack.texture.is_some() && stack.drawn.is_some());
            drawn.map(move |(stack, _)| (tile, stack)).collect::<Vec<_>>()
        };
        self.drapes.iter().flat_map(stacks).collect()
    }

    /// The tiles of the drapes and the side their drapes take.
    #[cfg(test)]
    pub(crate) fn sizes(&self) -> Vec<(OverscaledTileID, u32)> {
        self.drapes.iter().map(|drape| (drape.tile, drape.size)).collect()
    }

    /// The tile, stack, and UV transform of each drape currently sampling a
    /// retired ancestor stand-in texture, in the cover's order.
    #[cfg(test)]
    pub(crate) fn stand_ins(&self) -> Vec<(OverscaledTileID, usize, [f32; 4])> {
        self.drapes
            .iter()
            .flat_map(|drape| {
                let tile = drape.tile;
                drape
                    .stacks
                    .iter()
                    .enumerate()
                    .filter_map(move |(stack, s)| s.stand_in.as_ref().map(|&(_, coords, _)| (tile, stack, coords)))
            })
            .collect()
    }

    /// How many retired ancestor tiles are currently held for stand-ins.
    #[cfg(test)]
    pub(crate) fn retired_count(&self) -> usize {
        self.retired.len()
    }

    /// The texture and UV transform of the drape of `stack` of the terrain
    /// tile `tile`: its own texture with identity UVs, or an ancestor stand-in
    /// texture with sub-rect UVs while the tile's own drape renders; `None`
    /// where the stack draws nothing in the tile.
    pub(crate) fn texture(&self, stack: usize, tile: &OverscaledTileID) -> Option<(&Texture, [f32; 4])> {
        let drape = self.drapes.iter().find(|drape| drape.tile == *tile)?;
        let stack = drape.stacks.get(stack)?;
        if let Some((texture, _)) = &stack.texture {
            Some((texture, IDENTITY_DRAPE_COORDS))
        } else if let Some((texture, coords, _)) = &stack.stand_in {
            Some((texture, *coords))
        } else {
            None
        }
    }

    /// Makes the drapes that show the buckets in `changed`, which changed,
    /// draw again.
    pub(crate) fn mark_changed(&mut self, changed: &ChangedBuckets) {
        for drape in self.drapes.iter_mut().flat_map(|drape| &mut drape.stacks) {
            if drape.drawn.as_ref().is_some_and(|drawn| drawn.holds(changed)) {
                drape.drawn = None;
            }
        }
        for retired in &mut self.retired {
            for stack in &mut retired.stacks {
                if stack.as_ref().is_some_and(|s| s.drawn.holds(changed)) {
                    *stack = None;
                }
            }
        }
    }

    /// Makes every drape draw again: what they show changed in a way that
    /// their keys don't tell, such as the style's images, or the frame that
    /// drew them failed.
    pub(crate) fn redraw(&mut self) {
        self.repaint = DrapeRepaint::None;
        self.last_zoom_moved_at = None;
        self.retired.clear();
        for drape in self.drapes.iter_mut().flat_map(|drape| &mut drape.stacks) {
            drape.drawn = None;
            drape.stand_in = None;
        }
    }

    /// Counts in the rendering stats of `context` the drapes whose textures
    /// are made, and the bytes of their textures and of the depths, stencils
    /// and composites they draw with.
    pub(crate) fn count(&self, context: &mut Context) {
        let (mut drapes, mut bytes) = (0, 0);
        let active_textures = self
            .drapes
            .iter()
            .flat_map(|drape| &drape.stacks)
            .filter_map(|drape| drape.texture.as_ref().map(|(t, _)| t));
        let retired_textures = self
            .retired
            .iter()
            .flat_map(|retired| &retired.stacks)
            .filter_map(|stack| stack.as_ref().map(|s| &s.texture));
        for texture in active_textures.chain(retired_textures) {
            if let Some(texture) = context.texture(texture).filter(|texture| texture.gpu_texture().is_some()) {
                drapes += 1;
                bytes += texture.bytes();
            }
        }
        let depth_stencil: u64 = (self.targets.iter())
            .filter(|targets| targets.depth_stencil.is_some())
            .map(|targets| attachment_bytes(Size::new(targets.side, targets.side), DEPTH_STENCIL))
            .sum();
        let composite: u64 = self.targets.iter().map(|targets| targets.layer_composite.bytes()).sum();
        let held = bytes as u64 + depth_stencil + composite;
        let stats = &mut context.rendering_stats().terrain;
        stats.drapes = drapes;
        stats.mem_drapes = usize::try_from(held).unwrap_or(usize::MAX);
    }

    /// Makes what the drapes that draw again draw with, and uploads the GPU
    /// objects of their draws and the masks of the tiles they clip to,
    /// through `gpu`, the context of `parameters`, the frame's. The drapes
    /// of a side share what they draw with, kept while a drape's texture has
    /// that side: a depth and stencil, made once one of them draws, and a
    /// layer composite, which takes the composited draw groups of those that
    /// draw again, and drops its textures where there are none.
    pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
        let drapes = || self.drapes.iter().flat_map(|drape| &drape.stacks);
        let sides: SmallVec<[u32; 8]> =
            drapes().filter_map(|drape| drape.texture.as_ref().map(|&(_, side)| side)).collect();
        self.targets.retain(|targets| sides.contains(&targets.side));
        for &side in &sides {
            if self.targets.iter().all(|targets| targets.side != side) {
                let layer_composite = LayerComposite::default();
                self.targets.push(Targets { side, depth_stencil: None, layer_composite });
            }
        }
        let redraws_at = |drape: &StackDrape, side: u32| {
            drape.updated && drape.texture.as_ref().is_some_and(|&(_, texture_side)| texture_side == side)
        };
        for targets in self.targets.iter_mut().filter(|targets| targets.depth_stencil.is_none()) {
            if !drapes().any(|drape| redraws_at(drape, targets.side)) {
                continue;
            }
            // The drapes of the side then fail to draw.
            let size = Size::new(targets.side, targets.side);
            match parameters.context.device().attachment(gpu, "drape depth and stencil", size, DEPTH_STENCIL) {
                Ok(depth_stencil) => targets.depth_stencil = Some(depth_stencil),
                Err(error) => parameters.context.fail(format!("Making the drapes' depth and stencil failed: {error}")),
            }
        }
        for Drape { tile, transform, size, clip_masks, stacks, .. } in &mut self.drapes {
            if !stacks.iter().any(|drape| drape.updated) {
                continue;
            }
            let composite = &mut LayerComposite::default();
            let size = Size::new(*size, *size);
            let parameters = parameters.drape(transform, clip_masks, composite, size, tile.to_unwrapped());
            for drape in stacks.iter_mut().filter(|drape| drape.updated) {
                let context = &mut *parameters.context;
                for layer in &drape.layers {
                    layer.draws.upload(gpu, context);
                }
                let layers = &drape.layers;
                drape.groups = DrawGroups::of(
                    |visit| {
                        for layer in layers {
                            layer.draws.visit_groups(visit);
                        }
                    },
                    |tiles| parameters.stencil_clear_tiles(tiles),
                );
            }
            // The masks of the tiles of every stack that draws again, which
            // their passes clip to in turn.
            let mut clip_tiles: Vec<_> = (stacks.iter().filter(|drape| drape.updated))
                .flat_map(|drape| drape.groups.clip_tiles.iter().copied())
                .collect();
            clip_tiles.sort_unstable();
            clip_tiles.dedup();
            let transform = parameters.transform_params;
            parameters.clip_masks.update(gpu, parameters.context, false, &clip_tiles, |tile| {
                (transform.projection_data_for_tile(tile, false)).ubo()
            });
        }
        for targets in &mut self.targets {
            let redrawn =
                self.drapes.iter().flat_map(|drape| &drape.stacks).filter(|drape| redraws_at(drape, targets.side));
            let composited: Vec<_> = redrawn.flat_map(|drape| drape.groups.composited.iter().copied()).collect();
            let size = Size::new(targets.side, targets.side);
            targets.layer_composite.update(gpu, parameters.context, size, Some(COLOR), &composited);
        }
    }

    /// Draws each drape that draws again into its texture, through `gpu`,
    /// the context of `parameters`, the frame's, outside any pass, after
    /// the targets of its layers' draws, and then its texture's mips: its layers' opaque draws front to back, then
    /// their translucent ones back to front, over transparent texels. A
    /// drape with a layer that blends in the shader draws into the layer
    /// composite's frame texture, which is then copied into its own. A drape
    /// that fails to draw fails the frame, and draws again in the next.
    pub(crate) fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
        let formats = TargetFormats { color: Some(COLOR), depth_stencil: Some(DEPTH_STENCIL) };
        for Drape { tile, transform, clip_masks, stacks, .. } in &mut self.drapes {
            for drape in stacks.iter_mut().filter(|drape| drape.updated) {
                let StackDrape { texture: Some((texture, side)), layers, groups, drawn, key, .. } = drape else {
                    continue;
                };
                *drawn = None;
                // Without its side's depth and stencil, the upload said why.
                let Some(Targets { depth_stencil: Some(depth_stencil), layer_composite, .. }) =
                    self.targets.iter_mut().find(|targets| targets.side == *side)
                else {
                    continue;
                };
                let (depth_stencil, size) = (depth_stencil.id(), Size::new(*side, *side));
                // The targets of the layers' draws, which they sample.
                for layer in layers.iter_mut() {
                    layer.draws.render_targets(gpu, parameters);
                }
                let color = match parameters.context.create_texture(gpu, texture) {
                    Ok(color) => color,
                    Err(error) => {
                        parameters.context.fail(format!("Making a drape's texture failed: {error}"));
                        continue;
                    }
                };
                let clear = LoadOp::Clear(Rgba::new(0.0, 0.0, 0.0, 0.0));
                let frame_texture = layer_composite.frame_texture_for(&groups.composited);
                let pass = OpenPass {
                    label: "drape",
                    color: Some(ColorAttachment { texture: frame_texture.unwrap_or(color), load: clear }),
                    depth_stencil: Some(DepthStencilAttachment {
                        texture: depth_stencil,
                        depth: LoadOp::Clear(1.0),
                        stencil: LoadOp::Clear(0),
                    }),
                    size,
                    targets: formats,
                };
                let unwrapped = tile.to_unwrapped();
                let mut drape_parameters = parameters.drape(transform, clip_masks, layer_composite, size, unwrapped);
                drape_parameters.stencil_clear.clone_from(&groups.stencil_clear);
                let drawn_pass = drape_parameters.begin_pass(gpu, pass).and_then(|()| {
                    drape_parameters.depth_range_size = groups.depth_range_size();
                    drape_parameters.pass = RenderPass::OPAQUE;
                    drape_parameters.current_layer = 0;
                    for layer in layers.iter_mut().rev() {
                        layer.draws.render(gpu, &mut drape_parameters, DrawOrder::TopDown, None);
                    }
                    drape_parameters.pass = RenderPass::TRANSLUCENT;
                    drape_parameters.current_layer = (groups.count as u32).wrapping_sub(1);
                    for layer in layers.iter_mut() {
                        layer.draws.render(gpu, &mut drape_parameters, DrawOrder::BottomUp, None);
                    }
                    // A drape whose frame doesn't reach it failed, as one
                    // whose pass did.
                    let presented = match frame_texture {
                        Some(_) => {
                            let present = OpenPass {
                                label: "drape",
                                color: Some(ColorAttachment { texture: color, load: clear }),
                                depth_stencil: None,
                                size,
                                targets: TargetFormats { color: Some(COLOR), depth_stencil: None },
                            };
                            drape_parameters.present_frame(gpu, present)
                        }
                        None => Ok(()),
                    };
                    drape_parameters.end_pass(gpu).and(presented)
                });
                match drawn_pass.and_then(|()| parameters.context.generate_mipmaps(gpu, texture)) {
                    Ok(()) => {
                        *drawn = Some(std::mem::take(key));
                        parameters.context.rendering_stats().terrain.drapes_drawn += 1;
                    }
                    Err(error) => parameters.context.fail(format!("Drawing a drape failed: {error}")),
                }
            }
        }
    }
}

/// A drape's texture of `side` texels a side, made in `context`'s store,
/// mipmapped and sampled through its mips, anisotropically, clamped to its
/// edges.
fn drape_texture(context: &mut Context, side: u32) -> Texture {
    context.add_texture_with(|texture| {
        texture.set_size(Size::new(side, side));
        texture.set_format(COLOR);
        texture.set_render_target();
        texture.set_mipmapped(true);
        texture.set_sampler(SamplerState {
            filter: TextureFilterType::Linear,
            wrap_u: TextureWrapType::Clamp,
            wrap_v: TextureWrapType::Clamp,
            max_anisotropy: MAX_ANISOTROPY,
            mipmapped: true,
        });
    })
}

#[cfg(test)]
mod tests {
    use mln_style::geo::LatLng;
    use mln_style::tile_id::CanonicalTileID;
    use mln_style::types::ProjectionDefinition;

    use super::*;
    use crate::camera::transform::Transform;
    use crate::camera::{CameraOptions, ConstrainMode};
    use crate::render::terrain::{ElevationRanges, TerrainTile};

    /// A view of the globe at `zoom` over 512 by 512 pixels.
    fn globe(center: LatLng, zoom: f64) -> View {
        let mut transform = Transform::new(ConstrainMode::HeightOnly);
        transform.resize(mln_style::size::Size::new(512, 512)).unwrap();
        transform.set_projection(ProjectionDefinition::from_name("vertical-perspective").into());
        transform.jump_to(&CameraOptions { center: Some(center), zoom: Some(zoom), ..Default::default() });
        assert!(transform.view().is_globe());
        transform.view().clone()
    }

    /// On the globe, a drape draws its layers as on Mercator, so they draw as
    /// flat as on a Mercator map: its view isn't the globe's, and its tile
    /// projects through the Mercator matrix onto its texture.
    #[test]
    fn a_globe_drape_draws_on_mercator() {
        let view = globe(LatLng::new(30.0, 20.0).unwrap(), 3.0);
        let id = OverscaledTileID::new(3, 0, CanonicalTileID::new(3, 4, 3));
        let cover = TerrainCover {
            source_id: "dem".to_owned(),
            tile_size: 512,
            tiles: vec![TerrainTile { id, dem: None }],
            center: None,
            dem_tiles: Vec::new(),
            ranges: ElevationRanges::default(),
            world: mln_style::crs::WorldMapping::default(),
        };
        let mut drapes = Drapes::default();
        drapes.begin(&view, &cover, 1, (u64::MAX, 4096));
        let transform = &drapes.drapes[0].transform;
        assert!(!transform.view.is_globe());
        let tile = id.to_unwrapped();
        let projection = transform.projection_data_for_tile(&tile, false);
        let mercator = TransformParameters::for_drape(&view.mercator(), 1.0, &tile);
        assert_eq!(mercator.proj_matrix * view.mercator().tile_matrix(&tile), projection.main_matrix);
        assert_eq!(0.0, projection.projection_transition);
    }

    /// A drape is twice as wide as its tile, or as wide as the device's
    /// largest texture where that is smaller: a DEM of 512 pixels makes
    /// terrain tiles of 1024 and drapes of 2048, and one of 1024 or 2048
    /// drapes of 4096 or 8192, larger than many devices take.
    #[test]
    fn the_largest_drape_fits_the_device() {
        assert_eq!(2048, drape_size(1024, 16384));
        assert_eq!(2048, drape_size(2048, 2048));
        assert_eq!(4096, drape_size(4096, 4096));
        assert_eq!(1, drape_size(1024, 0));
    }

    /// The bytes of three tiles' two drapes each, of `sizes`, and of the
    /// depth and stencil of each side.
    fn held(sizes: [u32; 3]) -> u64 {
        held_bytes(&sizes, &[2; 3])
    }

    /// The cap counts a depth and stencil for each side the drapes have, and
    /// nothing for a tile whose drapes hold no texture.
    #[test]
    fn the_cap_counts_the_depth_and_stencil_of_each_side() {
        let side = |size: u32| attachment_bytes(Size::new(size, size), DEPTH_STENCIL);
        assert_eq!(
            4 * texture_bytes(2048) + 2 * texture_bytes(1024) + side(2048) + side(1024),
            held([2048, 2048, 1024])
        );
        assert_eq!(texture_bytes(1024) + side(1024), held_bytes(&[2048, 1024], &[0, 1]));
    }

    /// The cap lowers the largest side of three tiles' two drapes each, from
    /// 2048 texels, a step at a time, for the tiles farthest from the center
    /// first, as far as it needs, to a texel: every tile takes a side before
    /// any takes the next one down.
    #[test]
    fn the_cap_lowers_the_sides_of_the_farthest_tiles_first() {
        let cases = [
            (u64::MAX, [2048, 2048, 2048]),
            (held([2048, 2048, 1024]), [2048, 2048, 1024]),
            (held([2048, 1024, 1024]), [2048, 1024, 1024]),
            (held([2048, 1024, 1024]) - 1, [1024, 1024, 1024]),
            (held([1024, 1024, 1024]) - 1, [1024, 1024, 512]),
            (held([1024, 1024, 512]) - 1, [1024, 512, 512]),
            (held([128, 128, 128]) - 1, [128, 128, 64]),
            (0, [1, 1, 1]),
        ];
        for (cap, expected) in cases {
            let mut sizes = [2048; 3];
            cap_sizes(&mut sizes, &[2; 3], cap);
            assert_eq!(expected, sizes, "cap {cap}");
        }
    }

    #[test]
    fn ancestor_drape_coords_maps_child_subrect() {
        let tile = |z, x, y, wrap| OverscaledTileID::new(z, wrap, CanonicalTileID::new(z, x, y));
        let cases = [
            // Direct children of (2, 1, 1):
            (tile(3, 2, 2, 0), tile(2, 1, 1, 0), false, Some([0.5, 0.0, 0.0, 0.0])),
            (tile(3, 3, 2, 0), tile(2, 1, 1, 0), false, Some([0.5, 0.5, 0.0, 0.0])),
            (tile(3, 2, 3, 0), tile(2, 1, 1, 0), false, Some([0.5, 0.0, 0.5, 0.0])),
            (tile(3, 3, 3, 0), tile(2, 1, 1, 0), false, Some([0.5, 0.5, 0.5, 0.0])),
            // Grandchild two zooms deeper:
            (tile(4, 7, 5, 0), tile(2, 1, 1, 0), false, Some([0.25, 0.75, 0.25, 0.0])),
            // Different world copy: rejected on Mercator, allowed on globe:
            (tile(3, 3, 2, 1), tile(2, 1, 1, 0), false, None),
            (tile(3, 3, 2, 1), tile(2, 1, 1, 0), true, Some([0.5, 0.5, 0.0, 0.0])),
            // Same zoom or non-ancestor:
            (tile(2, 1, 1, 0), tile(2, 1, 1, 0), false, None),
            (tile(3, 0, 0, 0), tile(2, 1, 1, 0), false, None),
        ];
        for (child, parent, globe, expected) in cases {
            assert_eq!(expected, ancestor_drape_coords(child, parent, globe), "{child:?} in {parent:?} globe={globe}");
        }
    }

    #[test]
    fn tile_distance_sq_ranks_mixed_lod_and_wrapped_tiles() {
        let tile = |z, x, y, wrap| OverscaledTileID::new(z, wrap, CanonicalTileID::new(z, x, y));
        // View centered in world copy 0 at (0.52, 0.52):
        // a nearby z=14 tile beats a coarse z=12 tile farther away.
        let near_z14 = tile(14, (0.52_f64 * 16384.0) as u32, (0.52_f64 * 16384.0) as u32, 0);
        let far_z12 = tile(12, (0.60_f64 * 4096.0) as u32, (0.60_f64 * 4096.0) as u32, 0);
        assert!(tile_distance_sq(near_z14, (0.52, 0.52), false) < tile_distance_sq(far_z12, (0.52, 0.52), false));

        // On Mercator with center in world copy 1 (x = 1.1), a tile in copy 1
        // beats the same canonical tile in copy 0.
        let same_copy = tile(2, 0, 2, 1);
        let other_copy = tile(2, 0, 2, 0);
        assert!(tile_distance_sq(same_copy, (1.1, 0.6), false) < tile_distance_sq(other_copy, (1.1, 0.6), false));
    }

    #[test]
    fn scheduled_repaint_disables_zoom_deferral() {
        use std::sync::atomic::{AtomicBool, Ordering};

        use mln_style::layer::{LayerStyle, LayerTypeInfo, NoProperties, SourceKind, StyleLayerType};
        use mln_style::property::evaluation::PropertyEvaluationParameters;
        use mln_style::property::table::{PropertyTable, PropertyVisitor};
        use mln_style::time::Instant;

        use crate::layer::{EvaluateCx, Evaluation, FrameTile, Layer, LayerValues, NoTiles, PrepareCx};
        use crate::registry::RegistryBuilder;

        static PROPS: PropertyTable = PropertyTable::new(&[], &[]);

        struct ScheduledStyle;
        impl StyleLayerType for ScheduledStyle {
            const INFO: LayerTypeInfo =
                LayerTypeInfo { name: "test.drape-scheduled", source: SourceKind::None, from_json: false };
            const PROPERTIES: &'static PropertyTable = &PROPS;
            type LayoutProperties = NoProperties;
            type PaintProperties = NoProperties;
            type Extra = Arc<AtomicBool>;

            fn visit_property<V: PropertyVisitor<LayerStyle<Self>>>(_slot: usize, _visitor: V) -> Option<V::Output> {
                None
            }
        }

        struct ScheduledLayer(Arc<AtomicBool>);
        impl Layer for ScheduledLayer {
            type Style = ScheduledStyle;
            type Input = NoTiles;
            type Tile = ();

            fn new(values: &LayerValues<Self::Style>) -> Self {
                ScheduledLayer(Arc::clone(&values.style.extra))
            }

            fn evaluate(&mut self, cx: EvaluateCx<'_, Self>) -> Evaluation {
                let repaint_at =
                    self.0.load(Ordering::Relaxed).then(|| cx.time_point().unwrap() + Duration::from_millis(50));
                Evaluation { repaint_at, ..Evaluation::TRANSLUCENT }
            }

            fn prepare(&mut self, _cx: &mut PrepareCx<'_, '_, Self>, _tiles: &[FrameTile<'_, Self>], _out: &mut Draws) {
            }
        }

        let mut builder = RegistryBuilder::new();
        builder.add_layer_type::<ScheduledLayer>().unwrap();
        let registry = builder.build();
        let layer_type = registry.layer_type(ScheduledStyle::INFO.name).unwrap();

        let scheduled = Arc::new(AtomicBool::new(true));
        let mut style = LayerStyle::<ScheduledStyle>::new("scheduled".to_owned(), String::new());
        style.extra = Arc::clone(&scheduled);
        let style: Arc<dyn ErasedLayerStyle> = Arc::new(style);
        let mut render_layer = layer_type.create_render_layer(&style).unwrap();

        let key_at = |layer: &dyn RenderLayer, zoom: f64| {
            let view = globe(LatLng::new(30.0, 20.0).unwrap(), zoom);
            let id = OverscaledTileID::new(3, 0, CanonicalTileID::new(3, 4, 3));
            let cover = TerrainCover {
                source_id: "dem".to_owned(),
                tile_size: 512,
                tiles: vec![TerrainTile { id, dem: None }],
                center: None,
                dem_tiles: Vec::new(),
                ranges: ElevationRanges::default(),
                world: mln_style::crs::WorldMapping::default(),
            };
            let mut drapes = Drapes::default();
            drapes.begin(&view, &cover, 1, (u64::MAX, 4096));
            drapes.key_layer(0, layer, None, false);
            drapes.drapes[0].stacks[0].key.zoom = zoom;
            std::mem::take(&mut drapes.drapes[0].stacks[0].key)
        };

        let t0 = Instant::now();
        let mut eval_params = PropertyEvaluationParameters::new(3.0);
        eval_params.now = Some(t0);
        render_layer.evaluate(&eval_params);
        let drawn_with_deadline = key_at(&*render_layer, 3.0);
        assert!(drawn_with_deadline.has_transition);

        // When the scheduled deadline fires during an active zoom gesture and
        // the animation finishes (returning repaint_at: None), the cached drape
        // must not stand in for the updated evaluation.
        scheduled.store(false, Ordering::Relaxed);
        eval_params.now = Some(t0 + Duration::from_millis(50));
        render_layer.evaluate(&eval_params);
        let after_deadline = key_at(&*render_layer, 3.05);
        assert!(!after_deadline.has_transition);
        assert!(!after_deadline.same_except_zoom(&drawn_with_deadline));

        // Once redrawn in the idle state, normal zoom deferral resumes.
        let idle_next = key_at(&*render_layer, 3.10);
        assert!(idle_next.same_except_zoom(&after_deadline));
    }
}