Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-tiler/src/mvt.rs10// Module : server11// Repository : https://git.spboucher.ai/ka-maps-engine12// Created : 2026-12-0113// Last Modified : 2026-12-0114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687//! Encodeur et décodeur Mapbox Vector Tile 2.1 maison (protobuf écrit à la main), plus lecture du WKB88//! renvoyé par PostGIS (géométries déjà en coordonnées de tuile par ST_AsMVTGeom).89//!90//! Règles appliquées ici (docs/TILE_ENGINE.md) : anneaux extérieurs d'aire positive (formule du géomètre,91//! axe y vers le bas), anneaux intérieurs d'aire négative, polygones de moins de `MIN_POLY_AREA` unités²92//! écartés, points consécutifs identiques supprimés, lignes dégénérées écartées.9394use std::collections::HashMap;9596pub const MIN_POLY_AREA: f64 = 4.0;9798#[derive(Clone, Debug, PartialEq)]99pub enum Value {100 Str(String),101 Int(i64),102 Double(f64),103 Bool(bool),104}105106#[derive(Clone, Debug, PartialEq)]107pub enum Geom {108 Points(Vec<(i32, i32)>),109 Lines(Vec<Vec<(i32, i32)>>),110 /// Liste de polygones ; chaque polygone = anneau extérieur puis trous.111 Polygons(Vec<Vec<Vec<(i32, i32)>>>),112}113114impl Geom {115 pub fn is_empty(&self) -> bool {116 match self {117 Geom::Points(p) => p.is_empty(),118 Geom::Lines(l) => l.is_empty(),119 Geom::Polygons(p) => p.is_empty(),120 }121 }122}123124// ------------------------------------------------------------------------------------------- WKB125126struct Rd<'a> {127 b: &'a [u8],128 p: usize,129}130131impl<'a> Rd<'a> {132 fn u8(&mut self) -> Option<u8> {133 let v = *self.b.get(self.p)?;134 self.p += 1;135 Some(v)136 }137 fn u32(&mut self, le: bool) -> Option<u32> {138 let s = self.b.get(self.p..self.p + 4)?;139 self.p += 4;140 let a = [s[0], s[1], s[2], s[3]];141 Some(if le { u32::from_le_bytes(a) } else { u32::from_be_bytes(a) })142 }143 fn f64(&mut self, le: bool) -> Option<f64> {144 let s = self.b.get(self.p..self.p + 8)?;145 self.p += 8;146 let mut a = [0u8; 8];147 a.copy_from_slice(s);148 Some(if le { f64::from_le_bytes(a) } else { f64::from_be_bytes(a) })149 }150}151152fn rd_point(r: &mut Rd, le: bool, dims: usize) -> Option<(i32, i32)> {153 let x = r.f64(le)?;154 let y = r.f64(le)?;155 for _ in 2..dims {156 r.f64(le)?;157 }158 if !x.is_finite() || !y.is_finite() {159 return None;160 }161 Some((x.round() as i32, y.round() as i32))162}163164fn rd_seq(r: &mut Rd, le: bool, dims: usize) -> Option<Vec<(i32, i32)>> {165 let n = r.u32(le)? as usize;166 if n > r.b.len() / 16 + 1 {167 return None;168 }169 let mut v = Vec::with_capacity(n);170 for _ in 0..n {171 let p = rd_point(r, le, dims)?;172 if v.last() != Some(&p) {173 v.push(p);174 }175 }176 Some(v)177}178179#[derive(Default)]180struct Acc {181 points: Vec<(i32, i32)>,182 lines: Vec<Vec<(i32, i32)>>,183 polys: Vec<Vec<Vec<(i32, i32)>>>,184}185186fn rd_geom(r: &mut Rd, acc: &mut Acc, depth: u8) -> Option<()> {187 if depth > 4 {188 return None;189 }190 let le = r.u8()? == 1;191 let mut ty = r.u32(le)?;192 let mut dims = 2;193 // EWKB : drapeaux Z/M/SRID ; ISO : +1000/+2000/+3000194 if ty & 0x2000_0000 != 0 {195 r.u32(le)?;196 }197 if ty & 0x8000_0000 != 0 {198 dims += 1;199 }200 if ty & 0x4000_0000 != 0 {201 dims += 1;202 }203 ty &= 0x0fff_ffff;204 if ty >= 1000 {205 dims += if ty / 1000 == 3 { 2 } else { 1 };206 ty %= 1000;207 }208 match ty {209 1 => {210 // POINT EMPTY = NaN NaN211 let x = r.f64(le)?;212 let y = r.f64(le)?;213 for _ in 2..dims {214 r.f64(le)?;215 }216 if x.is_finite() && y.is_finite() {217 acc.points.push((x.round() as i32, y.round() as i32));218 }219 }220 2 => {221 let l = rd_seq(r, le, dims)?;222 if l.len() >= 2 {223 acc.lines.push(l);224 }225 }226 3 => {227 let n = r.u32(le)? as usize;228 let mut rings = Vec::with_capacity(n.min(64));229 for _ in 0..n {230 rings.push(rd_seq(r, le, dims)?);231 }232 acc.polys.push(rings);233 }234 4..=7 => {235 let n = r.u32(le)?;236 for _ in 0..n {237 rd_geom(r, acc, depth + 1)?;238 }239 }240 _ => return None,241 }242 Some(())243}244245/// Aire signée (formule du géomètre) d'un anneau fermé ou non.246pub fn ring_area(ring: &[(i32, i32)]) -> f64 {247 let n = ring.len();248 if n < 3 {249 return 0.0;250 }251 let mut a: i64 = 0;252 for i in 0..n {253 let (x1, y1) = ring[i];254 let (x2, y2) = ring[(i + 1) % n];255 a += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64;256 }257 a as f64 / 2.0258}259260/// Nettoie un anneau : retire le point de fermeture répété, vérifie ≥ 3 sommets.261fn clean_ring(mut ring: Vec<(i32, i32)>) -> Option<Vec<(i32, i32)>> {262 if ring.len() >= 2 && ring.first() == ring.last() {263 ring.pop();264 }265 if ring.len() < 3 {266 return None;267 }268 Some(ring)269}270271/// Convertit le WKB PostGIS en géométrie MVT. Le type dominant l'emporte (polygones > lignes > points).272pub fn geom_from_wkb(wkb: &[u8]) -> Option<Geom> {273 let mut r = Rd { b: wkb, p: 0 };274 let mut acc = Acc::default();275 rd_geom(&mut r, &mut acc, 0)?;276 if !acc.polys.is_empty() {277 let mut out = Vec::with_capacity(acc.polys.len());278 for rings in acc.polys {279 let mut it = rings.into_iter();280 let Some(ext) = it.next().and_then(clean_ring) else { continue };281 let a = ring_area(&ext);282 if a.abs() < MIN_POLY_AREA {283 continue;284 }285 let mut poly = Vec::new();286 let mut ext = ext;287 if a < 0.0 {288 ext.reverse();289 }290 poly.push(ext);291 for hole in it {292 let Some(mut h) = clean_ring(hole) else { continue };293 let ha = ring_area(&h);294 if ha.abs() < MIN_POLY_AREA {295 continue;296 }297 if ha > 0.0 {298 h.reverse();299 }300 poly.push(h);301 }302 out.push(poly);303 }304 if out.is_empty() {305 return None;306 }307 return Some(Geom::Polygons(out));308 }309 if !acc.lines.is_empty() {310 return Some(Geom::Lines(acc.lines));311 }312 if !acc.points.is_empty() {313 return Some(Geom::Points(acc.points));314 }315 None316}317318// ------------------------------------------------------------------------------------------- protobuf319320pub fn put_varint(out: &mut Vec<u8>, mut v: u64) {321 while v >= 0x80 {322 out.push((v as u8) | 0x80);323 v >>= 7;324 }325 out.push(v as u8);326}327328#[inline]329fn zigzag(v: i64) -> u64 {330 ((v << 1) ^ (v >> 63)) as u64331}332333fn put_tag(out: &mut Vec<u8>, field: u32, wire: u8) {334 put_varint(out, ((field as u64) << 3) | wire as u64);335}336337fn put_bytes(out: &mut Vec<u8>, field: u32, b: &[u8]) {338 put_tag(out, field, 2);339 put_varint(out, b.len() as u64);340 out.extend_from_slice(b);341}342343// ------------------------------------------------------------------------------------------- encodeur344345#[derive(Hash, PartialEq, Eq)]346enum VKey {347 S(String),348 I(i64),349 D(u64),350 B(bool),351}352353pub struct LayerBuilder {354 name: String,355 extent: u32,356 keys: Vec<String>,357 key_ix: HashMap<String, u32>,358 values: Vec<Value>,359 val_ix: HashMap<VKey, u32>,360 features: Vec<u8>,361 pub count: usize,362}363364impl LayerBuilder {365 pub fn new(name: &str, extent: u32) -> Self {366 LayerBuilder {367 name: name.to_string(),368 extent,369 keys: Vec::new(),370 key_ix: HashMap::new(),371 values: Vec::new(),372 val_ix: HashMap::new(),373 features: Vec::new(),374 count: 0,375 }376 }377378 fn key(&mut self, k: &str) -> u32 {379 if let Some(&i) = self.key_ix.get(k) {380 return i;381 }382 let i = self.keys.len() as u32;383 self.keys.push(k.to_string());384 self.key_ix.insert(k.to_string(), i);385 i386 }387388 fn value(&mut self, v: &Value) -> u32 {389 let k = match v {390 Value::Str(s) => VKey::S(s.clone()),391 Value::Int(i) => VKey::I(*i),392 Value::Double(d) => VKey::D(d.to_bits()),393 Value::Bool(b) => VKey::B(*b),394 };395 if let Some(&i) = self.val_ix.get(&k) {396 return i;397 }398 let i = self.values.len() as u32;399 self.values.push(v.clone());400 self.val_ix.insert(k, i);401 i402 }403404 /// Ajoute une entité. Renvoie `false` si la géométrie est vide (rien n'est écrit).405 pub fn add(&mut self, geom: &Geom, attrs: &[(&str, Value)]) -> bool {406 let (gtype, cmds) = encode_geometry(geom);407 if cmds.is_empty() {408 return false;409 }410 let mut tags: Vec<u8> = Vec::with_capacity(attrs.len() * 2);411 for (k, v) in attrs {412 let ki = self.key(k);413 let vi = self.value(v);414 put_varint(&mut tags, ki as u64);415 put_varint(&mut tags, vi as u64);416 }417 let mut gbytes: Vec<u8> = Vec::with_capacity(cmds.len() * 2);418 for c in &cmds {419 put_varint(&mut gbytes, *c as u64);420 }421 let mut f: Vec<u8> = Vec::with_capacity(tags.len() + gbytes.len() + 8);422 if !tags.is_empty() {423 put_bytes(&mut f, 2, &tags);424 }425 put_tag(&mut f, 3, 0);426 put_varint(&mut f, gtype as u64);427 put_bytes(&mut f, 4, &gbytes);428 put_bytes(&mut self.features, 2, &f);429 self.count += 1;430 true431 }432433 pub fn is_empty(&self) -> bool {434 self.count == 0435 }436437 pub fn name(&self) -> &str {438 &self.name439 }440441 /// Sérialise le message `Layer` (sans l'enveloppe `Tile.layers`).442 pub fn finish(self) -> Vec<u8> {443 let mut l: Vec<u8> = Vec::with_capacity(self.features.len() + 256);444 put_tag(&mut l, 15, 0);445 put_varint(&mut l, 2); // version446 put_bytes(&mut l, 1, self.name.as_bytes());447 l.extend_from_slice(&self.features);448 for k in &self.keys {449 put_bytes(&mut l, 3, k.as_bytes());450 }451 for v in &self.values {452 let mut vb = Vec::new();453 match v {454 Value::Str(s) => put_bytes(&mut vb, 1, s.as_bytes()),455 Value::Double(d) => {456 put_tag(&mut vb, 3, 1);457 vb.extend_from_slice(&d.to_le_bytes());458 }459 Value::Int(i) => {460 if *i >= 0 {461 put_tag(&mut vb, 5, 0); // uint_value462 put_varint(&mut vb, *i as u64);463 } else {464 put_tag(&mut vb, 6, 0); // sint_value465 put_varint(&mut vb, zigzag(*i));466 }467 }468 Value::Bool(b) => {469 put_tag(&mut vb, 7, 0);470 put_varint(&mut vb, *b as u64);471 }472 }473 put_bytes(&mut l, 4, &vb);474 }475 put_tag(&mut l, 5, 0);476 put_varint(&mut l, self.extent as u64);477 l478 }479}480481/// Assemble les couches en un message `Tile`.482pub fn assemble(layers: Vec<Vec<u8>>) -> Vec<u8> {483 let mut t = Vec::with_capacity(layers.iter().map(|l| l.len() + 6).sum());484 for l in layers {485 put_bytes(&mut t, 3, &l);486 }487 t488}489490#[inline]491fn cmd(id: u32, count: u32) -> u32 {492 (id & 0x7) | (count << 3)493}494495#[inline]496fn zz32(v: i32) -> u32 {497 ((v << 1) ^ (v >> 31)) as u32498}499500/// Encode la géométrie en commandes MVT (MoveTo=1, LineTo=2, ClosePath=7). Renvoie (type, commandes).501pub fn encode_geometry(g: &Geom) -> (u8, Vec<u32>) {502 let mut out = Vec::new();503 let (mut cx, mut cy) = (0i32, 0i32);504 match g {505 Geom::Points(pts) => {506 if pts.is_empty() {507 return (1, out);508 }509 out.push(cmd(1, pts.len() as u32));510 for &(x, y) in pts {511 out.push(zz32(x - cx));512 out.push(zz32(y - cy));513 cx = x;514 cy = y;515 }516 (1, out)517 }518 Geom::Lines(lines) => {519 for l in lines {520 if l.len() < 2 {521 continue;522 }523 out.push(cmd(1, 1));524 out.push(zz32(l[0].0 - cx));525 out.push(zz32(l[0].1 - cy));526 cx = l[0].0;527 cy = l[0].1;528 out.push(cmd(2, (l.len() - 1) as u32));529 for &(x, y) in &l[1..] {530 out.push(zz32(x - cx));531 out.push(zz32(y - cy));532 cx = x;533 cy = y;534 }535 }536 (2, out)537 }538 Geom::Polygons(polys) => {539 for poly in polys {540 for ring in poly {541 if ring.len() < 3 {542 continue;543 }544 out.push(cmd(1, 1));545 out.push(zz32(ring[0].0 - cx));546 out.push(zz32(ring[0].1 - cy));547 cx = ring[0].0;548 cy = ring[0].1;549 out.push(cmd(2, (ring.len() - 1) as u32));550 for &(x, y) in &ring[1..] {551 out.push(zz32(x - cx));552 out.push(zz32(y - cy));553 cx = x;554 cy = y;555 }556 out.push(cmd(7, 1));557 }558 }559 (3, out)560 }561 }562}563564// ------------------------------------------------------------------------------------------- décodeur565// Sert aux tests, à `km-tiler inspect` et à la validation des archives : lecture stricte du protobuf.566567#[derive(Debug, Clone, PartialEq)]568pub struct DFeature {569 pub id: Option<u64>,570 pub gtype: u8,571 pub geom: Geom,572 pub attrs: Vec<(String, Value)>,573}574575#[derive(Debug, Clone)]576pub struct DLayer {577 pub name: String,578 pub version: u32,579 pub extent: u32,580 pub features: Vec<DFeature>,581}582583pub fn get_varint(b: &[u8], p: &mut usize) -> Result<u64, String> {584 let mut v: u64 = 0;585 let mut shift = 0;586 loop {587 let byte = *b.get(*p).ok_or("varint tronqué")?;588 *p += 1;589 v |= ((byte & 0x7f) as u64) << shift;590 if byte & 0x80 == 0 {591 return Ok(v);592 }593 shift += 7;594 if shift > 63 {595 return Err("varint trop long".into());596 }597 }598}599600fn get_field<'a>(b: &'a [u8], p: &mut usize) -> Result<(u32, u8, u64, &'a [u8]), String> {601 let key = get_varint(b, p)?;602 let (field, wire) = ((key >> 3) as u32, (key & 7) as u8);603 match wire {604 0 => Ok((field, wire, get_varint(b, p)?, &[])),605 1 => {606 let s = b.get(*p..*p + 8).ok_or("fixed64 tronqué")?;607 *p += 8;608 let mut a = [0u8; 8];609 a.copy_from_slice(s);610 Ok((field, wire, u64::from_le_bytes(a), &[]))611 }612 2 => {613 let n = get_varint(b, p)? as usize;614 let s = b.get(*p..*p + n).ok_or("champ tronqué")?;615 *p += n;616 Ok((field, wire, 0, s))617 }618 5 => {619 let s = b.get(*p..*p + 4).ok_or("fixed32 tronqué")?;620 *p += 4;621 Ok((field, wire, u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as u64, &[]))622 }623 _ => Err(format!("type de fil {} inconnu", wire)),624 }625}626627fn unzz(v: u32) -> i32 {628 ((v >> 1) as i32) ^ -((v & 1) as i32)629}630631pub fn decode_geometry(gtype: u8, cmds: &[u32]) -> Result<Geom, String> {632 let (mut x, mut y) = (0i32, 0i32);633 let mut i = 0;634 let mut pts: Vec<(i32, i32)> = Vec::new();635 let mut parts: Vec<Vec<(i32, i32)>> = Vec::new();636 let mut cur: Vec<(i32, i32)> = Vec::new();637 while i < cmds.len() {638 let c = cmds[i];639 i += 1;640 let (id, count) = (c & 7, c >> 3);641 match id {642 1 | 2 => {643 for _ in 0..count {644 if i + 2 > cmds.len() {645 return Err("commande tronquée".into());646 }647 x += unzz(cmds[i]);648 y += unzz(cmds[i + 1]);649 i += 2;650 if gtype == 1 {651 pts.push((x, y));652 } else if id == 1 {653 if !cur.is_empty() {654 parts.push(std::mem::take(&mut cur));655 }656 cur.push((x, y));657 } else {658 if cur.is_empty() {659 return Err("LineTo sans MoveTo".into());660 }661 cur.push((x, y));662 }663 }664 }665 7 => {666 if gtype != 3 || count != 1 {667 return Err("ClosePath invalide".into());668 }669 if cur.len() < 3 {670 return Err("anneau de moins de 3 sommets".into());671 }672 parts.push(std::mem::take(&mut cur));673 }674 _ => return Err(format!("commande {} inconnue", id)),675 }676 }677 if !cur.is_empty() {678 if gtype == 3 {679 return Err("anneau non fermé".into());680 }681 parts.push(cur);682 }683 match gtype {684 1 => Ok(Geom::Points(pts)),685 2 => {686 if parts.iter().any(|l| l.len() < 2) {687 return Err("ligne de moins de 2 sommets".into());688 }689 Ok(Geom::Lines(parts))690 }691 3 => {692 let mut polys: Vec<Vec<Vec<(i32, i32)>>> = Vec::new();693 for ring in parts {694 let a = ring_area(&ring);695 if a > 0.0 {696 polys.push(vec![ring]);697 } else if a < 0.0 {698 match polys.last_mut() {699 Some(p) => p.push(ring),700 None => return Err("trou sans anneau extérieur".into()),701 }702 } else {703 return Err("anneau d'aire nulle".into());704 }705 }706 Ok(Geom::Polygons(polys))707 }708 _ => Err("type de géométrie inconnu".into()),709 }710}711712pub fn decode(tile: &[u8]) -> Result<Vec<DLayer>, String> {713 let mut layers = Vec::new();714 let mut p = 0;715 while p < tile.len() {716 let (field, wire, _, lb) = get_field(tile, &mut p)?;717 if field != 3 || wire != 2 {718 return Err(format!("champ de tuile inattendu {}", field));719 }720 let mut name = None;721 let mut version = 1;722 let mut extent = 4096;723 let mut keys: Vec<String> = Vec::new();724 let mut values: Vec<Value> = Vec::new();725 let mut raw_features: Vec<&[u8]> = Vec::new();726 let mut q = 0;727 while q < lb.len() {728 let (f, w, v, s) = get_field(lb, &mut q)?;729 match (f, w) {730 (15, 0) => version = v as u32,731 (1, 2) => name = Some(String::from_utf8(s.to_vec()).map_err(|_| "nom non UTF-8")?),732 (2, 2) => raw_features.push(s),733 (3, 2) => keys.push(String::from_utf8(s.to_vec()).map_err(|_| "clé non UTF-8")?),734 (4, 2) => {735 let mut r = 0;736 let mut val = None;737 while r < s.len() {738 let (vf, vw, vv, vs) = get_field(s, &mut r)?;739 val = Some(match (vf, vw) {740 (1, 2) => Value::Str(String::from_utf8(vs.to_vec()).map_err(|_| "valeur non UTF-8")?),741 (2, 5) => Value::Double(f32::from_bits(vv as u32) as f64),742 (3, 1) => Value::Double(f64::from_bits(vv)),743 (4, 0) => Value::Int(vv as i64),744 (5, 0) => Value::Int(vv as i64),745 (6, 0) => Value::Int(((vv >> 1) as i64) ^ -((vv & 1) as i64)),746 (7, 0) => Value::Bool(vv != 0),747 _ => return Err("valeur de type inconnu".into()),748 });749 }750 values.push(val.ok_or("valeur vide")?);751 }752 (5, 0) => extent = v as u32,753 _ => return Err(format!("champ de couche inattendu {}", f)),754 }755 }756 let mut features = Vec::with_capacity(raw_features.len());757 for fb in raw_features {758 let mut r = 0;759 let mut id = None;760 let mut gtype = 0u8;761 let mut tags: Vec<u32> = Vec::new();762 let mut cmds: Vec<u32> = Vec::new();763 while r < fb.len() {764 let (f, w, v, s) = get_field(fb, &mut r)?;765 match (f, w) {766 (1, 0) => id = Some(v),767 (2, 2) => {768 let mut t = 0;769 while t < s.len() {770 tags.push(get_varint(s, &mut t)? as u32);771 }772 }773 (3, 0) => gtype = v as u8,774 (4, 2) => {775 let mut t = 0;776 while t < s.len() {777 cmds.push(get_varint(s, &mut t)? as u32);778 }779 }780 _ => return Err(format!("champ d'entité inattendu {}", f)),781 }782 }783 if tags.len() % 2 != 0 {784 return Err("tags impairs".into());785 }786 let mut attrs = Vec::with_capacity(tags.len() / 2);787 for kv in tags.chunks(2) {788 let k = keys.get(kv[0] as usize).ok_or("index de clé hors bornes")?;789 let v = values.get(kv[1] as usize).ok_or("index de valeur hors bornes")?;790 attrs.push((k.clone(), v.clone()));791 }792 let geom = decode_geometry(gtype, &cmds)?;793 features.push(DFeature { id, gtype, geom, attrs });794 }795 layers.push(DLayer { name: name.ok_or("couche sans nom")?, version, extent, features });796 }797 Ok(layers)798}799800#[cfg(test)]801mod tests {802 use super::*;803804 fn wkb_point(x: f64, y: f64) -> Vec<u8> {805 let mut b = vec![1u8];806 b.extend_from_slice(&1u32.to_le_bytes());807 b.extend_from_slice(&x.to_le_bytes());808 b.extend_from_slice(&y.to_le_bytes());809 b810 }811 fn wkb_line(pts: &[(f64, f64)]) -> Vec<u8> {812 let mut b = vec![1u8];813 b.extend_from_slice(&2u32.to_le_bytes());814 b.extend_from_slice(&(pts.len() as u32).to_le_bytes());815 for (x, y) in pts {816 b.extend_from_slice(&x.to_le_bytes());817 b.extend_from_slice(&y.to_le_bytes());818 }819 b820 }821 fn wkb_poly(rings: &[Vec<(f64, f64)>]) -> Vec<u8> {822 let mut b = vec![1u8];823 b.extend_from_slice(&3u32.to_le_bytes());824 b.extend_from_slice(&(rings.len() as u32).to_le_bytes());825 for r in rings {826 b.extend_from_slice(&(r.len() as u32).to_le_bytes());827 for (x, y) in r {828 b.extend_from_slice(&x.to_le_bytes());829 b.extend_from_slice(&y.to_le_bytes());830 }831 }832 b833 }834 fn wkb_multi(ty: u32, parts: &[Vec<u8>]) -> Vec<u8> {835 let mut b = vec![1u8];836 b.extend_from_slice(&ty.to_le_bytes());837 b.extend_from_slice(&(parts.len() as u32).to_le_bytes());838 for p in parts {839 b.extend_from_slice(p);840 }841 b842 }843844 #[test]845 fn spec_examples() {846 // Exemples de la spécification MVT 2.1 (§4.3.5).847 let (t, c) = encode_geometry(&Geom::Points(vec![(25, 17)]));848 assert_eq!((t, c), (1, vec![9, 50, 34]));849 let (t, c) = encode_geometry(&Geom::Points(vec![(5, 7), (3, 2)]));850 assert_eq!((t, c), (1, vec![17, 10, 14, 3, 9]));851 let (t, c) = encode_geometry(&Geom::Lines(vec![vec![(2, 2), (2, 10), (10, 10)]]));852 assert_eq!((t, c), (2, vec![9, 4, 4, 18, 0, 16, 16, 0]));853 let (t, c) = encode_geometry(&Geom::Lines(vec![vec![(2, 2), (2, 10), (10, 10)], vec![(1, 1), (3, 5)]]));854 assert_eq!((t, c), (2, vec![9, 4, 4, 18, 0, 16, 16, 0, 9, 17, 17, 10, 4, 8]));855 let (t, c) = encode_geometry(&Geom::Polygons(vec![vec![vec![(3, 6), (8, 12), (20, 34)]]]));856 assert_eq!((t, c), (3, vec![9, 6, 12, 18, 10, 12, 24, 44, 15]));857 }858859 #[test]860 fn winding_and_min_area() {861 // Carré en sens inverse (aire négative en coordonnées de tuile) : doit être retourné.862 let ccw = vec![(0.0, 0.0), (0.0, 10.0), (10.0, 10.0), (10.0, 0.0), (0.0, 0.0)];863 let hole = vec![(2.0, 2.0), (2.0, 5.0), (5.0, 5.0), (5.0, 2.0), (2.0, 2.0)];864 let tiny_hole = vec![(7.0, 7.0), (8.0, 7.0), (8.0, 8.0), (7.0, 8.0), (7.0, 7.0)];865 let g = geom_from_wkb(&wkb_poly(&[ccw.clone(), hole, tiny_hole])).unwrap();866 match &g {867 Geom::Polygons(p) => {868 assert_eq!(p.len(), 1);869 assert_eq!(p[0].len(), 2, "le trou de 1 unité² est écarté");870 assert!(ring_area(&p[0][0]) > 0.0);871 assert!(ring_area(&p[0][1]) < 0.0);872 }873 _ => panic!(),874 }875 // Polygone de 1 unité² : écarté.876 let tiny = vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)];877 assert!(geom_from_wkb(&wkb_poly(&[tiny])).is_none());878 // Multipolygone : le petit disparaît, le grand reste.879 let big = wkb_poly(&[ccw]);880 let small = wkb_poly(&[vec![(50.0, 50.0), (51.0, 50.0), (51.0, 51.0), (50.0, 50.0)]]);881 match geom_from_wkb(&wkb_multi(6, &[big, small])).unwrap() {882 Geom::Polygons(p) => assert_eq!(p.len(), 1),883 _ => panic!(),884 }885 }886887 #[test]888 fn wkb_lines_points() {889 let g = geom_from_wkb(&wkb_line(&[(0.4, 0.4), (0.0, 0.2), (5.0, 5.0)])).unwrap();890 assert_eq!(g, Geom::Lines(vec![vec![(0, 0), (5, 5)]]), "points consécutifs identiques fusionnés");891 assert!(geom_from_wkb(&wkb_line(&[(1.0, 1.0), (1.2, 0.9)])).is_none(), "ligne dégénérée");892 assert_eq!(geom_from_wkb(&wkb_point(12.0, -3.0)).unwrap(), Geom::Points(vec![(12, -3)]));893 assert!(geom_from_wkb(&wkb_point(f64::NAN, f64::NAN)).is_none());894 let ml = wkb_multi(5, &[wkb_line(&[(0.0, 0.0), (4.0, 0.0)]), wkb_line(&[(9.0, 9.0), (9.0, 20.0)])]);895 match geom_from_wkb(&ml).unwrap() {896 Geom::Lines(l) => assert_eq!(l.len(), 2),897 _ => panic!(),898 }899 assert!(geom_from_wkb(&[1, 2, 3]).is_none());900 assert!(geom_from_wkb(&[]).is_none());901 }902903 #[test]904 fn roundtrip_tile() {905 let mut road = LayerBuilder::new("road", 4096);906 let line = Geom::Lines(vec![vec![(-64, 100), (2000, 2100), (4160, 4000)]]);907 assert!(road.add(908 &line,909 &[910 ("kind", Value::Str("motorway".into())),911 ("link", Value::Int(0)),912 ("struct", Value::Int(1)),913 ("name", Value::Str("Autoroute Décarie".into())),914 ("ref", Value::Str("15".into())),915 ("oneway", Value::Int(1)),916 ("layer", Value::Int(-1)),917 ]918 ));919 assert!(road.add(&line, &[("kind", Value::Str("motorway".into())), ("link", Value::Int(0))]));920 assert!(!road.add(&Geom::Lines(vec![]), &[]));921 let mut b = LayerBuilder::new("building", 4096);922 let poly = Geom::Polygons(vec![vec![923 vec![(10, 10), (110, 10), (110, 110), (10, 110)],924 vec![(40, 40), (40, 60), (60, 60), (60, 40)],925 ]]);926 b.add(927 &poly,928 &[("h", Value::Int(125)), ("mh", Value::Int(0)), ("hs", Value::Int(2)), ("kind", Value::Str("house".into())), ("id", Value::Int(-123456789012))],929 );930 let mut pl = LayerBuilder::new("place", 4096);931 pl.add(&Geom::Points(vec![(2048, 2048)]), &[("name", Value::Str("Montréal".into())), ("pop", Value::Int(1762949)), ("x", Value::Double(1.5)), ("b", Value::Bool(true))]);932 let tile = assemble(vec![road.finish(), b.finish(), pl.finish()]);933 let d = decode(&tile).unwrap();934 assert_eq!(d.len(), 3);935 assert_eq!(d[0].name, "road");936 assert_eq!(d[0].version, 2);937 assert_eq!(d[0].extent, 4096);938 assert_eq!(d[0].features.len(), 2);939 assert_eq!(d[0].features[0].geom, line);940 assert_eq!(d[0].features[0].attrs.len(), 7);941 assert_eq!(d[0].features[0].attrs[3], ("name".to_string(), Value::Str("Autoroute Décarie".into())));942 assert_eq!(d[0].features[0].attrs[6], ("layer".to_string(), Value::Int(-1)));943 assert_eq!(d[1].features[0].geom, poly);944 assert_eq!(d[1].features[0].attrs[4], ("id".to_string(), Value::Int(-123456789012)));945 assert_eq!(d[2].features[0].geom, Geom::Points(vec![(2048, 2048)]));946 assert_eq!(d[2].features[0].attrs[2], ("x".to_string(), Value::Double(1.5)));947 assert_eq!(d[2].features[0].attrs[3], ("b".to_string(), Value::Bool(true)));948 }949950 #[test]951 fn keys_values_are_deduplicated() {952 let mut l = LayerBuilder::new("t", 4096);953 for i in 0..100 {954 l.add(&Geom::Points(vec![(i, i)]), &[("kind", Value::Str("a".into())), ("n", Value::Int(i as i64 % 2))]);955 }956 assert_eq!(l.keys.len(), 2);957 assert_eq!(l.values.len(), 3);958 let d = decode(&assemble(vec![l.finish()])).unwrap();959 assert_eq!(d[0].features.len(), 100);960 }961962 #[test]963 fn decoder_rejects_garbage() {964 assert!(decode(&[0xff, 0xff, 0xff]).is_err());965 assert!(decode(&[0x1a, 0x05, 0x01]).is_err());966 assert!(decode_geometry(3, &[9, 0, 0, 10, 2, 2, 15]).is_err());967 assert!(decode(&[]).unwrap().is_empty());968 }969}970