1use super::mvt::{PbFeature, PbLayer, PbTile, PbValue, GEOJSON_LAYER};
17use prost::Message;
18use serde_json::Value as Json;
19
20const EXTENT: f64 = 8192.0;
21
22fn js_round(v: f64) -> f64 {
24 (v + 0.5).floor()
25}
26
27#[derive(Clone, Debug)]
28struct Line {
29 pts: Vec<[f64; 3]>,
30 size: f64,
32}
33
34#[derive(Clone, Debug)]
35enum Geom {
36 Points(Vec<[f64; 3]>),
37 Lines(Vec<Line>),
38 Polygons(Vec<Vec<Line>>),
40}
41
42#[derive(Clone, Debug)]
43enum Prop {
44 Str(String),
45 Num(f64),
46 Bool(bool),
47}
48
49#[derive(Clone, Debug)]
50struct Feat {
51 id: Option<u64>,
52 geom: Geom,
53 props: Vec<(String, Prop)>,
54 min: (f64, f64),
55 max: (f64, f64),
56}
57
58#[derive(Clone, Copy, Debug)]
60pub struct GeoJsonOptions {
61 pub max_zoom: u8,
62 pub buffer: f64,
64 pub tolerance: f64,
66}
67
68impl GeoJsonOptions {
69 pub fn from_source(src: &Json) -> Self {
71 let scale = EXTENT / 512.0;
72 GeoJsonOptions {
73 max_zoom: src["maxzoom"].as_u64().map_or(18, |z| z.min(24) as u8),
74 buffer: src["buffer"].as_f64().unwrap_or(128.0) * scale,
75 tolerance: src["tolerance"].as_f64().unwrap_or(0.375) * scale,
76 }
77 }
78}
79
80pub struct GeoJsonIndex {
82 features: Vec<Feat>,
83 opts: GeoJsonOptions,
84}
85
86impl GeoJsonIndex {
87 pub fn new(data: &Json, opts: GeoJsonOptions) -> Self {
88 let sq_tol = (opts.tolerance / ((1u64 << opts.max_zoom) as f64 * EXTENT)).powi(2);
89 let mut features = Vec::new();
90 convert(data, &mut features, sq_tol, None);
91 let features = wrap(features, opts.buffer / EXTENT);
92 GeoJsonIndex { features, opts }
93 }
94
95 pub fn tile(&self, z: u8, x: u32, y: u32) -> Vec<u8> {
97 let z2 = (1u64 << z) as f64;
98 let k = self.opts.buffer / EXTENT;
99 let (x0, x1) = ((x as f64 - k) / z2, (x as f64 + 1.0 + k) / z2);
100 let (y0, y1) = ((y as f64 - k) / z2, (y as f64 + 1.0 + k) / z2);
101 let clipped = clip(&self.features, x0, x1, 0);
102 let clipped = clip(&clipped, y0, y1, 1);
103 let tol = if z >= self.opts.max_zoom { 0.0 } else { self.opts.tolerance / (z2 * EXTENT) };
104 encode_tile(&clipped, z2, x as f64, y as f64, tol)
105 }
106}
107
108fn project_x(lng: f64) -> f64 {
111 lng / 360.0 + 0.5
112}
113
114fn project_y(lat: f64) -> f64 {
115 let s = lat.to_radians().sin();
116 let y = 0.5 - 0.25 * ((1.0 + s) / (1.0 - s)).ln() / std::f64::consts::PI;
117 y.clamp(0.0, 1.0)
118}
119
120fn convert(data: &Json, out: &mut Vec<Feat>, sq_tol: f64, inherit: Option<(&Json, Option<u64>)>) {
121 match data["type"].as_str() {
122 Some("FeatureCollection") => {
123 for f in data["features"].as_array().map(|v| v.as_slice()).unwrap_or(&[]) {
124 convert(f, out, sq_tol, None);
125 }
126 }
127 Some("Feature") => {
128 let id = feature_id(&data["id"]);
129 convert_geometry(&data["geometry"], &data["properties"], id, out, sq_tol);
130 }
131 Some(_) => {
132 let (props, id) = inherit.unwrap_or((&Json::Null, None));
133 convert_geometry(data, props, id, out, sq_tol);
134 }
135 None => {}
136 }
137}
138
139fn feature_id(j: &Json) -> Option<u64> {
141 match j {
142 Json::Number(n) => n.as_u64().or_else(|| n.as_f64().filter(|v| *v >= 0.0).map(|v| v as u64)),
143 Json::String(s) => s.trim().parse::<f64>().ok().filter(|v| *v >= 0.0).map(|v| v as u64),
144 _ => None,
145 }
146}
147
148fn props_of(p: &Json) -> Vec<(String, Prop)> {
149 let Some(obj) = p.as_object() else { return Vec::new() };
150 obj.iter()
151 .filter_map(|(k, v)| {
152 let v = match v {
153 Json::String(s) => Prop::Str(s.clone()),
154 Json::Number(n) => Prop::Num(n.as_f64()?),
155 Json::Bool(b) => Prop::Bool(*b),
156 Json::Null => return None,
157 other => Prop::Str(other.to_string()),
158 };
159 Some((k.clone(), v))
160 })
161 .collect()
162}
163
164fn convert_geometry(g: &Json, props: &Json, id: Option<u64>, out: &mut Vec<Feat>, sq_tol: f64) {
165 let coords = &g["coordinates"];
166 let point = |c: &Json| -> Option<[f64; 3]> {
167 let a = c.as_array()?;
168 Some([project_x(a.first()?.as_f64()?), project_y(a.get(1)?.as_f64()?), 0.0])
169 };
170 let line = |c: &Json, polygon: bool| -> Option<Line> {
171 let pts: Vec<[f64; 3]> = c.as_array()?.iter().filter_map(point).collect();
172 if pts.is_empty() {
173 return None;
174 }
175 Some(convert_line(pts, sq_tol, polygon))
176 };
177 let geom = match g["type"].as_str() {
178 Some("Point") => point(coords).map(|p| Geom::Points(vec![p])),
179 Some("MultiPoint") => Some(Geom::Points(coords.as_array().map(|a| a.iter().filter_map(point).collect()).unwrap_or_default())),
180 Some("LineString") => line(coords, false).map(|l| Geom::Lines(vec![l])),
181 Some("MultiLineString") => {
182 Some(Geom::Lines(coords.as_array().map(|a| a.iter().filter_map(|c| line(c, false)).collect()).unwrap_or_default()))
183 }
184 Some("Polygon") => {
185 let rings: Vec<Line> = coords.as_array().map(|a| a.iter().filter_map(|c| line(c, true)).collect()).unwrap_or_default();
186 Some(Geom::Polygons(vec![rings]))
187 }
188 Some("MultiPolygon") => Some(Geom::Polygons(
189 coords
190 .as_array()
191 .map(|a| a.iter().map(|p| p.as_array().map(|r| r.iter().filter_map(|c| line(c, true)).collect()).unwrap_or_default()).collect())
192 .unwrap_or_default(),
193 )),
194 Some("GeometryCollection") => {
195 for sub in g["geometries"].as_array().map(|v| v.as_slice()).unwrap_or(&[]) {
196 convert_geometry(sub, props, id, out, sq_tol);
197 }
198 None
199 }
200 _ => None,
201 };
202 if let Some(geom) = geom {
203 out.push(make_feat(id, geom, props_of(props)));
204 }
205}
206
207fn make_feat(id: Option<u64>, geom: Geom, props: Vec<(String, Prop)>) -> Feat {
208 let mut f = Feat { id, geom, props, min: (f64::INFINITY, f64::INFINITY), max: (f64::NEG_INFINITY, f64::NEG_INFINITY) };
209 let mut extend = |p: &[f64; 3]| {
210 f.min = (f.min.0.min(p[0]), f.min.1.min(p[1]));
211 f.max = (f.max.0.max(p[0]), f.max.1.max(p[1]));
212 };
213 match &f.geom {
214 Geom::Points(pts) => pts.iter().for_each(&mut extend),
215 Geom::Lines(ls) => ls.iter().flat_map(|l| l.pts.iter()).for_each(&mut extend),
216 Geom::Polygons(ps) => ps.iter().flatten().flat_map(|l| l.pts.iter()).for_each(&mut extend),
217 }
218 f
219}
220
221fn convert_line(mut pts: Vec<[f64; 3]>, sq_tol: f64, polygon: bool) -> Line {
222 let mut size = 0.0;
223 for j in 1..pts.len() {
224 let (a, b) = (pts[j - 1], pts[j]);
225 if polygon {
226 size += (a[0] * b[1] - b[0] * a[1]) / 2.0;
227 } else {
228 size += ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt();
229 }
230 }
231 let last = pts.len() - 1;
232 pts[0][2] = 1.0;
233 simplify(&mut pts, 0, last, sq_tol);
234 pts[last][2] = 1.0;
235 Line { pts, size: size.abs() }
236}
237
238fn simplify(c: &mut [[f64; 3]], first: usize, last: usize, sq_tol: f64) {
241 let mut max_sq = sq_tol;
242 let mid = (last - first) / 2 + first;
243 let mut min_pos_to_mid = last - first;
244 let mut index = None;
245 let (a, b) = (c[first], c[last]);
246 for i in first + 1..last {
247 let d = sq_seg_dist(c[i][0], c[i][1], a[0], a[1], b[0], b[1]);
248 if d > max_sq {
249 index = Some(i);
250 max_sq = d;
251 } else if d == max_sq {
252 let pos = i.abs_diff(mid);
254 if pos < min_pos_to_mid {
255 index = Some(i);
256 min_pos_to_mid = pos;
257 }
258 }
259 }
260 if max_sq > sq_tol {
261 let index = index.unwrap();
262 if index - first > 1 {
263 simplify(c, first, index, sq_tol);
264 }
265 c[index][2] = max_sq;
266 if last - index > 1 {
267 simplify(c, index, last, sq_tol);
268 }
269 }
270}
271
272fn sq_seg_dist(px: f64, py: f64, mut x: f64, mut y: f64, bx: f64, by: f64) -> f64 {
273 let (mut dx, mut dy) = (bx - x, by - y);
274 if dx != 0.0 || dy != 0.0 {
275 let t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
276 if t > 1.0 {
277 x = bx;
278 y = by;
279 } else if t > 0.0 {
280 x += dx * t;
281 y += dy * t;
282 }
283 }
284 dx = px - x;
285 dy = py - y;
286 dx * dx + dy * dy
287}
288
289fn wrap(features: Vec<Feat>, buffer: f64) -> Vec<Feat> {
292 let left = clip(&features, -1.0 - buffer, buffer, 0);
293 let right = clip(&features, 1.0 - buffer, 2.0 + buffer, 0);
294 if left.is_empty() && right.is_empty() {
295 return features;
296 }
297 let mut merged: Vec<Feat> = left.into_iter().map(|f| shift(f, 1.0)).collect();
298 merged.extend(clip(&features, -buffer, 1.0 + buffer, 0));
299 merged.extend(right.into_iter().map(|f| shift(f, -1.0)));
300 merged
301}
302
303fn shift(mut f: Feat, dx: f64) -> Feat {
304 let s = |p: &mut [f64; 3]| p[0] += dx;
305 match &mut f.geom {
306 Geom::Points(pts) => pts.iter_mut().for_each(s),
307 Geom::Lines(ls) => ls.iter_mut().flat_map(|l| l.pts.iter_mut()).for_each(s),
308 Geom::Polygons(ps) => ps.iter_mut().flatten().flat_map(|l| l.pts.iter_mut()).for_each(s),
309 }
310 f.min.0 += dx;
311 f.max.0 += dx;
312 f
313}
314
315fn clip(features: &[Feat], k1: f64, k2: f64, axis: usize) -> Vec<Feat> {
319 let mut out = Vec::new();
320 for f in features {
321 let (min, max) = if axis == 0 { (f.min.0, f.max.0) } else { (f.min.1, f.max.1) };
322 if min >= k1 && max < k2 {
323 out.push(f.clone());
324 continue;
325 }
326 if max < k1 || min >= k2 {
327 continue;
328 }
329 let geom = match &f.geom {
330 Geom::Points(pts) => {
331 let kept: Vec<[f64; 3]> = pts.iter().filter(|p| p[axis] >= k1 && p[axis] <= k2).copied().collect();
332 if kept.is_empty() { None } else { Some(Geom::Points(kept)) }
333 }
334 Geom::Lines(ls) => {
335 let mut nl = Vec::new();
336 for l in ls {
337 clip_line(l, &mut nl, k1, k2, axis, false);
338 }
339 if nl.is_empty() { None } else { Some(Geom::Lines(nl)) }
340 }
341 Geom::Polygons(ps) => {
342 let mut np = Vec::new();
343 for p in ps {
344 let mut rings = Vec::new();
345 for r in p {
346 clip_line(r, &mut rings, k1, k2, axis, true);
347 }
348 if !rings.is_empty() {
349 np.push(rings);
350 }
351 }
352 if np.is_empty() { None } else { Some(Geom::Polygons(np)) }
353 }
354 };
355 if let Some(g) = geom {
356 out.push(make_feat(f.id, g, f.props.clone()));
357 }
358 }
359 out
360}
361
362fn clip_line(geom: &Line, out: &mut Vec<Line>, k1: f64, k2: f64, axis: usize, polygon: bool) {
363 let new_slice = || Line { pts: Vec::new(), size: geom.size };
364 let mut slice = new_slice();
365 let intersect = |s: &mut Line, a: [f64; 3], b: [f64; 3], k: f64| {
366 if axis == 0 {
367 let t = (k - a[0]) / (b[0] - a[0]);
368 s.pts.push([k, a[1] + (b[1] - a[1]) * t, 1.0]);
369 } else {
370 let t = (k - a[1]) / (b[1] - a[1]);
371 s.pts.push([a[0] + (b[0] - a[0]) * t, k, 1.0]);
372 }
373 };
374 let n = geom.pts.len();
375 for i in 0..n.saturating_sub(1) {
376 let (pa, pb) = (geom.pts[i], geom.pts[i + 1]);
377 let (a, b) = (pa[axis], pb[axis]);
378 let mut exited = false;
379 if a < k1 {
380 if b > k1 {
381 intersect(&mut slice, pa, pb, k1);
382 }
383 } else if a > k2 {
384 if b < k2 {
385 intersect(&mut slice, pa, pb, k2);
386 }
387 } else {
388 slice.pts.push(pa);
389 }
390 if b < k1 && a >= k1 {
391 intersect(&mut slice, pa, pb, k1);
392 exited = true;
393 }
394 if b > k2 && a <= k2 {
395 intersect(&mut slice, pa, pb, k2);
396 exited = true;
397 }
398 if !polygon && exited {
399 out.push(std::mem::replace(&mut slice, new_slice()));
400 }
401 }
402 if let Some(&last) = geom.pts.last() {
403 if last[axis] >= k1 && last[axis] <= k2 {
404 slice.pts.push(last);
405 }
406 }
407 if polygon && slice.pts.len() >= 2 {
409 let (f, l) = (slice.pts[0], *slice.pts.last().unwrap());
410 if f[0] != l[0] || f[1] != l[1] {
411 slice.pts.push(f);
412 }
413 }
414 if !slice.pts.is_empty() {
415 out.push(slice);
416 }
417}
418
419fn encode_tile(features: &[Feat], z2: f64, tx: f64, ty: f64, tol: f64) -> Vec<u8> {
422 let sq_tol = tol * tol;
423 let transform = |p: &[f64; 3]| -> (i64, i64) {
424 (js_round(EXTENT * (p[0] * z2 - tx)) as i64, js_round(EXTENT * (p[1] * z2 - ty)) as i64)
425 };
426 let keep = |l: &Line, polygon: bool, outer: bool| -> Option<Vec<(i64, i64)>> {
428 if tol > 0.0 && l.size < if polygon { sq_tol } else { tol } {
429 return None;
430 }
431 let mut ring: Vec<(i64, i64)> = l.pts.iter().filter(|p| tol == 0.0 || p[2] > sq_tol).map(transform).collect();
432 if polygon {
433 rewind(&mut ring, outer);
434 }
435 Some(ring)
436 };
437 let mut keys: Vec<String> = Vec::new();
438 let mut values: Vec<(u8, String)> = Vec::new(); let mut pb_values: Vec<PbValue> = Vec::new();
440 let mut pb_features = Vec::new();
441 for f in features {
442 let (kind, geometry): (i32, Vec<u32>) = match &f.geom {
443 Geom::Points(pts) => {
444 let pts: Vec<(i64, i64)> = pts.iter().map(transform).collect();
445 (1, encode_points(&pts))
446 }
447 Geom::Lines(ls) => {
448 let lines: Vec<Vec<(i64, i64)>> = ls.iter().filter_map(|l| keep(l, false, false)).filter(|l| l.len() >= 2).collect();
449 if lines.is_empty() {
450 continue;
451 }
452 (2, encode_lines(&lines, false))
453 }
454 Geom::Polygons(ps) => {
455 let mut rings = Vec::new();
456 for p in ps {
457 for (i, r) in p.iter().enumerate() {
458 if let Some(ring) = keep(r, true, i == 0) {
459 if ring.len() >= 2 {
460 rings.push(ring);
461 }
462 }
463 }
464 }
465 if rings.is_empty() {
466 continue;
467 }
468 (3, encode_lines(&rings, true))
469 }
470 };
471 let mut tags = Vec::new();
472 for (k, v) in &f.props {
473 let ki = keys.iter().position(|x| x == k).unwrap_or_else(|| {
474 keys.push(k.clone());
475 keys.len() - 1
476 });
477 let canon = match v {
478 Prop::Str(s) => (0u8, s.clone()),
479 Prop::Num(n) => (1, n.to_bits().to_string()),
480 Prop::Bool(b) => (2, b.to_string()),
481 };
482 let vi = values.iter().position(|x| *x == canon).unwrap_or_else(|| {
483 values.push(canon);
484 let mut pv = PbValue::default();
485 match v {
486 Prop::Str(s) => pv.string_value = Some(s.clone()),
487 Prop::Num(n) => pv.double_value = Some(*n),
488 Prop::Bool(b) => pv.bool_value = Some(*b),
489 }
490 pb_values.push(pv);
491 values.len() - 1
492 });
493 tags.push(ki as u32);
494 tags.push(vi as u32);
495 }
496 pb_features.push(PbFeature { id: f.id, tags, r#type: Some(kind), geometry });
497 }
498 let layer = PbLayer { version: 2, name: GEOJSON_LAYER.to_owned(), features: pb_features, keys, values: pb_values, extent: Some(EXTENT as u32) };
499 PbTile { layers: vec![layer] }.encode_to_vec()
500}
501
502fn rewind(ring: &mut [(i64, i64)], clockwise: bool) {
504 let n = ring.len();
505 if n < 3 {
506 return;
507 }
508 let mut area = 0.0;
509 let mut j = n - 1;
510 for i in 0..n {
511 area += (ring[i].0 - ring[j].0) as f64 * (ring[i].1 + ring[j].1) as f64;
512 j = i;
513 }
514 if (area > 0.0) == clockwise {
515 ring.reverse();
516 }
517}
518
519fn zigzag(v: i64) -> u32 {
520 ((v << 1) ^ (v >> 63)) as u32
521}
522
523fn command(id: u32, count: u32) -> u32 {
524 (id & 7) | (count << 3)
525}
526
527fn encode_points(pts: &[(i64, i64)]) -> Vec<u32> {
528 let mut g = vec![command(1, pts.len() as u32)];
529 let (mut cx, mut cy) = (0, 0);
530 for &(x, y) in pts {
531 g.push(zigzag(x - cx));
532 g.push(zigzag(y - cy));
533 cx = x;
534 cy = y;
535 }
536 g
537}
538
539fn encode_lines(lines: &[Vec<(i64, i64)>], closed: bool) -> Vec<u32> {
542 let mut g = Vec::new();
543 let (mut cx, mut cy) = (0, 0);
544 for l in lines {
545 let mut pts: &[(i64, i64)] = l;
546 if closed && pts.len() > 1 && pts.first() == pts.last() {
547 pts = &pts[..pts.len() - 1];
548 }
549 if pts.is_empty() {
550 continue;
551 }
552 g.push(command(1, 1));
553 g.push(zigzag(pts[0].0 - cx));
554 g.push(zigzag(pts[0].1 - cy));
555 cx = pts[0].0;
556 cy = pts[0].1;
557 if pts.len() > 1 {
558 g.push(command(2, (pts.len() - 1) as u32));
559 for &(x, y) in &pts[1..] {
560 g.push(zigzag(x - cx));
561 g.push(zigzag(y - cy));
562 cx = x;
563 cy = y;
564 }
565 }
566 if closed {
567 g.push(command(7, 1));
568 }
569 }
570 g
571}
572
573#[cfg(test)]
574mod tests {
575 use super::*;
576 use serde_json::json;
577
578 #[test]
579 fn point_and_polygon_tile_round_trip_through_mvt() {
580 let data = json!({"type": "FeatureCollection", "features": [
581 {"type": "Feature", "id": 7, "properties": {"name": "A", "n": 3},
582 "geometry": {"type": "Point", "coordinates": [0.0, 0.0]}},
583 {"type": "Feature", "properties": {"kind": "park"},
584 "geometry": {"type": "Polygon", "coordinates": [[[-10.0, -10.0], [10.0, -10.0], [10.0, 10.0], [-10.0, 10.0], [-10.0, -10.0]]]}}
585 ]});
586 let idx = GeoJsonIndex::new(&data, GeoJsonOptions { max_zoom: 18, buffer: 2048.0, tolerance: 6.0 });
587 let bytes = idx.tile(1, 1, 1);
588 let tile = super::super::mvt::decode(&bytes).unwrap();
589 let layer = &tile.layers[GEOJSON_LAYER];
590 assert_eq!(layer.features.len(), 2);
591 let p = &layer.features[0];
592 assert_eq!(p.id, Some(7));
593 match &p.geometry {
595 super::super::mvt::Geometry::Points(pts) => assert_eq!(pts[0], (0.0, 0.0)),
596 g => panic!("{g:?}"),
597 }
598 match &layer.features[1].geometry {
599 super::super::mvt::Geometry::Polygons(polys) => {
600 assert_eq!(polys.len(), 1);
601 let xs: Vec<f32> = polys[0][0].iter().map(|p| p.0).collect();
603 assert!(xs.iter().cloned().fold(f32::INFINITY, f32::min) >= -2048.0);
604 }
605 g => panic!("{g:?}"),
606 }
607 }
608
609 #[test]
610 fn simplification_drops_vertices_at_low_zoom_only() {
611 let coords: Vec<Json> = (0..=200).map(|i| json!([i as f64 * 0.01, (i as f64 * 0.3).sin() * 0.0001])).collect();
612 let data = json!({"type": "LineString", "coordinates": coords});
613 let idx = GeoJsonIndex::new(&data, GeoJsonOptions { max_zoom: 4, buffer: 2048.0, tolerance: 6.0 });
615 let count = |z: u8| {
616 let n = 1u32 << z;
617 let (x, y) = ((0.5 + 1.0 / 360.0) * n as f64, 0.5 * n as f64);
618 let t = super::super::mvt::decode(&idx.tile(z, x as u32, y as u32)).unwrap();
619 match &t.layers[GEOJSON_LAYER].features[0].geometry {
620 super::super::mvt::Geometry::Lines(ls) => ls.iter().map(|l| l.len()).sum::<usize>(),
621 g => panic!("{g:?}"),
622 }
623 };
624 assert!(count(2) < 10, "below maxzoom the line is simplified");
625 assert_eq!(count(4), 201, "at maxzoom every vertex is kept");
626 }
627}