rustial-engine 0.0.1

Framework-agnostic 2.5D map engine for rustial
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
//! Mapbox Vector Tile (MVT / PBF) binary decoder.
//!
//! This module decodes [Mapbox Vector Tile v2][spec] protocol-buffer
//! payloads into the engine's [`FeatureCollection`] geometry model.
//!
//! [spec]: https://github.com/mapbox/vector-tile-spec/tree/master/2.1
//!
//! # Wire format summary
//!
//! An MVT tile is a protobuf message containing one or more **layers**,
//! each of which contains:
//!
//! - a `name` (source layer id)
//! - shared `keys` and `values` string tables
//! - one or more **features** with:
//!   - an optional `id`
//!   - a geometry type (`POINT`, `LINESTRING`, `POLYGON`)
//!   - a command-encoded geometry stream
//!   - interleaved `tags` indexing into the key/value tables
//!
//! Coordinates in MVT are integer tile-local pixel positions in a grid
//! of `extent` units (typically 4096).  This decoder converts them to
//! WGS-84 [`GeoCoord`] using the tile's geographic bounds.
//!
//! # Usage
//!
//! ```rust,ignore
//! use rustial_engine::mvt::{decode_mvt, MvtDecodeOptions};
//! use rustial_math::TileId;
//!
//! let tile_id = TileId::new(14, 8192, 5461);
//! let layers = decode_mvt(&pbf_bytes, &tile_id, &MvtDecodeOptions::default())?;
//! for (layer_name, features) in &layers {
//!     println!("{}: {} features", layer_name, features.len());
//! }
//! ```
//!
//! # Error handling
//!
//! Decoding never panics.  Malformed protobuf fields are skipped, and
//! individual feature decode failures are logged and skipped rather
//! than aborting the entire tile.
//!
//! # No external protobuf dependency
//!
//! This decoder hand-rolls the protobuf wire format reading rather
//! than depending on `prost` or `protobuf`.  The MVT spec uses a tiny
//! subset of protobuf (varint, length-delimited, fixed32) and the
//! hand-rolled approach avoids a heavy code-generation dependency for
//! ~200 lines of wire decoding.

use crate::geometry::{
    Feature, FeatureCollection, Geometry, LineString, MultiLineString, MultiPoint, MultiPolygon,
    Point, Polygon, PropertyValue,
};
use rustial_math::TileId;
use std::collections::HashMap;
use std::fmt;

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Options controlling MVT decoding behaviour.
#[derive(Debug, Clone, Default)]
pub struct MvtDecodeOptions {
    /// Filter layers to decode.  When empty, all layers are decoded.
    pub layer_filter: Vec<String>,
}

/// Errors that can occur during MVT decoding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MvtError {
    /// The payload was too short or truncated.
    TruncatedPayload,
    /// An unsupported protobuf wire type was encountered.
    UnsupportedWireType(u8),
    /// A feature contained an invalid geometry command.
    InvalidGeometryCommand(u32),
    /// A generic decode error.
    DecodeError(String),
}

impl fmt::Display for MvtError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MvtError::TruncatedPayload => write!(f, "truncated MVT payload"),
            MvtError::UnsupportedWireType(wt) => {
                write!(f, "unsupported protobuf wire type: {wt}")
            }
            MvtError::InvalidGeometryCommand(cmd) => {
                write!(f, "invalid MVT geometry command: {cmd}")
            }
            MvtError::DecodeError(msg) => write!(f, "MVT decode error: {msg}"),
        }
    }
}

impl std::error::Error for MvtError {}

/// Decoded vector tile: a map from source-layer name to feature collection.
pub type DecodedVectorTile = HashMap<String, FeatureCollection>;

/// Decode an MVT (PBF) binary payload into per-layer feature collections.
///
/// Coordinates are transformed from tile-local integer positions to
/// WGS-84 geographic coordinates using `tile_id` to derive the
/// tile's geographic bounds.
pub fn decode_mvt(
    bytes: &[u8],
    tile_id: &TileId,
    options: &MvtDecodeOptions,
) -> Result<DecodedVectorTile, MvtError> {
    let tile_bounds = tile_geo_bounds(tile_id);
    let mut result = DecodedVectorTile::new();
    let mut reader = PbReader::new(bytes);

    while reader.remaining() > 0 {
        let (field_number, wire_type) = reader.read_tag()?;
        match (field_number, wire_type) {
            // Tile.layers (field 3, length-delimited)
            (3, WIRE_LEN) => {
                let layer_bytes = reader.read_bytes()?;
                match decode_layer(layer_bytes, &tile_bounds, options) {
                    Ok(Some((name, features))) => {
                        result
                            .entry(name)
                            .or_insert_with(|| FeatureCollection {
                                features: Vec::new(),
                            })
                            .features
                            .extend(features.features);
                    }
                    Ok(None) => {} // filtered out
                    Err(e) => {
                        log::warn!("skipping malformed MVT layer: {e}");
                    }
                }
            }
            _ => {
                reader.skip_field(wire_type)?;
            }
        }
    }

    Ok(result)
}

// ---------------------------------------------------------------------------
// Tile geographic bounds
// ---------------------------------------------------------------------------

/// Geographic bounds of a tile in WGS-84 degrees.
struct TileGeoBounds {
    west: f64,
    south: f64,
    east: f64,
    north: f64,
}

fn tile_geo_bounds(tile: &TileId) -> TileGeoBounds {
    let n = (1u64 << tile.zoom) as f64;
    let west = tile.x as f64 / n * 360.0 - 180.0;
    let east = (tile.x as f64 + 1.0) / n * 360.0 - 180.0;

    let north_rad = std::f64::consts::PI * (1.0 - 2.0 * tile.y as f64 / n);
    let south_rad = std::f64::consts::PI * (1.0 - 2.0 * (tile.y as f64 + 1.0) / n);

    let north = north_rad.sinh().atan().to_degrees();
    let south = south_rad.sinh().atan().to_degrees();

    TileGeoBounds {
        west,
        south,
        east,
        north,
    }
}

/// Convert tile-local integer coordinates to WGS-84.
#[inline]
fn tile_coord_to_geo(
    x: i32,
    y: i32,
    extent: u32,
    bounds: &TileGeoBounds,
) -> rustial_math::GeoCoord {
    let extent_f = extent as f64;
    let lon = bounds.west + (x as f64 / extent_f) * (bounds.east - bounds.west);
    let lat = bounds.north + (y as f64 / extent_f) * (bounds.south - bounds.north);
    rustial_math::GeoCoord::from_lat_lon(lat, lon)
}

// ---------------------------------------------------------------------------
// Layer decoding
// ---------------------------------------------------------------------------

fn decode_layer(
    bytes: &[u8],
    bounds: &TileGeoBounds,
    options: &MvtDecodeOptions,
) -> Result<Option<(String, FeatureCollection)>, MvtError> {
    let mut reader = PbReader::new(bytes);
    let mut name = String::new();
    let mut keys: Vec<String> = Vec::new();
    let mut values: Vec<PropertyValue> = Vec::new();
    let mut features_bytes: Vec<&[u8]> = Vec::new();
    let mut extent: u32 = 4096;

    while reader.remaining() > 0 {
        let (field_number, wire_type) = reader.read_tag()?;
        match (field_number, wire_type) {
            // Layer.name (field 1)
            (1, WIRE_LEN) => {
                name = reader.read_string()?;
            }
            // Layer.features (field 2)
            (2, WIRE_LEN) => {
                features_bytes.push(reader.read_bytes()?);
            }
            // Layer.keys (field 3)
            (3, WIRE_LEN) => {
                keys.push(reader.read_string()?);
            }
            // Layer.values (field 4)
            (4, WIRE_LEN) => {
                let val_bytes = reader.read_bytes()?;
                values.push(decode_value(val_bytes)?);
            }
            // Layer.extent (field 5)
            (5, WIRE_VARINT) => {
                extent = reader.read_varint()? as u32;
                if extent == 0 {
                    extent = 4096;
                }
            }
            // Layer.version (field 15) -- ignored
            (15, WIRE_VARINT) => {
                let _ = reader.read_varint()?;
            }
            _ => {
                reader.skip_field(wire_type)?;
            }
        }
    }

    // Apply layer filter.
    if !options.layer_filter.is_empty() && !options.layer_filter.iter().any(|f| f == &name) {
        return Ok(None);
    }

    let mut features = Vec::with_capacity(features_bytes.len());
    for feat_bytes in features_bytes {
        match decode_feature(feat_bytes, &keys, &values, extent, bounds) {
            Ok(feature) => features.push(feature),
            Err(e) => {
                log::debug!("skipping malformed MVT feature in layer '{name}': {e}");
            }
        }
    }

    Ok(Some((name, FeatureCollection { features })))
}

// ---------------------------------------------------------------------------
// Value decoding
// ---------------------------------------------------------------------------

fn decode_value(bytes: &[u8]) -> Result<PropertyValue, MvtError> {
    let mut reader = PbReader::new(bytes);
    let mut result = PropertyValue::Null;

    while reader.remaining() > 0 {
        let (field_number, wire_type) = reader.read_tag()?;
        match (field_number, wire_type) {
            // string_value (field 1)
            (1, WIRE_LEN) => {
                result = PropertyValue::String(reader.read_string()?);
            }
            // float_value (field 2)
            (2, WIRE_32) => {
                result = PropertyValue::Number(reader.read_fixed32_f32()? as f64);
            }
            // double_value (field 3)
            (3, WIRE_64) => {
                result = PropertyValue::Number(reader.read_fixed64_f64()?);
            }
            // int_value (field 4)
            (4, WIRE_VARINT) => {
                result = PropertyValue::Number(reader.read_varint()? as f64);
            }
            // uint_value (field 5)
            (5, WIRE_VARINT) => {
                result = PropertyValue::Number(reader.read_varint()? as f64);
            }
            // sint_value (field 6)
            (6, WIRE_VARINT) => {
                let raw = reader.read_varint()?;
                let decoded = zigzag_decode(raw);
                result = PropertyValue::Number(decoded as f64);
            }
            // bool_value (field 7)
            (7, WIRE_VARINT) => {
                result = PropertyValue::Bool(reader.read_varint()? != 0);
            }
            _ => {
                reader.skip_field(wire_type)?;
            }
        }
    }

    Ok(result)
}

// ---------------------------------------------------------------------------
// Feature decoding
// ---------------------------------------------------------------------------

/// MVT geometry types.
const GEOM_UNKNOWN: u32 = 0;
const GEOM_POINT: u32 = 1;
const GEOM_LINESTRING: u32 = 2;
const GEOM_POLYGON: u32 = 3;

fn decode_feature(
    bytes: &[u8],
    keys: &[String],
    values: &[PropertyValue],
    extent: u32,
    bounds: &TileGeoBounds,
) -> Result<Feature, MvtError> {
    let mut reader = PbReader::new(bytes);
    let mut geom_type: u32 = GEOM_UNKNOWN;
    let mut geometry_bytes: &[u8] = &[];
    let mut tags_bytes: &[u8] = &[];
    let mut feature_id: Option<u64> = None;

    while reader.remaining() > 0 {
        let (field_number, wire_type) = reader.read_tag()?;
        match (field_number, wire_type) {
            // Feature.id (field 1)
            (1, WIRE_VARINT) => {
                feature_id = Some(reader.read_varint()?);
            }
            // Feature.tags (field 2, packed varint)
            (2, WIRE_LEN) => {
                tags_bytes = reader.read_bytes()?;
            }
            // Feature.type (field 3)
            (3, WIRE_VARINT) => {
                geom_type = reader.read_varint()? as u32;
            }
            // Feature.geometry (field 4, packed uint32)
            (4, WIRE_LEN) => {
                geometry_bytes = reader.read_bytes()?;
            }
            _ => {
                reader.skip_field(wire_type)?;
            }
        }
    }

    let geometry = decode_geometry(geom_type, geometry_bytes, extent, bounds)?;
    let properties = decode_tags(tags_bytes, keys, values)?;

    let mut props = properties;
    if let Some(id) = feature_id {
        props.insert("$id".to_owned(), PropertyValue::Number(id as f64));
    }

    Ok(Feature {
        geometry,
        properties: props,
    })
}

fn decode_tags(
    bytes: &[u8],
    keys: &[String],
    values: &[PropertyValue],
) -> Result<HashMap<String, PropertyValue>, MvtError> {
    let mut props = HashMap::new();
    if bytes.is_empty() {
        return Ok(props);
    }

    let mut reader = PbReader::new(bytes);
    while reader.remaining() > 0 {
        let key_idx = reader.read_varint()? as usize;
        if reader.remaining() == 0 {
            break;
        }
        let val_idx = reader.read_varint()? as usize;

        if let (Some(key), Some(val)) = (keys.get(key_idx), values.get(val_idx)) {
            props.insert(key.clone(), val.clone());
        }
    }

    Ok(props)
}

// ---------------------------------------------------------------------------
// Geometry command decoding
// ---------------------------------------------------------------------------

/// MVT geometry command IDs.
const CMD_MOVE_TO: u32 = 1;
const CMD_LINE_TO: u32 = 2;
const CMD_CLOSE_PATH: u32 = 7;

fn decode_geometry(
    geom_type: u32,
    bytes: &[u8],
    extent: u32,
    bounds: &TileGeoBounds,
) -> Result<Geometry, MvtError> {
    let commands = decode_commands(bytes)?;
    let rings = commands_to_rings(&commands, extent, bounds);

    match geom_type {
        GEOM_POINT => geometry_from_points(rings),
        GEOM_LINESTRING => geometry_from_linestrings(rings),
        GEOM_POLYGON => geometry_from_polygons(rings),
        _ => Err(MvtError::DecodeError(format!(
            "unknown geometry type: {geom_type}"
        ))),
    }
}

struct GeomCommand {
    id: u32,
    params: Vec<(i32, i32)>,
}

fn decode_commands(bytes: &[u8]) -> Result<Vec<GeomCommand>, MvtError> {
    let mut reader = PbReader::new(bytes);
    let mut commands = Vec::new();
    let mut cursor_x: i32 = 0;
    let mut cursor_y: i32 = 0;

    while reader.remaining() > 0 {
        let cmd_int = reader.read_varint()? as u32;
        let cmd_id = cmd_int & 0x7;
        let cmd_count = cmd_int >> 3;

        if cmd_id == CMD_CLOSE_PATH {
            commands.push(GeomCommand {
                id: CMD_CLOSE_PATH,
                params: Vec::new(),
            });
            continue;
        }

        if cmd_id != CMD_MOVE_TO && cmd_id != CMD_LINE_TO {
            return Err(MvtError::InvalidGeometryCommand(cmd_int));
        }

        let mut params = Vec::with_capacity(cmd_count as usize);
        for _ in 0..cmd_count {
            if reader.remaining() < 2 {
                break;
            }
            let dx = zigzag_decode(reader.read_varint()?) as i32;
            let dy = zigzag_decode(reader.read_varint()?) as i32;
            cursor_x += dx;
            cursor_y += dy;
            params.push((cursor_x, cursor_y));
        }

        commands.push(GeomCommand { id: cmd_id, params });
    }

    Ok(commands)
}

fn commands_to_rings(
    commands: &[GeomCommand],
    extent: u32,
    bounds: &TileGeoBounds,
) -> Vec<Vec<rustial_math::GeoCoord>> {
    let mut rings: Vec<Vec<rustial_math::GeoCoord>> = Vec::new();
    let mut current_ring: Vec<rustial_math::GeoCoord> = Vec::new();

    for cmd in commands {
        match cmd.id {
            CMD_MOVE_TO => {
                if !current_ring.is_empty() {
                    rings.push(std::mem::take(&mut current_ring));
                }
                for &(x, y) in &cmd.params {
                    current_ring.push(tile_coord_to_geo(x, y, extent, bounds));
                }
            }
            CMD_LINE_TO => {
                for &(x, y) in &cmd.params {
                    current_ring.push(tile_coord_to_geo(x, y, extent, bounds));
                }
            }
            CMD_CLOSE_PATH => {
                if let Some(&first) = current_ring.first() {
                    current_ring.push(first);
                }
                rings.push(std::mem::take(&mut current_ring));
            }
            _ => {}
        }
    }

    if !current_ring.is_empty() {
        rings.push(current_ring);
    }

    rings
}

fn geometry_from_points(rings: Vec<Vec<rustial_math::GeoCoord>>) -> Result<Geometry, MvtError> {
    let points: Vec<Point> = rings
        .into_iter()
        .flat_map(|ring| ring.into_iter().map(|coord| Point { coord }))
        .collect();

    match points.len() {
        0 => Err(MvtError::DecodeError("empty point geometry".into())),
        1 => Ok(Geometry::Point(points.into_iter().next().expect("len==1"))),
        _ => Ok(Geometry::MultiPoint(MultiPoint { points })),
    }
}

fn geometry_from_linestrings(
    rings: Vec<Vec<rustial_math::GeoCoord>>,
) -> Result<Geometry, MvtError> {
    let lines: Vec<LineString> = rings
        .into_iter()
        .filter(|r| r.len() >= 2)
        .map(|coords| LineString { coords })
        .collect();

    match lines.len() {
        0 => Err(MvtError::DecodeError("empty linestring geometry".into())),
        1 => Ok(Geometry::LineString(
            lines.into_iter().next().expect("len==1"),
        )),
        _ => Ok(Geometry::MultiLineString(MultiLineString { lines })),
    }
}

fn geometry_from_polygons(rings: Vec<Vec<rustial_math::GeoCoord>>) -> Result<Geometry, MvtError> {
    if rings.is_empty() {
        return Err(MvtError::DecodeError("empty polygon geometry".into()));
    }

    let mut polygons: Vec<Polygon> = Vec::new();

    for ring in rings {
        if ring.len() < 4 {
            continue;
        }

        let area = signed_ring_area(&ring);

        if area > 0.0 {
            // Positive area = exterior ring (counter-clockwise in screen space
            // = clockwise in geographic = outer ring in MVT spec).
            // Start a new polygon.
            polygons.push(Polygon {
                exterior: ring,
                interiors: Vec::new(),
            });
        } else if area < 0.0 {
            // Negative area = interior ring (hole).
            if let Some(last) = polygons.last_mut() {
                last.interiors.push(ring);
            } else {
                // Orphan hole -- promote to exterior.
                let mut reversed = ring;
                reversed.reverse();
                polygons.push(Polygon {
                    exterior: reversed,
                    interiors: Vec::new(),
                });
            }
        }
        // area == 0 -> degenerate, skip
    }

    match polygons.len() {
        0 => Err(MvtError::DecodeError("no valid polygon rings found".into())),
        1 => Ok(Geometry::Polygon(
            polygons.into_iter().next().expect("len==1"),
        )),
        _ => Ok(Geometry::MultiPolygon(MultiPolygon { polygons })),
    }
}

/// Compute the signed area of a ring using the shoelace formula.
///
/// Positive = counter-clockwise in screen space (MVT exterior ring).
fn signed_ring_area(ring: &[rustial_math::GeoCoord]) -> f64 {
    let mut area = 0.0f64;
    let n = ring.len();
    if n < 3 {
        return 0.0;
    }
    for i in 0..n {
        let j = (i + 1) % n;
        // Using lon as x, lat as y for area computation.
        area += ring[i].lon * ring[j].lat;
        area -= ring[j].lon * ring[i].lat;
    }
    area / 2.0
}

// ---------------------------------------------------------------------------
// Protobuf wire format reader
// ---------------------------------------------------------------------------

/// Protobuf wire types used by MVT.
const WIRE_VARINT: u8 = 0;
const WIRE_64: u8 = 1;
const WIRE_LEN: u8 = 2;
const WIRE_32: u8 = 5;

/// Minimal protobuf reader for MVT decoding.
struct PbReader<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> PbReader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data, pos: 0 }
    }

    #[inline]
    fn remaining(&self) -> usize {
        self.data.len().saturating_sub(self.pos)
    }

    fn read_byte(&mut self) -> Result<u8, MvtError> {
        if self.pos >= self.data.len() {
            return Err(MvtError::TruncatedPayload);
        }
        let b = self.data[self.pos];
        self.pos += 1;
        Ok(b)
    }

    fn read_varint(&mut self) -> Result<u64, MvtError> {
        let mut result: u64 = 0;
        let mut shift: u32 = 0;
        loop {
            let b = self.read_byte()?;
            result |= ((b & 0x7F) as u64) << shift;
            if b & 0x80 == 0 {
                return Ok(result);
            }
            shift += 7;
            if shift >= 64 {
                return Err(MvtError::DecodeError("varint too long".into()));
            }
        }
    }

    fn read_tag(&mut self) -> Result<(u32, u8), MvtError> {
        let varint = self.read_varint()? as u32;
        let field_number = varint >> 3;
        let wire_type = (varint & 0x7) as u8;
        Ok((field_number, wire_type))
    }

    fn read_bytes(&mut self) -> Result<&'a [u8], MvtError> {
        let len = self.read_varint()? as usize;
        if self.pos + len > self.data.len() {
            return Err(MvtError::TruncatedPayload);
        }
        let slice = &self.data[self.pos..self.pos + len];
        self.pos += len;
        Ok(slice)
    }

    fn read_string(&mut self) -> Result<String, MvtError> {
        let bytes = self.read_bytes()?;
        String::from_utf8(bytes.to_vec())
            .map_err(|e| MvtError::DecodeError(format!("invalid UTF-8: {e}")))
    }

    fn read_fixed32_f32(&mut self) -> Result<f32, MvtError> {
        if self.remaining() < 4 {
            return Err(MvtError::TruncatedPayload);
        }
        let bytes = [
            self.data[self.pos],
            self.data[self.pos + 1],
            self.data[self.pos + 2],
            self.data[self.pos + 3],
        ];
        self.pos += 4;
        Ok(f32::from_le_bytes(bytes))
    }

    fn read_fixed64_f64(&mut self) -> Result<f64, MvtError> {
        if self.remaining() < 8 {
            return Err(MvtError::TruncatedPayload);
        }
        let mut bytes = [0u8; 8];
        bytes.copy_from_slice(&self.data[self.pos..self.pos + 8]);
        self.pos += 8;
        Ok(f64::from_le_bytes(bytes))
    }

    fn skip_field(&mut self, wire_type: u8) -> Result<(), MvtError> {
        match wire_type {
            WIRE_VARINT => {
                let _ = self.read_varint()?;
            }
            WIRE_64 => {
                if self.remaining() < 8 {
                    return Err(MvtError::TruncatedPayload);
                }
                self.pos += 8;
            }
            WIRE_LEN => {
                let _ = self.read_bytes()?;
            }
            WIRE_32 => {
                if self.remaining() < 4 {
                    return Err(MvtError::TruncatedPayload);
                }
                self.pos += 4;
            }
            other => return Err(MvtError::UnsupportedWireType(other)),
        }
        Ok(())
    }
}

/// Protobuf zigzag decoding: maps unsigned varint back to signed.
#[inline]
fn zigzag_decode(n: u64) -> i64 {
    ((n >> 1) as i64) ^ -((n & 1) as i64)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- Zigzag decoding --------------------------------------------------

    #[test]
    fn zigzag_decode_positive() {
        assert_eq!(zigzag_decode(0), 0);
        assert_eq!(zigzag_decode(2), 1);
        assert_eq!(zigzag_decode(4), 2);
        assert_eq!(zigzag_decode(100), 50);
    }

    #[test]
    fn zigzag_decode_negative() {
        assert_eq!(zigzag_decode(1), -1);
        assert_eq!(zigzag_decode(3), -2);
        assert_eq!(zigzag_decode(5), -3);
        assert_eq!(zigzag_decode(99), -50);
    }

    // -- PbReader basic operations ----------------------------------------

    #[test]
    fn pb_reader_read_varint_single_byte() {
        let data = [0x08]; // varint 8
        let mut reader = PbReader::new(&data);
        assert_eq!(reader.read_varint().unwrap(), 8);
    }

    #[test]
    fn pb_reader_read_varint_multi_byte() {
        let data = [0xAC, 0x02]; // 300
        let mut reader = PbReader::new(&data);
        assert_eq!(reader.read_varint().unwrap(), 300);
    }

    #[test]
    fn pb_reader_read_tag() {
        // field_number=3, wire_type=2 (length-delimited): (3 << 3) | 2 = 26
        let data = [26];
        let mut reader = PbReader::new(&data);
        let (field, wire) = reader.read_tag().unwrap();
        assert_eq!(field, 3);
        assert_eq!(wire, WIRE_LEN);
    }

    #[test]
    fn pb_reader_read_string() {
        // length=5, then "hello"
        let data = [5, b'h', b'e', b'l', b'l', b'o'];
        let mut reader = PbReader::new(&data);
        assert_eq!(reader.read_string().unwrap(), "hello");
    }

    #[test]
    fn pb_reader_truncated_payload() {
        let data = [0xFF]; // varint continuation but no next byte
        let mut reader = PbReader::new(&data);
        assert!(reader.read_varint().is_err());
    }

    // -- Tile geo bounds --------------------------------------------------

    #[test]
    fn tile_geo_bounds_zoom_0() {
        let bounds = tile_geo_bounds(&TileId::new(0, 0, 0));
        assert!((bounds.west - (-180.0)).abs() < 1e-6);
        assert!((bounds.east - 180.0).abs() < 1e-6);
        assert!(bounds.north > 85.0);
        assert!(bounds.south < -85.0);
    }

    #[test]
    fn tile_geo_bounds_higher_zoom() {
        let bounds = tile_geo_bounds(&TileId::new(1, 0, 0));
        assert!((bounds.west - (-180.0)).abs() < 1e-6);
        assert!((bounds.east - 0.0).abs() < 1e-6);
        assert!(bounds.north > 85.0);
        assert!(bounds.south > -1.0); // north half
    }

    // -- Signed ring area -------------------------------------------------

    #[test]
    fn signed_ring_area_ccw_positive() {
        use rustial_math::GeoCoord;
        // CCW square in lon/lat space
        let ring = vec![
            GeoCoord::from_lat_lon(0.0, 0.0),
            GeoCoord::from_lat_lon(0.0, 1.0),
            GeoCoord::from_lat_lon(1.0, 1.0),
            GeoCoord::from_lat_lon(1.0, 0.0),
            GeoCoord::from_lat_lon(0.0, 0.0),
        ];
        let area = signed_ring_area(&ring);
        assert!(area > 0.0, "CCW ring should have positive area, got {area}");
    }

    #[test]
    fn signed_ring_area_cw_negative() {
        use rustial_math::GeoCoord;
        // CW square
        let ring = vec![
            GeoCoord::from_lat_lon(0.0, 0.0),
            GeoCoord::from_lat_lon(1.0, 0.0),
            GeoCoord::from_lat_lon(1.0, 1.0),
            GeoCoord::from_lat_lon(0.0, 1.0),
            GeoCoord::from_lat_lon(0.0, 0.0),
        ];
        let area = signed_ring_area(&ring);
        assert!(area < 0.0, "CW ring should have negative area, got {area}");
    }

    // -- Coordinate conversion --------------------------------------------

    #[test]
    fn tile_coord_to_geo_corners() {
        let bounds = tile_geo_bounds(&TileId::new(0, 0, 0));
        let nw = tile_coord_to_geo(0, 0, 4096, &bounds);
        assert!((nw.lon - (-180.0)).abs() < 0.01);
        assert!(nw.lat > 85.0);

        let se = tile_coord_to_geo(4096, 4096, 4096, &bounds);
        assert!((se.lon - 180.0).abs() < 0.01);
        assert!(se.lat < -85.0);
    }

    // -- MVT encoding helper for tests ------------------------------------

    fn encode_varint(mut val: u64) -> Vec<u8> {
        let mut buf = Vec::new();
        loop {
            let mut byte = (val & 0x7F) as u8;
            val >>= 7;
            if val != 0 {
                byte |= 0x80;
            }
            buf.push(byte);
            if val == 0 {
                break;
            }
        }
        buf
    }

    fn encode_tag(field_number: u32, wire_type: u8) -> Vec<u8> {
        encode_varint(((field_number as u64) << 3) | wire_type as u64)
    }

    fn encode_len_delimited(field_number: u32, data: &[u8]) -> Vec<u8> {
        let mut buf = encode_tag(field_number, WIRE_LEN);
        buf.extend(encode_varint(data.len() as u64));
        buf.extend_from_slice(data);
        buf
    }

    fn encode_string_field(field_number: u32, s: &str) -> Vec<u8> {
        encode_len_delimited(field_number, s.as_bytes())
    }

    fn encode_varint_field(field_number: u32, val: u64) -> Vec<u8> {
        let mut buf = encode_tag(field_number, WIRE_VARINT);
        buf.extend(encode_varint(val));
        buf
    }

    fn zigzag_encode(n: i32) -> u32 {
        ((n << 1) ^ (n >> 31)) as u32
    }

    fn encode_geometry_commands(commands: &[(u32, &[(i32, i32)])]) -> Vec<u8> {
        let mut buf = Vec::new();
        for &(cmd_id, params) in commands {
            let count = if cmd_id == CMD_CLOSE_PATH {
                1u32
            } else {
                params.len() as u32
            };
            buf.extend(encode_varint(((count as u64) << 3) | cmd_id as u64));
            for &(dx, dy) in params {
                buf.extend(encode_varint(zigzag_encode(dx) as u64));
                buf.extend(encode_varint(zigzag_encode(dy) as u64));
            }
        }
        buf
    }

    fn build_mvt_value_string(s: &str) -> Vec<u8> {
        encode_string_field(1, s)
    }

    fn build_mvt_value_double(v: f64) -> Vec<u8> {
        let mut buf = encode_tag(3, WIRE_64);
        buf.extend(v.to_le_bytes());
        buf
    }

    fn build_mvt_feature(
        id: Option<u64>,
        geom_type: u32,
        tags: &[u32],
        geometry: &[u8],
    ) -> Vec<u8> {
        let mut buf = Vec::new();
        if let Some(id) = id {
            buf.extend(encode_varint_field(1, id));
        }
        if !tags.is_empty() {
            let mut tags_buf = Vec::new();
            for &t in tags {
                tags_buf.extend(encode_varint(t as u64));
            }
            buf.extend(encode_len_delimited(2, &tags_buf));
        }
        buf.extend(encode_varint_field(3, geom_type as u64));
        buf.extend(encode_len_delimited(4, geometry));
        buf
    }

    fn build_mvt_layer(
        name: &str,
        features: &[Vec<u8>],
        keys: &[&str],
        values: &[Vec<u8>],
        extent: u32,
    ) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.extend(encode_string_field(1, name));
        for feat in features {
            buf.extend(encode_len_delimited(2, feat));
        }
        for key in keys {
            buf.extend(encode_string_field(3, key));
        }
        for val in values {
            buf.extend(encode_len_delimited(4, val));
        }
        buf.extend(encode_varint_field(5, extent as u64));
        buf.extend(encode_varint_field(15, 2)); // version = 2
        buf
    }

    fn build_mvt_tile(layers: &[Vec<u8>]) -> Vec<u8> {
        let mut buf = Vec::new();
        for layer in layers {
            buf.extend(encode_len_delimited(3, layer));
        }
        buf
    }

    // -- Full MVT decode --------------------------------------------------

    #[test]
    fn decode_empty_tile() {
        let bytes = build_mvt_tile(&[]);
        let result = decode_mvt(&bytes, &TileId::new(0, 0, 0), &MvtDecodeOptions::default());
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn decode_point_feature() {
        // A point at tile-local coords (2048, 2048) = center of tile
        let geom = encode_geometry_commands(&[(CMD_MOVE_TO, &[(2048, 2048)])]);
        let feature = build_mvt_feature(Some(42), GEOM_POINT, &[], &geom);
        let layer = build_mvt_layer("points", &[feature], &[], &[], 4096);
        let tile = build_mvt_tile(&[layer]);

        let tile_id = TileId::new(0, 0, 0);
        let result = decode_mvt(&tile, &tile_id, &MvtDecodeOptions::default()).unwrap();

        assert_eq!(result.len(), 1);
        let features = &result["points"];
        assert_eq!(features.len(), 1);

        match &features.features[0].geometry {
            Geometry::Point(pt) => {
                // Center of zoom-0 tile should be roughly (0, 0)
                assert!(pt.coord.lon.abs() < 1.0);
                assert!(pt.coord.lat.abs() < 1.0);
            }
            other => panic!("expected Point, got {}", other.type_name()),
        }

        // Check feature id
        let id_prop = features.features[0].property("$id");
        assert_eq!(id_prop.and_then(|v| v.as_f64()), Some(42.0));
    }

    #[test]
    fn decode_linestring_feature() {
        let geom = encode_geometry_commands(&[
            (CMD_MOVE_TO, &[(0, 0)]),
            (CMD_LINE_TO, &[(4096, 0), (0, 4096)]),
        ]);
        let feature = build_mvt_feature(None, GEOM_LINESTRING, &[], &geom);
        let layer = build_mvt_layer("roads", &[feature], &[], &[], 4096);
        let tile = build_mvt_tile(&[layer]);

        let tile_id = TileId::new(0, 0, 0);
        let result = decode_mvt(&tile, &tile_id, &MvtDecodeOptions::default()).unwrap();

        let features = &result["roads"];
        assert_eq!(features.len(), 1);
        match &features.features[0].geometry {
            Geometry::LineString(ls) => {
                assert_eq!(ls.coords.len(), 3);
            }
            other => panic!("expected LineString, got {}", other.type_name()),
        }
    }

    #[test]
    fn decode_polygon_feature() {
        // Exterior ring (CW in screen space = positive area in MVT convention)
        let geom = encode_geometry_commands(&[
            (CMD_MOVE_TO, &[(0, 0)]),
            (CMD_LINE_TO, &[(4096, 0), (0, 4096), (-4096, 0)]),
            (CMD_CLOSE_PATH, &[]),
        ]);
        let feature = build_mvt_feature(None, GEOM_POLYGON, &[], &geom);
        let layer = build_mvt_layer("water", &[feature], &[], &[], 4096);
        let tile = build_mvt_tile(&[layer]);

        let tile_id = TileId::new(0, 0, 0);
        let result = decode_mvt(&tile, &tile_id, &MvtDecodeOptions::default()).unwrap();

        let features = &result["water"];
        assert_eq!(features.len(), 1);
        match &features.features[0].geometry {
            Geometry::Polygon(poly) => {
                assert!(poly.exterior.len() >= 4, "polygon should have 4+ vertices");
                assert!(poly.interiors.is_empty());
            }
            other => panic!("expected Polygon, got {}", other.type_name()),
        }
    }

    #[test]
    fn decode_feature_with_properties() {
        let geom = encode_geometry_commands(&[(CMD_MOVE_TO, &[(100, 100)])]);
        let keys = &["name", "population"];
        let values = &[
            build_mvt_value_string("Springfield"),
            build_mvt_value_double(12345.0),
        ];
        // tags: key_idx=0, val_idx=0, key_idx=1, val_idx=1
        let feature = build_mvt_feature(None, GEOM_POINT, &[0, 0, 1, 1], &geom);
        let layer = build_mvt_layer("places", &[feature], keys, values, 4096);
        let tile = build_mvt_tile(&[layer]);

        let tile_id = TileId::new(1, 0, 0);
        let result = decode_mvt(&tile, &tile_id, &MvtDecodeOptions::default()).unwrap();

        let features = &result["places"];
        assert_eq!(features.len(), 1);
        let props = &features.features[0].properties;
        assert_eq!(
            props.get("name").and_then(|v| v.as_str()),
            Some("Springfield")
        );
        assert_eq!(
            props.get("population").and_then(|v| v.as_f64()),
            Some(12345.0)
        );
    }

    #[test]
    fn decode_with_layer_filter() {
        let geom = encode_geometry_commands(&[(CMD_MOVE_TO, &[(100, 100)])]);
        let feat = build_mvt_feature(None, GEOM_POINT, &[], &geom);
        let layer_a = build_mvt_layer("water", std::slice::from_ref(&feat), &[], &[], 4096);
        let layer_b = build_mvt_layer("roads", &[feat], &[], &[], 4096);
        let tile = build_mvt_tile(&[layer_a, layer_b]);

        let options = MvtDecodeOptions {
            layer_filter: vec!["water".into()],
        };
        let tile_id = TileId::new(0, 0, 0);
        let result = decode_mvt(&tile, &tile_id, &options).unwrap();

        assert_eq!(result.len(), 1);
        assert!(result.contains_key("water"));
        assert!(!result.contains_key("roads"));
    }

    #[test]
    fn decode_multi_point_feature() {
        let geom = encode_geometry_commands(&[(CMD_MOVE_TO, &[(100, 100), (200, 200)])]);
        let feature = build_mvt_feature(None, GEOM_POINT, &[], &geom);
        let layer = build_mvt_layer("multi", &[feature], &[], &[], 4096);
        let tile = build_mvt_tile(&[layer]);

        let tile_id = TileId::new(0, 0, 0);
        let result = decode_mvt(&tile, &tile_id, &MvtDecodeOptions::default()).unwrap();
        match &result["multi"].features[0].geometry {
            Geometry::MultiPoint(mp) => {
                assert_eq!(mp.points.len(), 2);
            }
            other => panic!("expected MultiPoint, got {}", other.type_name()),
        }
    }

    #[test]
    fn mvt_error_display() {
        assert!(MvtError::TruncatedPayload.to_string().contains("truncated"));
        assert!(MvtError::UnsupportedWireType(6).to_string().contains("6"));
        assert!(MvtError::InvalidGeometryCommand(99)
            .to_string()
            .contains("99"));
    }
}