mln-rs-plugin 0.0.23

Safe Rust SDK for writing MapLibre layer, source, and expression plugins
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
//! Safe, host-agnostic traits, descriptors, contexts, and RAII GPU handles for
//! layer plugins.

use core::any::Any;
use core::marker::PhantomData;
use std::borrow::Cow;
use std::sync::Arc;

use crate::backend::{
    AfterGpuHandle, AfterGpuRefBackend, DrawGroupBackend, DrawsBackend, EvaluateCxBackend, EvaluatedLayerBackend,
    FrameBackend, FrameQueryCxMutBackend, FrameQueryCxReadBackend, GroundHeightsHandle, HitCxBackend, HostBackend,
    IndexBufferHandle, MeshHandle, PaintAttributesHandle, PrepareCxMutBackend, PrepareCxReadBackend, ResourcesBackend,
    TargetHandle, TextureHandle, TileBackend, TileBuildCxBackend, TileGeometryBackend, TileGeometryBuilderBackend,
    UpdateCxMutBackend, UpdateCxReadBackend, VertexBufferHandle, ViewBackend,
};
use crate::error::Result;
use crate::program::{AttributeFormat, Program, ProgramDesc};
use crate::types::{
    Alignment, CollisionShape, Color, ColorMode, CullFaceMode, DrawMode, DrawOptions, DrawRange, FeatureType,
    FrameInfo, GpuEnd, LatLng, LayerInput, LendAt, LendFrame, LendStage, MapMode, PointI16, ProjectedPoint,
    ProjectionUbo, ProjectionVariant, RenderPasses, SamplerState, ScreenPoint, TerrainMode, TextureChannelType,
    TextureFormat, TileChanges, TileId, TileOrder, TileTransform, Vec2, ViewInfo,
};

// ---------------------------------------------------------------------------
// Host handle for one-time plugin initialization
// ---------------------------------------------------------------------------

/// Borrowed host handle passed to [`LayerPlugin::init`] when a plugin is
/// registered, allowing one-time creation of shared resources such as shader
/// [`Program`]s.
pub struct Host<'a> {
    backend: &'a dyn HostBackend,
}

impl<'a> Host<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a dyn HostBackend) -> Self {
        Self { backend }
    }

    /// Registers a multi-backend shader program with the host.
    pub fn create_program(&self, desc: &ProgramDesc<'_>) -> Result<Program> {
        self.backend.create_program(desc)
    }

    /// Creates a reusable ground-height sampler cache.
    pub fn create_ground_heights(&self) -> Result<GroundHeights> {
        self.backend.create_ground_heights()
    }
}

// ---------------------------------------------------------------------------
// Schema descriptors
// ---------------------------------------------------------------------------

/// Whether a custom property belongs to paint or layout.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PropertyScope {
    Paint,
    Layout,
}

/// Typed default value for a custom style property.
#[derive(Clone, Copy, Debug)]
pub enum PropertyDefault<'a> {
    Float(f32),
    Bool(bool),
    Color(Color),
    Vec2(Vec2),
    LatLng(LatLng),
    RotationDegrees(f32),
    String(&'a str),
    Enum { variants: &'a [&'a str], default_index: u32 },
}

/// Descriptor for one custom paint or layout property.
#[derive(Clone, Copy, Debug)]
pub struct PropertyDesc<'a> {
    pub name: &'a str,
    pub scope: PropertyScope,
    pub data_driven: bool,
    pub paint_lays_out: bool,
    pub attribute_name: &'a str,
    pub default: PropertyDefault<'a>,
}

impl<'a> PropertyDesc<'a> {
    /// Constant (non-data-driven) paint property.
    #[must_use]
    pub const fn paint(name: &'a str, default: PropertyDefault<'a>) -> Self {
        Self {
            name,
            scope: PropertyScope::Paint,
            data_driven: false,
            paint_lays_out: false,
            attribute_name: "",
            default,
        }
    }

    /// Data-driven paint property backed by a vertex attribute.
    #[must_use]
    pub const fn paint_data_driven(name: &'a str, attribute_name: &'a str, default: PropertyDefault<'a>) -> Self {
        Self { name, scope: PropertyScope::Paint, data_driven: true, paint_lays_out: false, attribute_name, default }
    }

    /// Layout property.
    #[must_use]
    pub const fn layout(name: &'a str, default: PropertyDefault<'a>) -> Self {
        Self {
            name,
            scope: PropertyScope::Layout,
            data_driven: false,
            paint_lays_out: false,
            attribute_name: "",
            default,
        }
    }
}

/// Static descriptor for a custom layer type returned by [`LayerPlugin::desc`].
#[derive(Clone, Debug)]
pub struct LayerDesc<'a> {
    pub name: &'a str,
    pub input: LayerInput,
    pub tile_order: TileOrder,
    pub terrain_mode: TerrainMode,
    pub is_volume: bool,
    pub properties: &'a [PropertyDesc<'a>],
}

/// Output of [`LayerInstance::evaluate`].
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Evaluation {
    pub passes: RenderPasses,
    pub solid_color: Option<Color>,
    pub drapes_by_bearing: bool,
    pub drapes_by_zoom: bool,
    pub needs_repaint: bool,
    pub repaint_after_ns: Option<u64>,
    /// Whether the layer reads the shapes the frame's placement tested
    /// ([`Frame::collision_shapes`]). Placement records them only while a
    /// layer the frame draws reads them.
    pub reads_collision_shapes: bool,
}

impl Evaluation {
    #[must_use]
    pub const fn passes(passes: RenderPasses) -> Self {
        Self {
            passes,
            solid_color: None,
            drapes_by_bearing: false,
            drapes_by_zoom: false,
            needs_repaint: false,
            repaint_after_ns: None,
            reads_collision_shapes: false,
        }
    }
}

/// Outcome of a tile-feature hit test ([`LayerInstance::hit`]).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Hit {
    #[default]
    Miss,
    InPlace,
    AtDistance(f64),
}

// ---------------------------------------------------------------------------
// Layer blend & compositing
// ---------------------------------------------------------------------------

/// Compositing blend mode for a draw group.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LayerBlend {
    #[default]
    Normal,
    Multiply,
    Screen,
    Overlay,
    Darken,
    Lighten,
    ColorDodge,
    ColorBurn,
    HardLight,
    SoftLight,
    Difference,
    Exclusion,
    Hue,
    Saturation,
    Color,
    Luminosity,
    PlusLighter,
}

/// Compositing configuration for a [`DrawGroup`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Composite {
    pub opacity: f32,
    pub blend: LayerBlend,
    pub frame_depth: bool,
}

// ---------------------------------------------------------------------------
// RAII GPU handles
// ---------------------------------------------------------------------------

/// Owned GPU vertex buffer handle.
#[derive(Debug)]
pub struct VertexBuffer {
    inner: Box<dyn VertexBufferHandle>,
}

impl VertexBuffer {
    #[doc(hidden)]
    #[must_use]
    pub fn from_handle(inner: Box<dyn VertexBufferHandle>) -> Self {
        Self { inner }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn handle(&self) -> &dyn VertexBufferHandle {
        &*self.inner
    }
}

/// Owned GPU index buffer handle.
#[derive(Debug)]
pub struct IndexBuffer {
    inner: Box<dyn IndexBufferHandle>,
}

impl IndexBuffer {
    #[doc(hidden)]
    #[must_use]
    pub fn from_handle(inner: Box<dyn IndexBufferHandle>) -> Self {
        Self { inner }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn handle(&self) -> &dyn IndexBufferHandle {
        &*self.inner
    }
}

/// Owned GPU texture handle.
#[derive(Debug)]
pub struct Texture {
    inner: Box<dyn TextureHandle>,
}

impl Texture {
    #[doc(hidden)]
    #[must_use]
    pub fn from_handle(inner: Box<dyn TextureHandle>) -> Self {
        Self { inner }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn handle(&self) -> &dyn TextureHandle {
        &*self.inner
    }
}

/// Owned offscreen render target handle.
#[derive(Debug)]
pub struct Target {
    inner: Box<dyn TargetHandle>,
}

impl Target {
    #[doc(hidden)]
    #[must_use]
    pub fn from_handle(inner: Box<dyn TargetHandle>) -> Self {
        Self { inner }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn handle(&self) -> &dyn TargetHandle {
        &*self.inner
    }

    /// Returns a handle to the color texture backed by this render target.
    #[must_use]
    pub fn texture(&self) -> Option<Texture> {
        self.inner.texture()
    }
}

/// Owned paint-attribute binder snapshot for a tile/layer.
#[derive(Debug)]
pub struct PaintAttributes {
    inner: Box<dyn PaintAttributesHandle>,
}

impl PaintAttributes {
    #[doc(hidden)]
    #[must_use]
    pub fn from_handle(inner: Box<dyn PaintAttributesHandle>) -> Self {
        Self { inner }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn handle(&self) -> &dyn PaintAttributesHandle {
        &*self.inner
    }
}

/// Owned GPU mesh handle.
#[derive(Debug)]
pub struct Mesh {
    inner: Box<dyn MeshHandle>,
}

impl Mesh {
    #[doc(hidden)]
    #[must_use]
    pub fn from_handle(inner: Box<dyn MeshHandle>) -> Self {
        Self { inner }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn handle(&self) -> &dyn MeshHandle {
        &*self.inner
    }

    /// Monotonic sequence number suitable for [`DrawOptions::order`].
    #[must_use]
    pub fn seq(&self) -> i64 {
        self.inner.seq()
    }

    /// Binds or clears a texture at `slot` on this mesh.
    pub fn set_texture(&self, res: &mut Resources<'_>, slot: u32, texture: Option<&Texture>) -> Result<()> {
        res.backend.mesh_set_texture(self, slot, texture)
    }

    /// Overrides the sampler state at `slot` on this mesh.
    pub fn set_sampler(&self, res: &mut Resources<'_>, slot: u32, sampler: SamplerState) -> Result<()> {
        res.backend.mesh_set_sampler(self, slot, sampler)
    }

    /// Updates paint attributes on this mesh after paint property changes.
    pub fn set_paint(&self, res: &mut Resources<'_>, paint: &PaintAttributes) -> Result<()> {
        res.backend.mesh_set_paint(self, paint)
    }

    /// Rebinds a vertex stream on this mesh.
    pub fn bind_vertices(&self, res: &mut Resources<'_>, binding: &VertexBinding<'_>) -> Result<()> {
        res.backend.mesh_bind_vertices(self, binding)
    }
}

/// Owned ground-height sampler cache for standing geometry layers.
#[derive(Debug)]
pub struct GroundHeights {
    inner: Box<dyn GroundHeightsHandle>,
}

impl GroundHeights {
    #[doc(hidden)]
    #[must_use]
    pub fn from_handle(inner: Box<dyn GroundHeightsHandle>) -> Self {
        Self { inner }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn handle_mut(&mut self) -> &mut dyn GroundHeightsHandle {
        &mut *self.inner
    }

    /// Samples terrain heights at `centers` in `tile_id` and binds them to
    /// `attribute_name` on `mesh` when terrain data changes.
    pub fn apply(
        &mut self,
        mesh: &Mesh,
        res: &mut Resources<'_>,
        frame: Frame<'_>,
        tile_id: TileId,
        attribute_name: &str,
        centers: &[PointI16],
    ) -> Result<()> {
        res.backend.apply_ground_heights(self, mesh, frame, tile_id, attribute_name, centers)
    }
}

// ---------------------------------------------------------------------------
// Mesh descriptors
// ---------------------------------------------------------------------------

/// Attribute entry inside a [`VertexBinding`].
#[derive(Clone, Copy, Debug)]
pub struct VertexAttribute<'a> {
    pub name: &'a str,
    pub format: AttributeFormat,
    pub offset: u32,
}

impl<'a> VertexAttribute<'a> {
    #[must_use]
    pub const fn new(name: &'a str, format: AttributeFormat, offset: u32) -> Self {
        Self { name, format, offset }
    }
}

/// Vertex buffer stream binding passed to [`MeshDesc`] or [`Mesh::bind_vertices`].
#[derive(Clone, Copy, Debug)]
pub struct VertexBinding<'a> {
    pub buffer: &'a VertexBuffer,
    pub stride: u32,
    pub first_vertex: u32,
    pub attributes: &'a [VertexAttribute<'a>],
}

/// Descriptor passed to [`Resources::create_mesh`].
pub struct MeshDesc<'a> {
    pub program: &'a Program,
    pub projection_variant: ProjectionVariant,
    pub extra_defines: &'a [&'a str],
    pub paint_attributes: Option<&'a PaintAttributes>,
    pub color_mode: ColorMode,
    pub cull_face_mode: CullFaceMode,
    pub draw_mode: DrawMode,
    pub vertex_bindings: &'a [VertexBinding<'a>],
    pub vertex_count: usize,
    pub instance_bindings: &'a [VertexBinding<'a>],
    pub indexes: &'a IndexBuffer,
    pub ranges: &'a [DrawRange],
    pub textures: &'a [Option<&'a Texture>],
}

// ---------------------------------------------------------------------------
// Borrowed host contexts
// ---------------------------------------------------------------------------

/// Borrowed view of an evaluated custom style layer.
#[derive(Clone, Copy)]
pub struct EvaluatedLayer<'a> {
    backend: &'a dyn EvaluatedLayerBackend,
}

impl<'a> EvaluatedLayer<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a dyn EvaluatedLayerBackend) -> Self {
        Self { backend }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn backend(&self) -> &'a dyn EvaluatedLayerBackend {
        self.backend
    }

    /// Layer ID from the style.
    #[must_use]
    pub fn id(&self) -> &'a str {
        self.backend.id()
    }

    /// Returns true if paint property `slot` has a constant (non-data-driven) value.
    #[must_use]
    pub fn paint_is_constant(&self, slot: u32) -> bool {
        self.backend.paint_is_constant(slot)
    }

    /// Reads a constant float paint property.
    pub fn paint_f32(&self, slot: u32) -> Result<f32> {
        self.backend.paint_f32(slot)
    }

    /// Reads a float paint property if constant, or returns `fallback` when data-driven.
    pub fn paint_f32_constant_or(&self, slot: u32, fallback: f32) -> Result<f32> {
        self.backend.paint_f32_constant_or(slot, fallback)
    }

    /// Reads a constant bool paint property.
    pub fn paint_bool(&self, slot: u32) -> Result<bool> {
        self.backend.paint_bool(slot)
    }

    /// Reads a constant color paint property.
    pub fn paint_color(&self, slot: u32) -> Result<Color> {
        self.backend.paint_color(slot)
    }

    /// Reads a color paint property if constant, or returns `fallback` when data-driven.
    pub fn paint_color_constant_or(&self, slot: u32, fallback: Color) -> Result<Color> {
        self.backend.paint_color_constant_or(slot, fallback)
    }

    /// Reads a constant 2-vector paint property.
    pub fn paint_vec2(&self, slot: u32) -> Result<Vec2> {
        self.backend.paint_vec2(slot)
    }

    /// Reads a constant geographic position paint property.
    pub fn paint_lat_lng(&self, slot: u32) -> Result<LatLng> {
        self.backend.paint_lat_lng(slot)
    }

    /// Reads a constant rotation paint property in degrees.
    pub fn paint_rotation_degrees(&self, slot: u32) -> Result<f32> {
        self.backend.paint_rotation_degrees(slot)
    }

    /// Reads a constant string (or enum label) paint property.
    pub fn paint_str(&self, slot: u32) -> Result<&'a str> {
        self.backend.paint_str(slot)
    }

    /// Reads a constant enum paint property as its 0-based variant index.
    pub fn paint_enum(&self, slot: u32) -> Result<u32> {
        self.backend.paint_enum(slot)
    }
}

/// Borrowed context for [`LayerInstance::evaluate`].
#[derive(Clone, Copy)]
pub struct EvaluateCx<'a> {
    backend: &'a dyn EvaluateCxBackend,
}

impl<'a> EvaluateCx<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a dyn EvaluateCxBackend) -> Self {
        Self { backend }
    }

    #[must_use]
    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
        self.backend.evaluated()
    }

    /// Current frame clock offset in signed nanoseconds relative to the host's
    /// process epoch, if a frame clock is active.
    #[must_use]
    pub fn time_point_ns(&self) -> Option<i64> {
        self.backend.time_point_ns()
    }
}

/// Borrowed context for [`LayerInstance::update`].
pub struct UpdateCx<'a> {
    ro: &'a dyn UpdateCxReadBackend,
    rw: &'a mut dyn UpdateCxMutBackend,
}

impl<'a> UpdateCx<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backends(ro: &'a dyn UpdateCxReadBackend, rw: &'a mut dyn UpdateCxMutBackend) -> Self {
        Self { ro, rw }
    }

    #[must_use]
    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
        self.ro.evaluated()
    }

    #[must_use]
    pub fn source_max_zoom(&self) -> Option<u8> {
        self.ro.source_max_zoom()
    }

    #[must_use]
    pub fn tile_count(&self) -> usize {
        self.ro.tile_count()
    }

    #[must_use]
    pub fn tile(&self, index: usize) -> Option<Tile<'a>> {
        self.ro.tile(index)
    }

    pub fn pick_tiles(&mut self, tiles: &[TileId]) -> Result<()> {
        self.rw.pick_tiles(tiles)
    }
}

/// Borrowed context for [`LayerInstance::create_tile_resources`].
pub struct TileCx<'a> {
    evaluated: EvaluatedLayer<'a>,
    projection_variant: ProjectionVariant,
    frame: Frame<'a>,
    tile: Tile<'a>,
    resources: &'a mut dyn ResourcesBackend,
}

impl<'a> TileCx<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn new(
        evaluated: EvaluatedLayer<'a>,
        projection_variant: ProjectionVariant,
        frame: Frame<'a>,
        tile: Tile<'a>,
        resources: &'a mut dyn ResourcesBackend,
    ) -> Self {
        Self { evaluated, projection_variant, frame, tile, resources }
    }

    #[must_use]
    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
        self.evaluated
    }

    #[must_use]
    pub fn projection_variant(&self) -> ProjectionVariant {
        self.projection_variant
    }

    #[must_use]
    pub fn frame(&self) -> Frame<'a> {
        self.frame
    }

    #[must_use]
    pub fn tile(&self) -> Tile<'a> {
        self.tile
    }

    #[must_use]
    pub fn resources(&mut self) -> Resources<'_> {
        Resources::from_backend(self.resources)
    }
}

/// Borrowed context for [`LayerInstance::prepare`].
pub struct PrepareCx<'a, T: 'static> {
    evaluated: EvaluatedLayer<'a>,
    frame: Frame<'a>,
    projection_variant: ProjectionVariant,
    ro: &'a dyn PrepareCxReadBackend,
    rw: &'a mut dyn PrepareCxMutBackend,
    _marker: PhantomData<*mut T>,
}

impl<'a, T: 'static> PrepareCx<'a, T> {
    #[doc(hidden)]
    #[must_use]
    pub fn new(
        evaluated: EvaluatedLayer<'a>,
        frame: Frame<'a>,
        projection_variant: ProjectionVariant,
        ro: &'a dyn PrepareCxReadBackend,
        rw: &'a mut dyn PrepareCxMutBackend,
    ) -> Self {
        Self { evaluated, frame, projection_variant, ro, rw, _marker: PhantomData }
    }

    #[must_use]
    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
        self.evaluated
    }

    #[must_use]
    pub fn frame(&self) -> Frame<'a> {
        self.frame
    }

    #[must_use]
    pub fn projection_variant(&self) -> ProjectionVariant {
        self.projection_variant
    }

    #[must_use]
    pub fn tile_count(&self) -> usize {
        self.ro.tile_count()
    }

    #[must_use]
    pub fn tile(&self, index: usize) -> Option<Tile<'a>> {
        self.ro.tile(index)
    }

    pub fn tiles(&self) -> impl Iterator<Item = Tile<'a>> + '_ {
        (0..self.tile_count()).filter_map(|i| self.tile(i))
    }

    #[must_use]
    pub fn resources(&mut self) -> Resources<'_> {
        self.rw.resources()
    }

    /// Mutably borrows the tile resources for `tile_id` together with [`Resources`].
    #[must_use]
    pub fn tile_resources_and_allocator(&mut self, tile_id: TileId) -> (Option<&mut T>, Resources<'_>) {
        let (slot, res) = self.rw.tile_resources_and_allocator(tile_id);
        (slot.and_then(<dyn Any>::downcast_mut::<T>), res)
    }

    #[must_use]
    pub fn tile_resources_mut(&mut self, tile_id: TileId) -> Option<&mut T> {
        self.rw.tile_resources_mut(tile_id).and_then(<dyn Any>::downcast_mut::<T>)
    }

    #[must_use]
    pub fn take_tile_changes(&mut self, tile_id: TileId) -> TileChanges {
        self.rw.take_tile_changes(tile_id)
    }

    #[must_use]
    pub fn picked_tiles(&self) -> Vec<TileId> {
        self.ro.picked_tiles()
    }

    #[must_use]
    pub fn read_shared_target(&mut self, name: &str) -> Option<Texture> {
        self.rw.read_shared_target(name)
    }
}

/// Borrowed raster pixel info for a raster tile.
#[derive(Clone, Copy, Debug)]
pub struct RasterTileInfo<'a> {
    pub image_id: u64,
    pub width: u32,
    pub height: u32,
    pub pixels: &'a [u8],
}

/// Borrowed tile handle valid during `update`, `create_tile_resources`, and `prepare`.
#[derive(Clone, Copy)]
pub struct Tile<'a> {
    backend: &'a dyn TileBackend,
}

impl<'a> Tile<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a dyn TileBackend) -> Self {
        Self { backend }
    }

    #[must_use]
    pub fn id(&self) -> TileId {
        self.backend.id()
    }

    #[must_use]
    pub fn draw_id(&self) -> TileId {
        self.backend.draw_id()
    }

    #[must_use]
    pub fn render_passes(&self) -> RenderPasses {
        self.backend.render_passes()
    }

    #[must_use]
    pub fn has_data_for_pass(&self, pass: RenderPasses) -> bool {
        self.backend.has_data_for_pass(pass)
    }

    #[must_use]
    pub fn geometry(&self) -> Option<TileGeometry<'a>> {
        self.backend.geometry()
    }

    #[must_use]
    pub fn geometry_vertices(&self, stream_index: usize) -> Option<VertexBuffer> {
        self.backend.geometry_vertices(stream_index)
    }

    #[must_use]
    pub fn geometry_indexes(&self, stream_index: usize) -> Option<IndexBuffer> {
        self.backend.geometry_indexes(stream_index)
    }

    #[must_use]
    pub fn paint_attributes(&self, res: &mut Resources<'_>, evaluated: EvaluatedLayer<'_>) -> Option<PaintAttributes> {
        self.backend.paint_attributes(res, evaluated)
    }

    #[must_use]
    pub fn raster_info(&self) -> Option<RasterTileInfo<'a>> {
        self.backend.raster_info()
    }
}

/// Borrowed worker-built tile geometry handle.
#[derive(Clone, Copy)]
pub struct TileGeometry<'a> {
    backend: &'a dyn TileGeometryBackend,
}

impl<'a> TileGeometry<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a dyn TileGeometryBackend) -> Self {
        Self { backend }
    }

    #[must_use]
    pub fn vertex_stream_count(&self) -> usize {
        self.backend.vertex_stream_count()
    }

    #[must_use]
    pub fn vertex_count(&self, stream_index: usize) -> usize {
        self.backend.vertex_count(stream_index)
    }

    #[must_use]
    pub fn vertex_stride(&self, stream_index: usize) -> u32 {
        self.backend.vertex_stride(stream_index)
    }

    #[must_use]
    pub fn index_stream_count(&self) -> usize {
        self.backend.index_stream_count()
    }

    #[must_use]
    pub fn index_count(&self, stream_index: usize) -> usize {
        self.backend.index_count(stream_index)
    }

    #[must_use]
    pub fn draw_ranges(&self) -> Cow<'a, [DrawRange]> {
        self.backend.draw_ranges()
    }

    #[must_use]
    pub fn metadata(&self) -> &'a [u8] {
        self.backend.metadata()
    }

    #[must_use]
    pub fn max_elevation(&self) -> f32 {
        self.backend.max_elevation()
    }

    #[must_use]
    pub fn binder_interpolation_factor(&self, layer_id: &str, paint_slot: u32, zoom: f32) -> f32 {
        self.backend.binder_interpolation_factor(layer_id, paint_slot, zoom)
    }

    #[must_use]
    pub fn binder_statistics_max_f32(&self, layer_id: &str, paint_slot: u32) -> Option<f32> {
        self.backend.binder_statistics_max_f32(layer_id, paint_slot)
    }
}

/// Information about the currently loaded feature inside [`TileBuildCx`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LoadedFeatureInfo {
    pub feature_index: usize,
    pub feature_type: FeatureType,
    pub ring_count: usize,
}

/// Tile-worker layout context passed to [`LayerPlugin::build_tile_geometry`].
pub struct TileBuildCx<'a> {
    backend: &'a mut dyn TileBuildCxBackend,
}

impl<'a> TileBuildCx<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a mut dyn TileBuildCxBackend) -> Self {
        Self { backend }
    }

    #[must_use]
    pub fn tile_id(&self) -> TileId {
        self.backend.tile_id()
    }

    /// Tile layout zoom level (`tile_id().overscaled_z as f64`).
    #[must_use]
    pub fn zoom(&self) -> f64 {
        self.backend.zoom()
    }

    #[must_use]
    pub fn mode(&self) -> MapMode {
        self.backend.mode()
    }

    #[must_use]
    pub fn pixel_ratio(&self) -> f32 {
        self.backend.pixel_ratio()
    }

    #[must_use]
    pub fn first_load(&self) -> bool {
        self.backend.first_load()
    }

    #[must_use]
    pub fn layer_count(&self) -> usize {
        self.backend.layer_count()
    }

    #[must_use]
    pub fn layer(&self, index: usize) -> Option<EvaluatedLayer<'_>> {
        self.backend.layer(index)
    }

    pub fn eval_layout_f32(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<f32> {
        self.backend.eval_layout_f32(layer_index, layout_slot, for_current_feature)
    }

    pub fn eval_layout_bool(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<bool> {
        self.backend.eval_layout_bool(layer_index, layout_slot, for_current_feature)
    }

    pub fn eval_layout_color(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<Color> {
        self.backend.eval_layout_color(layer_index, layout_slot, for_current_feature)
    }

    pub fn eval_layout_vec2(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<Vec2> {
        self.backend.eval_layout_vec2(layer_index, layout_slot, for_current_feature)
    }

    pub fn eval_layout_lat_lng(
        &self,
        layer_index: usize,
        layout_slot: u32,
        for_current_feature: bool,
    ) -> Result<LatLng> {
        self.backend.eval_layout_lat_lng(layer_index, layout_slot, for_current_feature)
    }

    pub fn eval_layout_rotation_degrees(
        &self,
        layer_index: usize,
        layout_slot: u32,
        for_current_feature: bool,
    ) -> Result<f32> {
        self.backend.eval_layout_rotation_degrees(layer_index, layout_slot, for_current_feature)
    }

    pub fn eval_layout_str(&mut self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<&str> {
        self.backend.eval_layout_str(layer_index, layout_slot, for_current_feature)
    }

    pub fn eval_layout_enum(&self, layer_index: usize, layout_slot: u32, for_current_feature: bool) -> Result<u32> {
        self.backend.eval_layout_enum(layer_index, layout_slot, for_current_feature)
    }

    #[must_use]
    pub fn feature_count(&self) -> usize {
        self.backend.feature_count()
    }

    pub fn load_feature(&mut self, selected_index: usize) -> Result<LoadedFeatureInfo> {
        self.backend.load_feature(selected_index)
    }

    #[must_use]
    pub fn feature_ring(&self, ring_index: usize) -> Option<Cow<'_, [PointI16]>> {
        self.backend.feature_ring(ring_index)
    }

    pub fn populate_binders(&mut self, vertex_count: usize) -> Result<()> {
        self.backend.populate_binders(vertex_count)
    }

    pub fn index_current_feature(&mut self) -> Result<()> {
        self.backend.index_current_feature()
    }
}

/// Output builder passed to [`LayerPlugin::build_tile_geometry`].
pub struct TileGeometryBuilder<'a> {
    backend: &'a mut dyn TileGeometryBuilderBackend,
}

impl<'a> TileGeometryBuilder<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a mut dyn TileGeometryBuilderBackend) -> Self {
        Self { backend }
    }

    pub fn add_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> Result<usize> {
        self.backend.add_vertices(bytes, vertex_count, stride)
    }

    pub fn add_indexes(&mut self, indexes: &[u16]) -> Result<usize> {
        self.backend.add_indexes(indexes)
    }

    pub fn add_draw_range(&mut self, range: DrawRange) -> Result<()> {
        self.backend.add_draw_range(range)
    }

    pub fn set_metadata(&mut self, bytes: &[u8]) -> Result<()> {
        self.backend.set_metadata(bytes)
    }

    pub fn set_max_elevation(&mut self, max_elevation: f32) -> Result<()> {
        self.backend.set_max_elevation(max_elevation)
    }
}

/// Borrowed per-frame read-only state (viewport, ground, tile projection).
#[derive(Clone, Copy)]
pub struct Frame<'a> {
    backend: &'a dyn FrameBackend,
}

impl<'a> Frame<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a dyn FrameBackend) -> Self {
        Self { backend }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn backend(&self) -> &'a dyn FrameBackend {
        self.backend
    }

    #[must_use]
    pub fn info(&self) -> FrameInfo {
        self.backend.info()
    }

    #[must_use]
    pub fn view(&self) -> View<'a> {
        self.backend.view()
    }

    pub fn tile_projection(&self, tile_id: TileId, transform: TileTransform) -> Result<ProjectionUbo> {
        self.backend.tile_projection(tile_id, transform)
    }

    #[must_use]
    pub fn ground_height(&self, tile_id: TileId, x: f32, y: f32) -> f32 {
        self.backend.ground_height(tile_id, x, y)
    }

    #[must_use]
    pub fn ground_depth_texture(&self) -> Option<Texture> {
        self.backend.ground_depth_texture()
    }

    /// The shapes the frame's placement tested for its labels and icons, in
    /// the order it tested them. Empty unless a layer the frame draws reads
    /// them ([`Evaluation::reads_collision_shapes`]).
    pub fn collision_shapes(&self) -> impl ExactSizeIterator<Item = CollisionShape> + 'a {
        let backend = self.backend;
        (0..backend.collision_shape_count()).map(move |index| backend.collision_shape(index).unwrap_or_default())
    }
}

/// Borrowed camera/projection view handle.
#[derive(Clone, Copy)]
pub struct View<'a> {
    backend: &'a dyn ViewBackend,
}

impl<'a> View<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a dyn ViewBackend) -> Self {
        Self { backend }
    }

    #[must_use]
    pub fn info(&self) -> ViewInfo {
        self.backend.info()
    }

    pub fn world_from_lat_lng(&self, lat_lng: LatLng) -> Result<(f64, f64)> {
        self.backend.world_from_lat_lng(lat_lng)
    }

    pub fn lat_lng_near_center(&self, lat_lng: LatLng) -> Result<LatLng> {
        self.backend.lat_lng_near_center(lat_lng)
    }

    #[must_use]
    pub fn ground_meters_per_world_unit_at(&self, lat_lng: LatLng) -> f64 {
        self.backend.ground_meters_per_world_unit_at(lat_lng)
    }

    pub fn world_copies(&self) -> Result<Vec<i16>> {
        self.backend.world_copies()
    }

    pub fn project_tile_point(&self, tile_id: TileId, x: f64, y: f64, elevation_m: f64) -> Result<ProjectedPoint> {
        self.backend.project_tile_point(tile_id, x, y, elevation_m)
    }

    #[must_use]
    pub fn map_aligned_scale_at(&self, tile_id: TileId, x: f64, y: f64) -> f64 {
        self.backend.map_aligned_scale_at(tile_id, x, y)
    }

    #[must_use]
    pub fn globe_extrude_scale(&self, tile_id: TileId) -> f32 {
        self.backend.globe_extrude_scale(tile_id)
    }

    pub fn tile_unit_translation(&self, tile_id: TileId, translate: Vec2, anchor: Alignment) -> Result<Vec2> {
        self.backend.tile_unit_translation(tile_id, translate, anchor)
    }
}

/// Borrowed GPU resource allocator valid during `create_tile_resources` and `prepare`.
pub struct Resources<'a> {
    backend: &'a mut dyn ResourcesBackend,
}

impl<'a> Resources<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a mut dyn ResourcesBackend) -> Self {
        Self { backend }
    }

    #[doc(hidden)]
    #[must_use]
    pub fn backend_mut(&mut self) -> &mut dyn ResourcesBackend {
        self.backend
    }

    pub fn create_program(&mut self, desc: &ProgramDesc<'_>) -> Result<Program> {
        self.backend.create_program(desc)
    }

    pub fn create_ground_heights(&mut self) -> Result<GroundHeights> {
        self.backend.create_ground_heights()
    }

    pub fn create_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> Result<VertexBuffer> {
        self.backend.create_vertices(bytes, vertex_count, stride)
    }

    pub fn create_dynamic_vertices(&mut self, bytes: &[u8], vertex_count: usize, stride: u32) -> Result<VertexBuffer> {
        self.backend.create_dynamic_vertices(bytes, vertex_count, stride)
    }

    pub fn update_vertices(&mut self, buffer: &VertexBuffer, bytes: &[u8]) -> bool {
        self.backend.update_vertices(buffer, bytes)
    }

    pub fn create_indexes(&mut self, indexes: &[u16]) -> Result<IndexBuffer> {
        self.backend.create_indexes(indexes)
    }

    pub fn quad_indexes(&mut self) -> Result<IndexBuffer> {
        self.backend.quad_indexes()
    }

    pub fn create_texture(&mut self, format: TextureFormat, sampler: SamplerState) -> Result<Texture> {
        self.backend.create_texture(format, sampler)
    }

    pub fn write_texture(&mut self, texture: &Texture, data: &[u8], width: u32, height: u32) -> Result<()> {
        self.backend.write_texture(texture, data, width, height)
    }

    pub fn create_target(
        &mut self,
        width: u32,
        height: u32,
        channel_type: TextureChannelType,
        clear_color: Color,
    ) -> Result<Target> {
        self.backend.create_target(width, height, channel_type, clear_color)
    }

    pub fn create_mesh(&mut self, desc: &MeshDesc<'_>) -> Result<Mesh> {
        self.backend.create_mesh(desc)
    }
}

/// Borrowed draw collector passed to [`LayerInstance::prepare`].
pub struct Draws<'a> {
    backend: &'a mut dyn DrawsBackend,
}

impl<'a> Draws<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a mut dyn DrawsBackend) -> Self {
        Self { backend }
    }

    /// Returns the main draw group targeting the map framebuffer.
    #[must_use]
    pub fn main(&mut self) -> DrawGroup<'_> {
        self.backend.main()
    }

    /// Returns a draw group targeting an offscreen [`Target`].
    #[must_use]
    pub fn target(&mut self, target: &Target) -> DrawGroup<'_> {
        self.backend.target(target)
    }

    /// Schedules a raw backend GPU command lending callback ([`LayerInstance::lend`])
    /// for this frame at stage `at`.
    pub fn lend(&mut self, at: LendAt) -> Result<()> {
        self.backend.lend(at)
    }
}

/// Borrowed draw group for pushing draws and uniform blocks.
pub struct DrawGroup<'a> {
    backend: &'a mut dyn DrawGroupBackend,
}

impl<'a> DrawGroup<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a mut dyn DrawGroupBackend) -> Self {
        Self { backend }
    }

    pub fn push(&mut self, mesh: &Mesh, options: DrawOptions, blocks: &[&[u8]]) -> Result<()> {
        self.backend.push(mesh, options, blocks)
    }

    pub fn push_at(
        &mut self,
        mesh: &Mesh,
        tile_id: TileId,
        projection: &ProjectionUbo,
        options: DrawOptions,
        blocks: &[&[u8]],
    ) -> Result<()> {
        self.backend.push_at(mesh, tile_id, projection, options, blocks)
    }

    pub fn set_block(&mut self, program: &Program, buffer_name: &str, bytes: &[u8]) -> Result<()> {
        self.backend.set_block(program, buffer_name, bytes)
    }

    pub fn set_composite(&mut self, composite: Composite) -> Result<()> {
        self.backend.set_composite(composite)
    }
}

// ---------------------------------------------------------------------------
// AfterGpu & raw GPU lending
// ---------------------------------------------------------------------------

/// Owned handle to a render session's post-GPU cleanup queue.
///
/// Clone from [`LendParameters::after_gpu`] to schedule GPU resource teardown
/// from [`Drop`] after in-flight GPU work finishes.
#[derive(Debug)]
pub struct AfterGpu {
    inner: Arc<dyn AfterGpuHandle>,
}

impl AfterGpu {
    #[doc(hidden)]
    #[must_use]
    pub fn from_handle(inner: Arc<dyn AfterGpuHandle>) -> Self {
        Self { inner }
    }

    /// Schedules `callback` to run once after the renderer's in-flight GPU work ends.
    pub fn push<F>(&self, callback: F) -> Result<()>
    where
        F: FnOnce(GpuEnd) + Send + 'static,
    {
        self.inner.push(Box::new(callback))
    }
}

impl Clone for AfterGpu {
    fn clone(&self) -> Self {
        Self { inner: self.inner.clone_handle().unwrap_or_else(|_| Arc::clone(&self.inner)) }
    }
}

/// Borrowed reference to a render session's post-GPU cleanup queue valid during
/// [`LayerInstance::lend`].
#[derive(Clone, Copy)]
pub struct AfterGpuRef<'a> {
    backend: &'a dyn AfterGpuRefBackend,
}

impl<'a> AfterGpuRef<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a dyn AfterGpuRefBackend) -> Self {
        Self { backend }
    }

    /// Clones an owned [`AfterGpu`] handle that can be stored on the layer instance.
    pub fn clone_handle(self) -> Result<AfterGpu> {
        self.backend.clone_handle()
    }

    /// Schedules `callback` to run once after the renderer's in-flight GPU work ends.
    pub fn push<F>(self, callback: F) -> Result<()>
    where
        F: FnOnce(GpuEnd) + Send + 'static,
    {
        self.backend.push(Box::new(callback))
    }
}

/// Borrowed parameters passed to [`LayerInstance::lend`].
#[derive(Clone, Copy)]
pub struct LendParameters<'a> {
    at: LendAt,
    frame: LendFrame,
    stage: LendStage<'a>,
    after_gpu: Option<AfterGpuRef<'a>>,
}

impl<'a> LendParameters<'a> {
    #[doc(hidden)]
    #[must_use]
    pub const fn new(at: LendAt, frame: LendFrame, stage: LendStage<'a>, after_gpu: Option<AfterGpuRef<'a>>) -> Self {
        Self { at, frame, stage, after_gpu }
    }

    /// Returns whether this lend callback runs before passes or inside the pass.
    #[must_use]
    pub const fn at(&self) -> LendAt {
        self.at
    }

    /// Returns the frame view, projection, and attachment dimensions.
    #[must_use]
    pub const fn frame(&self) -> &LendFrame {
        &self.frame
    }

    /// Returns the active stage and backend-specific encoder or pass handles.
    #[must_use]
    pub const fn stage(&self) -> LendStage<'a> {
        self.stage
    }

    /// Returns the borrowed after-GPU cleanup queue for this session, if present.
    #[must_use]
    pub const fn after_gpu(&self) -> Option<AfterGpuRef<'a>> {
        self.after_gpu
    }
}

// ---------------------------------------------------------------------------
// Query contexts (`HitCx`, `FrameQueryCx`)
// ---------------------------------------------------------------------------

/// Metadata snapshot for a tile-feature hit test ([`LayerInstance::hit`]).
#[derive(Clone, Debug)]
pub struct HitInfo<'a> {
    pub tile_id: TileId,
    pub pixels_to_tile_units: f32,
    pub has_ground: bool,
    pub query_geometry: Cow<'a, [PointI16]>,
    pub screen_geometry: Cow<'a, [ScreenPoint]>,
    pub feature_ring_count: usize,
}

/// Borrowed hit-test context passed to [`LayerInstance::hit`].
#[derive(Clone, Copy)]
pub struct HitCx<'a> {
    backend: &'a dyn HitCxBackend,
}

impl<'a> HitCx<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backend(backend: &'a dyn HitCxBackend) -> Self {
        Self { backend }
    }

    #[must_use]
    pub fn info(&self) -> HitInfo<'a> {
        self.backend.info()
    }

    #[must_use]
    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
        self.backend.evaluated()
    }

    #[must_use]
    pub fn view(&self) -> View<'a> {
        self.backend.view()
    }

    #[must_use]
    pub fn feature_ring(&self, index: usize) -> Option<Cow<'a, [PointI16]>> {
        self.backend.feature_ring(index)
    }

    pub fn eval_paint_f32(&self, slot: u32) -> Result<f32> {
        self.backend.eval_paint_f32(slot)
    }

    pub fn eval_paint_bool(&self, slot: u32) -> Result<bool> {
        self.backend.eval_paint_bool(slot)
    }

    pub fn eval_paint_color(&self, slot: u32) -> Result<Color> {
        self.backend.eval_paint_color(slot)
    }

    pub fn eval_paint_vec2(&self, slot: u32) -> Result<Vec2> {
        self.backend.eval_paint_vec2(slot)
    }

    pub fn eval_paint_enum(&self, slot: u32) -> Result<u32> {
        self.backend.eval_paint_enum(slot)
    }

    pub fn eval_paint_string(&self, slot: u32) -> Result<String> {
        self.backend.eval_paint_string(slot)
    }

    #[must_use]
    pub fn ground_height(&self, point: PointI16) -> f64 {
        self.backend.ground_height(point)
    }

    pub fn translated_query_geometry(&self, translate: Vec2, anchor: Alignment) -> Result<Vec<PointI16>> {
        self.backend.translated_query_geometry(translate, anchor)
    }

    pub fn plane_geometry(&self, elevation_m: f64, translate: Vec2, anchor: Alignment) -> Result<Vec<PointI16>> {
        self.backend.plane_geometry(elevation_m, translate, anchor)
    }

    #[must_use]
    pub fn viewport_point(&self, x: f64, y: f64, elevation_m: f64) -> Option<Vec2> {
        self.backend.viewport_point(x, y, elevation_m)
    }

    #[must_use]
    pub fn map_aligned_scale_at(&self, x: f64, y: f64) -> f64 {
        self.backend.map_aligned_scale_at(x, y)
    }

    #[must_use]
    pub fn pitch_scaled_size(
        &self,
        size: f32,
        point: PointI16,
        elevation_m: f64,
        pitch_scale: Alignment,
        pitch_alignment: Alignment,
    ) -> f32 {
        self.backend.pitch_scaled_size(size, point, elevation_m, pitch_scale, pitch_alignment)
    }

    #[must_use]
    pub fn shows(&self, x: f64, y: f64, elevation_m: f64) -> bool {
        self.backend.shows(x, y, elevation_m)
    }
}

/// Borrowed frame-query context passed to [`LayerInstance::hit_frame`].
pub struct FrameQueryCx<'a> {
    ro: &'a dyn FrameQueryCxReadBackend,
    rw: &'a mut dyn FrameQueryCxMutBackend,
}

impl<'a> FrameQueryCx<'a> {
    #[doc(hidden)]
    #[must_use]
    pub fn from_backends(ro: &'a dyn FrameQueryCxReadBackend, rw: &'a mut dyn FrameQueryCxMutBackend) -> Self {
        Self { ro, rw }
    }

    #[must_use]
    pub fn evaluated(&self) -> EvaluatedLayer<'a> {
        self.ro.evaluated()
    }

    #[must_use]
    pub fn view(&self) -> View<'a> {
        self.ro.view()
    }

    #[must_use]
    pub fn geometry(&self) -> Cow<'a, [ScreenPoint]> {
        self.ro.geometry()
    }

    #[must_use]
    pub fn has_ground(&self) -> bool {
        self.ro.has_ground()
    }

    #[must_use]
    pub fn ground_height(&self, tile_id: TileId, x: f32, y: f32) -> f32 {
        self.ro.ground_height(tile_id, x, y)
    }

    #[must_use]
    pub fn ground_visibility(&self, tile_id: TileId, x: f64, y: f64, elevation_m: f64) -> f64 {
        self.ro.ground_visibility(tile_id, x, y, elevation_m)
    }

    pub fn push_feature_json(&mut self, geojson_feature: &str) -> Result<()> {
        self.rw.push_feature_json(geojson_feature)
    }

    pub fn push_point_feature(&mut self, position: LatLng) -> Result<()> {
        self.rw.push_point_feature(position)
    }
}

// ---------------------------------------------------------------------------
// LayerPlugin & LayerInstance traits
// ---------------------------------------------------------------------------

/// Custom style layer type implemented against the MapLibre Plugin SDK.
///
/// One `LayerPlugin` value is registered once per registry builder (either
/// directly in `mln_engine::RegistryBuilder::add_layer_plugin` or over the C
/// Plugin ABI via `mln_plugin_c::RegistryBuilder::register_layer`) and lives
/// for the lifetime of the registered type.
pub trait LayerPlugin: Send + Sync + 'static {
    /// Per-style-layer instance state owned on the render thread.
    type Instance: LayerInstance;

    /// Returns the static layer descriptor (name, input, properties, terrain mode).
    fn desc(&self) -> LayerDesc<'_>;

    /// Optional one-time initialization against `host` when this plugin is
    /// registered (for example, registering shader [`Program`]s with
    /// [`Host::create_program`]).
    fn init(&mut self, _host: &Host<'_>) -> Result<()> {
        Ok(())
    }

    /// Creates per-layer render state when a style adds a layer of this type.
    fn create_instance(&self, evaluated: EvaluatedLayer<'_>) -> Result<Self::Instance>;

    /// Optional tile fade-in duration in nanoseconds.
    fn tile_fade_ns(&self, _evaluated: EvaluatedLayer<'_>) -> u64 {
        0
    }

    /// Optional tile-worker geometry layout hook (required for `LayerInput::GeometryTiles` layers).
    fn build_tile_geometry(&self, _cx: &mut TileBuildCx<'_>, _out: &mut TileGeometryBuilder<'_>) -> Result<()> {
        Ok(())
    }

    /// Optional query padding radius in pixels for worker-built tile geometry.
    fn query_radius(&self, _geometry: TileGeometry<'_>, _evaluated: EvaluatedLayer<'_>) -> f32 {
        0.0
    }
}

/// Per-style-layer render-thread instance for a [`LayerPlugin`].
pub trait LayerInstance: 'static {
    /// Per-tile GPU resources created in [`create_tile_resources`](Self::create_tile_resources).
    type TileResources: 'static;

    /// Evaluates render passes and repaint scheduling for the current frame.
    fn evaluate(&mut self, cx: EvaluateCx<'_>) -> Evaluation;

    /// Optional per-frame update hook before tile resource creation / draw preparation.
    fn update(&mut self, _cx: &mut UpdateCx<'_>) {}

    /// Optional per-tile GPU resource creation hook.
    fn create_tile_resources(
        &mut self,
        _cx: &mut TileCx<'_>,
        _previous: Option<&mut Self::TileResources>,
    ) -> Result<Option<Self::TileResources>> {
        Ok(None)
    }

    /// Records draw calls for the current frame.
    fn prepare(&mut self, _cx: &mut PrepareCx<'_, Self::TileResources>, _draws: &mut Draws<'_>) {}

    /// Tile-feature hit test for geometry layers.
    fn hit(&self, _cx: HitCx<'_>) -> Hit {
        Hit::Miss
    }

    /// Frame-level hit test for sourceless (`LayerInput::Frame`) layers.
    fn hit_frame(&self, _cx: &mut FrameQueryCx<'_>) {}

    /// Records raw backend GPU commands requested via [`Draws::lend`].
    fn lend(&mut self, _params: &LendParameters<'_>) {}
}