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
//! # mvt-reader
//!
//! `mvt-reader` is a Rust library for decoding and reading Mapbox vector tiles.
//!
//! It provides the `Reader` struct, which allows you to read vector tiles and access their layers and features.
//!
//! # Usage
//!
//! To use the `mvt-reader` library in your Rust project, add the following to your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies]
//! mvt-reader = "1.3.0"
//! ```
//!
//! Then, you can import and use the library in your code:
//!
//! ```rust
//! use mvt_reader::{Reader, error::{ParserError}};
//!
//! fn main() -> Result<(), ParserError> {
//!   // Read a vector tile from file or data
//!   let data = vec![/* Vector tile data */];
//!   let reader = Reader::new(data)?;
//!
//!   // Get layer names
//!   let layer_names = reader.get_layer_names()?;
//!   for name in layer_names {
//!     println!("Layer: {}", name);
//!   }
//!
//!   // Get features for a specific layer
//!   let layer_index = 0;
//!   let features = reader.get_features(layer_index)?;
//!   for feature in features {
//!     todo!()
//!   }
//!
//!   Ok(())
//! }
//! ```
//!
//! # Features
//!
//! The `mvt-reader` library provides the following features:
//!
//! - `wasm`: Enables the compilation of the library as a WebAssembly module, allowing usage in JavaScript/TypeScript projects.
//!
//! To enable the `wasm` feature, add the following to your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies.mvt-reader]
//! version = "1.2.0"
//! features = ["wasm"]
//! ```
//!
//! # License
//!
//! This project is licensed under the [MIT License](https://github.com/codeart1st/mvt-reader/blob/main/LICENSE).

pub mod error;
pub mod feature;

mod vector_tile;

use feature::Feature;
use geo_types::{
  Coord, Geometry, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon,
};
use prost::{bytes::Bytes, Message};
use vector_tile::{tile::GeomType, Tile};

/// The dimension used for the vector tile.
const DIMENSION: u32 = 2;

/// Reader for decoding and accessing vector tile data.
pub struct Reader {
  tile: Tile,
}

impl Reader {
  /// Creates a new `Reader` instance with the provided vector tile data.
  ///
  /// # Arguments
  ///
  /// * `data` - The vector tile data as a byte vector.
  ///
  /// # Returns
  ///
  /// A result containing the `Reader` instance if successful, or a `DecodeError` if decoding the vector tile data fails.
  ///
  /// # Examples
  ///
  /// ```
  /// use mvt_reader::Reader;
  ///
  /// let data = vec![/* Vector tile data */];
  /// let reader = Reader::new(data);
  /// ```
  pub fn new(data: Vec<u8>) -> Result<Self, error::ParserError> {
    match Tile::decode(Bytes::from(data)) {
      Ok(tile) => Ok(Self { tile }),
      Err(error) => Err(error::ParserError::new(error::DecodeError::new(error))),
    }
  }

  /// Retrieves the names of the layers in the vector tile.
  ///
  /// # Returns
  ///
  /// A result containing a vector of layer names if successful, or a `ParserError` if there is an error parsing the tile.
  ///
  /// # Examples
  ///
  /// ```
  /// use mvt_reader::Reader;
  ///
  /// let data = vec![/* Vector tile data */];
  /// let reader = Reader::new(data).unwrap();
  ///
  /// match reader.get_layer_names() {
  ///   Ok(layer_names) => {
  ///     for name in layer_names {
  ///       println!("Layer: {}", name);
  ///     }
  ///   }
  ///   Err(error) => {
  ///     todo!();
  ///   }
  /// }
  /// ```
  pub fn get_layer_names(&self) -> Result<Vec<String>, error::ParserError> {
    let mut layer_names = Vec::with_capacity(self.tile.layers.len());
    for layer in self.tile.layers.iter() {
      match layer.version {
        1 | 2 => {
          layer_names.push(layer.name.clone());
        }
        _ => {
          return Err(error::ParserError::new(error::VersionError::new(
            layer.name.clone(),
            layer.version,
          )))
        }
      }
    }
    Ok(layer_names)
  }

  /// Retrieves the features of a specific layer in the vector tile.
  ///
  /// # Arguments
  ///
  /// * `layer_index` - The index of the layer.
  ///
  /// # Returns
  ///
  /// A result containing a vector of features if successful, or a `ParserError` if there is an error parsing the tile or accessing the layer.
  ///
  /// # Examples
  ///
  /// ```
  /// use mvt_reader::Reader;
  ///
  /// let data = vec![/* Vector tile data */];
  /// let reader = Reader::new(data).unwrap();
  ///
  /// match reader.get_features(0) {
  ///   Ok(features) => {
  ///     for feature in features {
  ///       todo!();
  ///     }
  ///   }
  ///   Err(error) => {
  ///     todo!();
  ///   }
  /// }
  /// ```
  pub fn get_features(&self, layer_index: usize) -> Result<Vec<Feature>, error::ParserError> {
    let layer = self.tile.layers.get(layer_index);
    match layer {
      Some(layer) => {
        let mut features = Vec::with_capacity(layer.features.len());
        for feature in layer.features.iter() {
          if let Some(geom_type) = feature.r#type {
            match GeomType::try_from(geom_type) {
              Ok(geom_type) => {
                let parsed_geometry = match parse_geometry(&feature.geometry, geom_type) {
                  Ok(parsed_geometry) => parsed_geometry,
                  Err(error) => {
                    return Err(error);
                  }
                };

                let parsed_tags = match parse_tags(&feature.tags, &layer.keys, &layer.values) {
                  Ok(parsed_tags) => parsed_tags,
                  Err(error) => {
                    return Err(error);
                  }
                };

                features.push(Feature {
                  geometry: parsed_geometry,
                  properties: Some(parsed_tags),
                });
              }
              Err(error) => return Err(error::ParserError::new(error::DecodeError::new(error))),
            }
          }
        }
        Ok(features)
      }
      None => Ok(vec![]),
    }
  }
}

fn parse_tags(
  tags: &[u32],
  keys: &[String],
  values: &[vector_tile::tile::Value],
) -> Result<std::collections::HashMap<String, String>, error::ParserError> {
  let mut result = std::collections::HashMap::new();
  for item in tags.chunks(2) {
    if item.len() != 2
      || item[0] > keys.len().try_into().unwrap()
      || item[1] > values.len().try_into().unwrap()
    {
      return Err(error::ParserError::new(error::TagsError::new()));
    }
    result.insert(
      (*keys.get(item[0] as usize).expect("item not found")).clone(),
      get_string_value((*values.get(item[1] as usize).expect("item not found")).clone()),
    );
  }
  Ok(result)
}

fn get_string_value(value: vector_tile::tile::Value) -> String {
  if value.string_value.is_some() {
    return value.string_value.unwrap();
  }
  if value.float_value.is_some() {
    return value.float_value.unwrap().to_string();
  }
  if value.double_value.is_some() {
    return value.double_value.unwrap().to_string();
  }
  if value.int_value.is_some() {
    return value.int_value.unwrap().to_string();
  }
  if value.uint_value.is_some() {
    return value.uint_value.unwrap().to_string();
  }
  if value.sint_value.is_some() {
    return value.sint_value.unwrap().to_string();
  }
  if value.bool_value.is_some() {
    return value.bool_value.unwrap().to_string();
  }
  String::new()
}

fn shoelace_formula(points: &[Point<f32>]) -> f32 {
  let mut area: f32 = 0.0;
  let n = points.len();
  let mut v1 = points[n - 1];
  for v2 in points.iter().take(n) {
    area += (v2.y() - v1.y()) * (v2.x() + v1.x());
    v1 = *v2;
  }
  area * 0.5
}

fn parse_geometry(
  geometry_data: &[u32],
  geom_type: GeomType,
) -> Result<Geometry<f32>, error::ParserError> {
  if geom_type == GeomType::Unknown {
    return Err(error::ParserError::new(error::GeometryError::new()));
  }

  // worst case capacity to prevent reallocation. not needed to be exact.
  let mut coordinates: Vec<Coord<f32>> = Vec::with_capacity(geometry_data.len());
  let mut polygons: Vec<Polygon<f32>> = Vec::new();
  let mut linestrings: Vec<LineString<f32>> = Vec::new();

  let mut cursor: [i32; 2] = [0, 0];
  let mut parameter_count: u32 = 0;

  for (_, value) in geometry_data.iter().enumerate() {
    if parameter_count == 0 {
      let command_integer = value;
      let id = (command_integer & 0x7) as u8;
      match id {
        1 => {
          // MoveTo
          parameter_count = (command_integer >> 3) * DIMENSION;
          if geom_type == GeomType::Linestring && !coordinates.is_empty() {
            linestrings.push(LineString::new(coordinates));
            // start with a new linestring
            coordinates = Vec::with_capacity(geometry_data.len());
          }
        }
        2 => {
          // LineTo
          parameter_count = (command_integer >> 3) * DIMENSION;
        }
        7 => {
          // ClosePath
          let first_coordinate = match coordinates.first() {
            Some(coord) => coord.to_owned(),
            None => {
              return Err(error::ParserError::new(error::GeometryError::new()));
            }
          };
          coordinates.push(first_coordinate);

          let ring = LineString::new(coordinates);

          let area = shoelace_formula(&ring.clone().into_points());

          if area > 0.0 {
            // exterior ring
            if !linestrings.is_empty() {
              // finish previous geometry
              polygons.push(Polygon::new(
                linestrings[0].clone(),
                linestrings[1..].into(),
              ));
              linestrings = Vec::new();
            }
          }

          linestrings.push(ring);
          // start a new sequence
          coordinates = Vec::with_capacity(geometry_data.len());
        }
        _ => (),
      }
    } else {
      let parameter_integer = value;
      let integer_value = ((parameter_integer >> 1) as i32) ^ -((parameter_integer & 1) as i32);
      if parameter_count % DIMENSION == 0 {
        cursor[0] = match cursor[0].checked_add(integer_value) {
          Some(result) => result,
          None => std::i32::MAX, // clip value
        };
      } else {
        cursor[1] = match cursor[1].checked_add(integer_value) {
          Some(result) => result,
          None => std::i32::MAX, // clip value
        };
        coordinates.push(Coord {
          x: cursor[0] as f32,
          y: cursor[1] as f32,
        });
      }
      parameter_count -= 1;
    }
  }

  match geom_type {
    GeomType::Linestring => {
      // the last linestring is in coordinates vec
      if !linestrings.is_empty() {
        linestrings.push(LineString::new(coordinates));
        return Ok(MultiLineString::new(linestrings).into());
      }
      Ok(LineString::new(coordinates).into())
    }
    GeomType::Point => Ok(
      MultiPoint(
        coordinates
          .iter()
          .map(|coord| Point::new(coord.x, coord.y))
          .collect(),
      )
      .into(),
    ),
    GeomType::Polygon => {
      if !linestrings.is_empty() {
        // finish pending polygon
        polygons.push(Polygon::new(
          linestrings[0].clone(),
          linestrings[1..].into(),
        ));
        return Ok(MultiPolygon::new(polygons).into());
      }
      Ok(polygons.get(0).unwrap().to_owned().into())
    }
    GeomType::Unknown => Err(error::ParserError::new(error::GeometryError::new())),
  }
}

#[cfg(feature = "wasm")]
pub mod wasm {

  use geojson::{Feature, GeoJson, JsonObject};
  use serde::Serialize;
  use serde_wasm_bindgen::Serializer;
  use wasm_bindgen::prelude::*;

  /// Converts a `super::feature::Feature` into a `wasm_bindgen::JsValue`.
  impl From<super::feature::Feature> for wasm_bindgen::JsValue {
    fn from(feature: super::feature::Feature) -> Self {
      let properties: Option<JsonObject> = feature.properties.as_ref().map(|props| {
        props
          .clone()
          .into_iter()
          .map(|(k, v)| (k, v.into()))
          .collect()
      });

      let geojson = GeoJson::Feature(Feature {
        bbox: None,
        geometry: Some(feature.get_geometry().into()),
        id: None,
        properties,
        foreign_members: None,
      });

      geojson.serialize(&Serializer::json_compatible()).unwrap()
    }
  }

  /// Reader for decoding and accessing vector tile data in WebAssembly.
  #[wasm_bindgen]
  pub struct Reader {
    reader: Option<super::Reader>,
  }

  #[wasm_bindgen]
  impl Reader {
    /// Creates a new `Reader` instance with the provided vector tile data.
    ///
    /// # Arguments
    ///
    /// * `data` - The vector tile data as a `Vec<u8>`.
    /// * `error_callback` - An optional JavaScript callback function to handle errors. It should accept a single parameter which will contain the error message as a string.
    ///
    /// # Examples
    ///
    /// ```
    /// let tileData = getVectorTileData();
    /// let reader = new Reader(tileData, handleErrors);
    /// ```
    #[wasm_bindgen(constructor)]
    pub fn new(data: Vec<u8>, error_callback: Option<js_sys::Function>) -> Reader {
      let reader = match super::Reader::new(data) {
        Ok(reader) => Some(reader),
        Err(error) => {
          if let Some(callback) = error_callback {
            callback
              .call1(&JsValue::NULL, &JsValue::from_str(&format!("{:?}", error)))
              .unwrap();
          }
          None
        }
      };
      Reader { reader }
    }

    /// Retrieves the layer names present in the vector tile.
    ///
    /// # Arguments
    ///
    /// * `error_callback` - An optional JavaScript callback function to handle errors. It should accept a single parameter which will contain the error message as a string.
    ///
    /// # Returns
    ///
    /// A JavaScript array containing the layer names as strings.
    ///
    /// # Examples
    ///
    /// ```
    /// let layerNames = reader.getLayerNames(handleErrors);
    /// for (let i = 0; i < layerNames.length; i++) {
    ///   console.log(layerNames[i]);
    /// }
    /// ```
    #[wasm_bindgen(js_name = getLayerNames)]
    pub fn get_layer_names(&self, error_callback: Option<js_sys::Function>) -> JsValue {
      match &self.reader {
        Some(reader) => match reader.get_layer_names() {
          Ok(layer_names) => JsValue::from(
            layer_names
              .into_iter()
              .map(JsValue::from)
              .collect::<js_sys::Array>(),
          ),
          Err(error) => {
            if let Some(callback) = error_callback {
              callback
                .call1(&JsValue::NULL, &JsValue::from_str(&format!("{:?}", error)))
                .unwrap();
            }
            JsValue::NULL
          }
        },
        None => JsValue::NULL,
      }
    }

    /// Retrieves the features of a specific layer in the vector tile.
    ///
    /// # Arguments
    ///
    /// * `layer_index` - The index of the layer to retrieve features from.
    /// * `error_callback` - An optional JavaScript callback function to handle errors. It should accept a single parameter which will contain the error message as a string.
    ///
    /// # Returns
    ///
    /// A JavaScript array containing the features as GeoJSON objects.
    ///
    /// # Examples
    ///
    /// ```
    /// let features = reader.getFeatures(0, handleErrors);
    /// for (let i = 0; i < features.length; i++) {
    ///   console.log(features[i]);
    /// }
    /// ```
    #[wasm_bindgen(js_name = getFeatures)]
    pub fn get_features(
      &self,
      layer_index: usize,
      error_callback: Option<js_sys::Function>,
    ) -> JsValue {
      match &self.reader {
        Some(reader) => match reader.get_features(layer_index) {
          Ok(features) => JsValue::from(
            features
              .into_iter()
              .map(JsValue::from)
              .collect::<js_sys::Array>(),
          ),
          Err(error) => {
            if let Some(callback) = error_callback {
              callback
                .call1(&JsValue::NULL, &JsValue::from_str(&format!("{:?}", error)))
                .unwrap();
            }
            JsValue::NULL
          }
        },
        None => JsValue::NULL,
      }
    }
  }
}