mln-rs-plugin 0.0.22

Safe Rust SDK for writing MapLibre layer and source 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
//! Host-agnostic value types shared across plugin layers and sources.

use core::ffi::c_void;

/// Straight (non-premultiplied) extended-sRGB RGBA color.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Color {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Color {
    pub const BLACK: Self = Self::rgba(0.0, 0.0, 0.0, 1.0);
    pub const WHITE: Self = Self::rgba(1.0, 1.0, 1.0, 1.0);
    pub const TRANSPARENT: Self = Self::rgba(0.0, 0.0, 0.0, 0.0);

    #[must_use]
    pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self {
        Self { r, g, b, a }
    }

    /// Converts this straight extended-sRGB color into clipped premultiplied
    /// sRGB `[r*a, g*a, b*a, a]`.
    #[must_use]
    pub fn to_premultiplied(self) -> [f32; 4] {
        let r = self.r.clamp(0.0, 1.0);
        let g = self.g.clamp(0.0, 1.0);
        let b = self.b.clamp(0.0, 1.0);
        [r * self.a, g * self.a, b * self.a, self.a]
    }
}

/// Two-component float vector.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

impl Vec2 {
    #[must_use]
    pub const fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

impl From<[f32; 2]> for Vec2 {
    fn from([x, y]: [f32; 2]) -> Self {
        Self { x, y }
    }
}

impl From<Vec2> for [f32; 2] {
    fn from(v: Vec2) -> Self {
        [v.x, v.y]
    }
}

/// Geographic coordinate in WGS84 degrees.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct LatLng {
    pub latitude: f64,
    pub longitude: f64,
}

impl LatLng {
    #[must_use]
    pub const fn new(latitude: f64, longitude: f64) -> Self {
        Self { latitude, longitude }
    }

    /// Wraps longitude into `[-180, 180]`, matching `mln_style::geo::LatLng::wrapped`.
    #[must_use]
    pub fn wrapped(self) -> Self {
        let v = self.longitude;
        let lon = if (-180.0..180.0).contains(&v) {
            v
        } else if v == 180.0 {
            -180.0
        } else {
            let w = -180.0 + (v + 180.0) % 360.0;
            if v < -180.0 { w + 360.0 } else { w }
        };
        Self { latitude: self.latitude, longitude: lon }
    }
}

/// Geographic bounding box.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LatLngBounds {
    pub southwest: LatLng,
    pub northeast: LatLng,
}

/// Screen-space coordinate in logical pixels from top-left.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ScreenPoint {
    pub x: f64,
    pub y: f64,
}

/// Tile-space integer point.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PointI16 {
    pub x: i16,
    pub y: i16,
}

impl PointI16 {
    #[must_use]
    pub const fn new(x: i16, y: i16) -> Self {
        Self { x, y }
    }
}

/// Canonical tile coordinate (`z`, `x`, `y`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct CanonicalTileId {
    pub z: u32,
    pub x: u32,
    pub y: u32,
}

impl CanonicalTileId {
    #[must_use]
    pub const fn new(z: u32, x: u32, y: u32) -> Self {
        Self { z, x, y }
    }
}

/// Overscaled and wrapped tile coordinate.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TileId {
    pub overscaled_z: u32,
    pub wrap: i32,
    pub canonical_z: u32,
    pub canonical_x: u32,
    pub canonical_y: u32,
}

impl TileId {
    #[must_use]
    pub const fn canonical(self) -> CanonicalTileId {
        CanonicalTileId { z: self.canonical_z, x: self.canonical_x, y: self.canonical_y }
    }

    #[must_use]
    pub const fn from_canonical(z: u32, x: u32, y: u32) -> Self {
        Self { overscaled_z: z, wrap: 0, canonical_z: z, canonical_x: x, canonical_y: y }
    }

    #[must_use]
    pub const fn with_wrap(wrap: i32, canonical: CanonicalTileId) -> Self {
        Self {
            overscaled_z: canonical.z,
            wrap,
            canonical_z: canonical.z,
            canonical_x: canonical.x,
            canonical_y: canonical.y,
        }
    }

    #[must_use]
    pub const fn unwrapped(wrap: i32, z: u32, x: u32, y: u32) -> Self {
        Self { overscaled_z: z, wrap, canonical_z: z, canonical_x: x, canonical_y: y }
    }

    /// Converts a logical pixel distance into tile coordinate units at `zoom`.
    #[must_use]
    pub fn pixels_to_tile_units(self, pixels: f32, zoom: f32) -> f32 {
        pixels * (8192.0 / (512.0 * 2.0f32.powf(zoom - self.canonical_z as f32)))
    }
}

/// One indexed draw call range within a mesh.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DrawRange {
    pub first_index: u32,
    pub index_count: u32,
    pub base_vertex: i32,
    pub first_instance: u32,
    pub instance_count: u32,
}

impl DrawRange {
    #[must_use]
    pub const fn indexes(index_count: u32) -> Self {
        Self { first_index: 0, index_count, base_vertex: 0, first_instance: 0, instance_count: 1 }
    }
}

/// Per-draw tile projection uniform block.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ProjectionUbo {
    pub matrix: [f32; 16],
    pub fallback_matrix: [f32; 16],
    pub tile_mercator_coords: [f32; 4],
    pub clipping_plane: [f32; 4],
    pub projection_transition: f32,
    pub depth_offset: f32,
    pub translate: [f32; 2],
    pub anchor: [f32; 4],
    pub anchor_angles: [f32; 4],
}

/// What input data drives a plugin layer's per-frame preparation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LayerInput {
    /// No source tiles; `prepare` renders against the frame and camera view.
    Frame,
    /// No source tiles; `update` receives viewport tiles and picks tiles for `prepare`.
    ViewportTiles,
    /// Vector/GeoJSON geometry source tiles; tile workers run `build_tile_geometry`.
    GeometryTiles,
    /// Decoded RGBA raster source tiles.
    RasterTiles,
    /// Elevation DEM source tiles.
    RasterDemTiles,
    /// The tiles of a source of any type, without their data: the layer
    /// draws over the tiles its source renders.
    SourceTiles,
}

/// A shape that a frame's placement tested for a label or an icon
/// ([`Frame::collision_shapes`](crate::Frame::collision_shapes)).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct CollisionShape {
    pub kind: CollisionShapeKind,
    /// Whether the label or icon placed. One that collided, or that hides
    /// for another reason, such as a part it waits for, didn't.
    pub placed: bool,
}

/// The geometry of a [`CollisionShape`], in logical pixels from the view's
/// top-left corner.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CollisionShapeKind {
    /// An axis-aligned box, from its `min` corner to its `max` corner.
    Box { min: Vec2, max: Vec2 },
    /// A circle, which a line label's glyphs collide as.
    Circle { center: Vec2, radius: f32 },
}

impl Default for CollisionShapeKind {
    fn default() -> Self {
        Self::Box { min: Vec2::default(), max: Vec2::default() }
    }
}

/// Graphics backend active for a render session.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RenderBackend {
    Metal,
    Vulkan,
    OpenGl,
    WebGpu,
    D3d12,
}

/// When in a frame the renderer lends raw backend GPU commands to a layer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LendAt {
    /// Outside the map's render pass, before passes begin (prerender).
    BeforePasses,
    /// Inside the map's translucent render pass, at the layer's place.
    Pass,
}

/// How the GPU work waited on by [`crate::AfterGpu::push`] ended.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GpuEnd {
    /// The GPU finished the renderer's work; GPU objects can be destroyed.
    Completed,
    /// The renderer's graphics objects were lost; forget GPU objects without destroying them.
    ContextLost,
}

/// Map rendering mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MapMode {
    Continuous,
    Static,
    Tile,
}

/// Active projection variant for shader compilation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProjectionVariant {
    Mercator,
    Globe,
    MercatorStanding,
    GlobeStanding,
}

/// Translate anchor or pitch alignment frame of reference.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Alignment {
    Map,
    Viewport,
}

/// Vector tile feature geometry type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FeatureType {
    Unknown,
    Point,
    LineString,
    Polygon,
}

/// Render pass bitmask.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RenderPasses(pub u32);

impl RenderPasses {
    pub const NONE: Self = Self(0);
    pub const OPAQUE: Self = Self(1);
    pub const TRANSLUCENT: Self = Self(2);

    #[must_use]
    pub const fn from_bits(bits: u32) -> Self {
        Self(bits)
    }

    #[must_use]
    pub const fn bits(self) -> u32 {
        self.0
    }

    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }
}

/// Tile change bitmask reported by `PrepareCx::take_tile_changes`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TileChanges(pub u32);

impl TileChanges {
    pub const PAINT: u32 = 1;
    pub const OPACITY: u32 = 2;
    pub const DYNAMIC: u32 = 4;
    pub const SORT: u32 = 8;

    #[must_use]
    pub const fn from_bits(bits: u32) -> Self {
        Self(bits)
    }

    #[must_use]
    pub const fn bits(self) -> u32 {
        self.0
    }

    #[must_use]
    pub const fn paint(self) -> bool {
        (self.0 & Self::PAINT) != 0
    }

    #[must_use]
    pub const fn opacity(self) -> bool {
        (self.0 & Self::OPACITY) != 0
    }

    #[must_use]
    pub const fn dynamic(self) -> bool {
        (self.0 & Self::DYNAMIC) != 0
    }

    #[must_use]
    pub const fn sort(self) -> bool {
        (self.0 & Self::SORT) != 0
    }

    #[must_use]
    pub const fn any_paint(self) -> bool {
        self.paint() || self.dynamic()
    }
}

/// Order in which tiles are passed to a layer's prepare callback.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TileOrder {
    #[default]
    ById,
    ByY,
}

/// How a plugin layer interacts with 3D terrain.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TerrainMode {
    #[default]
    Flat,
    Stands,
    StandsHidingBehindGround,
    Drapes,
}

/// Tile transform parameters for `Frame::tile_projection`.
#[derive(Clone, Copy, Debug)]
pub struct TileTransform {
    pub translate: [f32; 2],
    pub translate_anchor: Alignment,
    pub near_clipped: bool,
    pub pixel_aligned: bool,
}

impl Default for TileTransform {
    fn default() -> Self {
        Self { translate: [0.0, 0.0], translate_anchor: Alignment::Map, near_clipped: false, pixel_aligned: false }
    }
}

/// Snapshot of frame-level parameters (sizes in device pixels).
#[derive(Clone, Copy, Debug)]
pub struct FrameInfo {
    pub width: u32,
    pub height: u32,
    pub pixel_ratio: f32,
    pub pixel_scale: f64,
    pub pixels_to_gl_units: [f32; 2],
    pub camera_moving: bool,
    pub terrain: bool,
    pub composites_with_frame_depth: bool,
    pub drape_lit: bool,
    pub has_ground: bool,
    pub time_point_ns: Option<i64>,
}

/// Snapshot of camera view parameters (sizes in logical pixels, angles in radians).
#[derive(Clone, Copy, Debug)]
pub struct ViewInfo {
    pub width: u32,
    pub height: u32,
    pub zoom: f64,
    pub integer_zoom: u8,
    pub angle_rad: f64,
    pub pitch_rad: f64,
    pub camera_to_center_distance: f64,
    pub is_globe: bool,
    pub world_wraps: bool,
}

/// Result of projecting a tile point through the active projection.
#[derive(Clone, Copy, Debug)]
pub struct ProjectedPoint {
    pub clip_x: f64,
    pub clip_y: f64,
    pub signed_distance_from_camera: f64,
    pub occluded: bool,
}

/// Color blend mode preset for a mesh.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ColorMode {
    AlphaBlended,
    Unblended,
    Additive,
    Disabled,
}

/// Face culling configuration for a mesh.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CullFaceMode {
    pub enabled: bool,
    pub side: CullFaceSide,
    pub winding: CullFaceWinding,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CullFaceSide {
    #[default]
    Back,
    Front,
    FrontAndBack,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CullFaceWinding {
    #[default]
    Ccw,
    Cw,
}

impl CullFaceMode {
    pub const DISABLED: Self = Self { enabled: false, side: CullFaceSide::Back, winding: CullFaceWinding::Ccw };
}

/// Primitive draw mode for a mesh.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DrawMode {
    Triangles,
    TriangleStrip,
    TriangleFan,
    Lines(f32),
    LineLoop(f32),
    LineStrip(f32),
    Points(f32),
}

/// Depth testing mode for a draw call.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DepthMode {
    Layer { sub_layer: u8, write: bool },
    Off,
    Volume { write: bool },
}

impl Default for DepthMode {
    fn default() -> Self {
        Self::Layer { sub_layer: 0, write: false }
    }
}

/// Per-draw submission options.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DrawOptions {
    pub order: i64,
    pub opaque: bool,
    pub depth: DepthMode,
    pub clip: bool,
}

impl Default for DrawOptions {
    fn default() -> Self {
        Self { order: 0, opaque: false, depth: DepthMode::Layer { sub_layer: 0, write: false }, clip: false }
    }
}

/// Texture texel format.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextureFormat {
    Rgba8Unorm,
    R8Unorm,
    A8Unorm,
    R16Float,
    R32Float,
    Rgba16Float,
    Rgba32Float,
}

/// Render target color channel type.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextureChannelType {
    UnsignedByte,
    HalfFloat,
    Float,
}

/// Texture sampler filter mode.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextureFilter {
    Nearest,
    #[default]
    Linear,
}

/// Texture sampler wrap mode.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextureWrap {
    #[default]
    Clamp,
    Repeat,
}

/// Texture sampler configuration.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SamplerState {
    pub filter: TextureFilter,
    pub wrap_u: TextureWrap,
    pub wrap_v: TextureWrap,
    pub max_anisotropy: u8,
    pub mipmapped: bool,
}

/// Whether a plugin source counts tile rows from the north (XYZ) or south (TMS).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TileScheme {
    #[default]
    Xyz,
    Tms,
}

/// Cache timestamps for a delivered plugin source tile.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TileTimes {
    pub modified_unix_ms: Option<i64>,
    pub expires_unix_ms: Option<i64>,
}

/// Tile urgency reported to plugin sources.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TileNecessity {
    Required,
    Optional,
}

/// Elevation encoding for `RasterDem` plugin sources.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RasterEncoding {
    Mapbox,
    Terrarium,
}

// ---------------------------------------------------------------------------
// Raw backend GPU lending types (`Draws::lend` / `LayerInstance::lend`)
// ---------------------------------------------------------------------------

/// Frame camera, projection, and attachment dimensions during a lent GPU callback.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LendFrame {
    pub center: LatLng,
    pub zoom: f64,
    pub bearing_deg: f64,
    pub pitch_deg: f64,
    pub projection_matrix: [[f64; 4]; 4],
    pub clip_depth_zero_to_one: bool,
    pub near_distance: f64,
    pub far_distance: f64,
    pub far_depth: f64,
    pub globe: bool,
    pub width: u32,
    pub height: u32,
}

/// Vulkan device/queue handles exposed to a lent GPU callback.
#[derive(Clone, Copy, Debug)]
pub struct VulkanContextDescriptor {
    pub instance: *mut c_void,
    pub physical_device: *mut c_void,
    pub device: *mut c_void,
    pub graphics_queue: *mut c_void,
    pub graphics_queue_family_index: u32,
    pub get_instance_proc_addr: *mut c_void,
    pub get_device_proc_addr: *mut c_void,
}

/// Metal encoder lent before passes begin.
#[derive(Clone, Copy, Debug)]
pub struct MetalEncoder {
    pub command_buffer: *mut c_void,
}

/// Vulkan command buffer lent before passes begin.
#[derive(Clone, Copy, Debug)]
pub struct VulkanEncoder {
    pub context: VulkanContextDescriptor,
    pub command_buffer: *mut c_void,
}

/// OpenGL or WebGL2 context lent before passes begin.
#[derive(Clone, Copy, Debug)]
pub struct OpenGlEncoder {
    /// On the web, the session's `WebGL2RenderingContext` object ID; `0` on native platforms.
    pub web_context: u32,
}

/// WebGPU device and command encoder object IDs lent before passes begin.
#[derive(Clone, Copy, Debug)]
pub struct WebGpuEncoder {
    pub device: u32,
    pub encoder: u32,
}

/// Direct3D 12 device and command list lent before passes begin.
#[derive(Clone, Copy, Debug)]
pub struct D3d12Encoder {
    pub device: *mut c_void,
    pub command_list: *mut c_void,
}

/// Metal render pass lent at a layer's place.
#[derive(Clone, Copy, Debug)]
pub struct MetalPass {
    pub encoder: *mut c_void,
    pub command_buffer: *mut c_void,
    pub color_format: u64,
    pub depth_format: u64,
    pub stencil_format: u64,
    pub sample_count: u32,
}

/// Vulkan render pass lent at a layer's place.
#[derive(Clone, Copy, Debug)]
pub struct VulkanPass {
    pub context: VulkanContextDescriptor,
    pub command_buffer: *mut c_void,
    pub render_pass: u64,
    pub subpass: u32,
    pub sample_count: u32,
    pub color_format: u32,
    pub depth_stencil_format: u32,
}

/// OpenGL or WebGL2 framebuffer lent at a layer's place.
#[derive(Clone, Copy, Debug)]
pub struct OpenGlPass {
    /// On native platforms, the framebuffer name (`0` for the default framebuffer); always `0` on the web.
    pub framebuffer: u32,
    /// On the web, the session's `WebGL2RenderingContext` object ID; `0` on native platforms.
    pub web_context: u32,
    /// On the web, the bound `WebGLFramebuffer` object ID (`0` for the default framebuffer); `0` on native platforms.
    pub web_framebuffer: u32,
}

/// Direct3D 12 render pass lent at a layer's place.
#[derive(Clone, Copy, Debug)]
pub struct D3d12Pass {
    pub device: *mut c_void,
    pub command_list: *mut c_void,
    pub render_target_view: u64,
    pub color_format: u32,
    pub depth_stencil_view: u64,
    pub depth_stencil_format: u32,
}

/// Raw backend GPU encoder lent outside the map's render pass ([`LendAt::BeforePasses`]).
#[derive(Clone, Copy, Debug)]
pub enum LendEncoder {
    Metal(MetalEncoder),
    Vulkan(VulkanEncoder),
    OpenGl(OpenGlEncoder),
    WebGpu(WebGpuEncoder),
    D3d12(D3d12Encoder),
}

/// Raw backend GPU render pass lent at the layer's place ([`LendAt::Pass`]).
#[derive(Clone, Copy, Debug)]
pub enum LendPass<'a> {
    Metal(MetalPass),
    Vulkan(VulkanPass),
    OpenGl(OpenGlPass),
    WebGpu { device: u32, encoder: u32, color_format: &'a str, depth_stencil_format: &'a str, sample_count: u32 },
    D3d12(D3d12Pass),
}

/// Stage-specific payload inside [`crate::LendParameters`].
#[derive(Clone, Copy, Debug)]
pub enum LendStage<'a> {
    BeforePasses { backend: RenderBackend, encoder: LendEncoder },
    Pass { backend: RenderBackend, pass: LendPass<'a>, layer_depth: f64 },
}

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

    #[test]
    fn lat_lng_wrapped_normalizes_longitudes() {
        let cases = [
            (0.0, 0.0),
            (-180.0, -180.0),
            (180.0, -180.0),
            (180.0f64.next_down(), 180.0f64.next_down()),
            (-540.0, 180.0),
            (540.0, -180.0),
            (190.0, -170.0),
            (-190.0, 170.0),
        ];
        for (input, expected) in cases {
            assert_eq!(LatLng::new(10.0, input).wrapped().longitude, expected, "input={input}");
        }
    }

    #[test]
    fn color_to_premultiplied_clamps_rgb_and_scales_by_alpha() {
        assert_eq!(Color::rgba(0.5, 1.5, -0.2, 0.5).to_premultiplied(), [0.25, 0.5, 0.0, 0.5]);
        assert_eq!(Color::TRANSPARENT.to_premultiplied(), [0.0, 0.0, 0.0, 0.0]);
    }
}