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
//! Interaction and query API primitives.
//!
//! This module provides a small engine-owned query surface for source-feature
//! lookup, rendered-feature picking, and feature-state storage keyed by style
//! sources / feature ids.

use crate::geometry::{Feature, Geometry, PropertyValue};
use rustial_math::{GeoCoord, TileId, WebMercator};
use std::collections::HashMap;

/// Mutable per-feature state payload.
pub type FeatureState = HashMap<String, PropertyValue>;

/// Stable feature-state identifier.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FeatureStateId {
    /// Style source id owning the feature.
    pub source_id: String,
    /// Stable feature id within that source.
    pub feature_id: String,
}

impl FeatureStateId {
    /// Create a new feature-state id.
    pub fn new(source_id: impl Into<String>, feature_id: impl Into<String>) -> Self {
        Self {
            source_id: source_id.into(),
            feature_id: feature_id.into(),
        }
    }
}

/// Query filtering options.
#[derive(Debug, Clone, Default)]
pub struct QueryOptions {
    /// Restrict results to specific style layer ids / runtime layer names.
    pub layers: Vec<String>,
    /// Restrict results to specific source ids.
    pub sources: Vec<String>,
    /// Hit tolerance in meters for point/line picking.
    pub tolerance_meters: f64,
    /// Whether placed-symbol collision boxes participate in rendered queries.
    pub include_symbols: bool,
}

impl QueryOptions {
    /// Create default query options.
    pub fn new() -> Self {
        Self {
            layers: Vec::new(),
            sources: Vec::new(),
            tolerance_meters: 16.0,
            include_symbols: true,
        }
    }
}

/// A feature returned by source or rendered query APIs.
#[derive(Debug, Clone)]
pub struct QueriedFeature {
    /// Style layer id or runtime layer name that produced the feature.
    pub layer_id: Option<String>,
    /// Style source id, when known.
    pub source_id: Option<String>,
    /// Style source-layer id, when known.
    pub source_layer: Option<String>,
    /// Tile that supplied the feature, when known.
    pub source_tile: Option<TileId>,
    /// Stable feature id.
    pub feature_id: String,
    /// Source-local feature index.
    pub feature_index: usize,
    /// Feature geometry.
    pub geometry: Geometry,
    /// Feature properties.
    pub properties: HashMap<String, PropertyValue>,
    /// Mutable feature-state snapshot.
    pub state: FeatureState,
    /// Distance from the query position in meters.
    pub distance_meters: f64,
    /// Whether the hit came from the rendered symbol representation.
    pub from_symbol: bool,
}

/// Derive a stable feature id from properties or source-local index.
pub fn feature_id_for_feature(feature: &Feature, feature_index: usize) -> String {
    if let Some(value) = feature.property("id") {
        return property_value_as_feature_id(value).unwrap_or_else(|| feature_index.to_string());
    }
    if let Some(value) = feature.property("feature_id") {
        return property_value_as_feature_id(value).unwrap_or_else(|| feature_index.to_string());
    }
    feature_index.to_string()
}

/// Geometric hit-testing against a feature geometry.
pub fn geometry_hit_distance(
    geometry: &Geometry,
    coord: &GeoCoord,
    tolerance_meters: f64,
) -> Option<f64> {
    match geometry {
        Geometry::Point(point) => {
            let dist = world_distance(coord, &point.coord);
            (dist <= tolerance_meters).then_some(dist)
        }
        Geometry::LineString(line) => {
            line_distance(&line.coords, coord).filter(|distance| *distance <= tolerance_meters)
        }
        Geometry::Polygon(polygon) => polygon_hit_distance(polygon, coord, tolerance_meters),
        Geometry::MultiPoint(points) => points
            .points
            .iter()
            .filter_map(|point| {
                geometry_hit_distance(&Geometry::Point(point.clone()), coord, tolerance_meters)
            })
            .min_by(f64::total_cmp),
        Geometry::MultiLineString(lines) => lines
            .lines
            .iter()
            .filter_map(|line| {
                geometry_hit_distance(&Geometry::LineString(line.clone()), coord, tolerance_meters)
            })
            .min_by(f64::total_cmp),
        Geometry::MultiPolygon(polygons) => polygons
            .polygons
            .iter()
            .filter_map(|polygon| {
                geometry_hit_distance(&Geometry::Polygon(polygon.clone()), coord, tolerance_meters)
            })
            .min_by(f64::total_cmp),
        Geometry::GeometryCollection(geometries) => geometries
            .iter()
            .filter_map(|geometry| geometry_hit_distance(geometry, coord, tolerance_meters))
            .min_by(f64::total_cmp),
    }
}

fn property_value_as_feature_id(value: &PropertyValue) -> Option<String> {
    match value {
        PropertyValue::Null => None,
        PropertyValue::Bool(value) => Some(value.to_string()),
        PropertyValue::Number(value) => Some(value.to_string()),
        PropertyValue::String(value) => Some(value.clone()),
    }
}

fn polygon_hit_distance(
    polygon: &crate::geometry::Polygon,
    coord: &GeoCoord,
    tolerance_meters: f64,
) -> Option<f64> {
    if point_in_ring(&polygon.exterior, coord)
        && !polygon
            .interiors
            .iter()
            .any(|hole| point_in_ring(hole, coord))
    {
        return Some(0.0);
    }

    let mut min_distance = line_distance(&polygon.exterior, coord);
    for hole in &polygon.interiors {
        let hole_distance = line_distance(hole, coord);
        min_distance = match (min_distance, hole_distance) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (Some(a), None) => Some(a),
            (None, Some(b)) => Some(b),
            (None, None) => None,
        };
    }
    min_distance.filter(|distance| *distance <= tolerance_meters)
}

fn line_distance(coords: &[GeoCoord], coord: &GeoCoord) -> Option<f64> {
    if coords.len() < 2 {
        return None;
    }
    let p = world_xy(coord);
    coords
        .windows(2)
        .map(|segment| point_to_segment_distance(p, world_xy(&segment[0]), world_xy(&segment[1])))
        .min_by(f64::total_cmp)
}

fn point_in_ring(ring: &[GeoCoord], coord: &GeoCoord) -> bool {
    if ring.len() < 3 {
        return false;
    }
    let p = world_xy(coord);
    let mut inside = false;
    let mut prev = world_xy(ring.last().expect("ring last"));
    for current_coord in ring {
        let current = world_xy(current_coord);
        let intersects = ((current[1] > p[1]) != (prev[1] > p[1]))
            && (p[0]
                < (prev[0] - current[0]) * (p[1] - current[1])
                    / (prev[1] - current[1]).max(f64::EPSILON)
                    + current[0]);
        if intersects {
            inside = !inside;
        }
        prev = current;
    }
    inside
}

fn point_to_segment_distance(point: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 {
    let ab = [b[0] - a[0], b[1] - a[1]];
    let ap = [point[0] - a[0], point[1] - a[1]];
    let len2 = ab[0] * ab[0] + ab[1] * ab[1];
    if len2 <= f64::EPSILON {
        return ((point[0] - a[0]).powi(2) + (point[1] - a[1]).powi(2)).sqrt();
    }
    let t = ((ap[0] * ab[0] + ap[1] * ab[1]) / len2).clamp(0.0, 1.0);
    let closest = [a[0] + ab[0] * t, a[1] + ab[1] * t];
    ((point[0] - closest[0]).powi(2) + (point[1] - closest[1]).powi(2)).sqrt()
}

fn world_distance(a: &GeoCoord, b: &GeoCoord) -> f64 {
    let a = world_xy(a);
    let b = world_xy(b);
    ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt()
}

fn world_xy(coord: &GeoCoord) -> [f64; 2] {
    let projected = WebMercator::project(coord);
    [projected.position.x, projected.position.y]
}

// ---------------------------------------------------------------------------
// Bounding-box intersection for box queries
// ---------------------------------------------------------------------------

/// Axis-aligned bounding box in Web Mercator world-space, used by box/rectangle
/// rendered-feature queries.
///
/// Coordinates are in the same projected space as [`world_xy`], i.e. Web
/// Mercator metres. `min` is the south-west corner, `max` is the north-east
/// corner.
#[derive(Debug, Clone, Copy)]
pub struct GeoBBox {
    /// Minimum (south-west) corner in projected world space.
    pub min: [f64; 2],
    /// Maximum (north-east) corner in projected world space.
    pub max: [f64; 2],
}

impl GeoBBox {
    /// Build a bounding box from two geographic coordinates.
    ///
    /// The coordinates need not be ordered; the constructor normalises them so
    /// `min <= max` on both axes.
    pub fn from_geo_coords(a: &GeoCoord, b: &GeoCoord) -> Self {
        let pa = world_xy(a);
        let pb = world_xy(b);
        Self {
            min: [pa[0].min(pb[0]), pa[1].min(pb[1])],
            max: [pa[0].max(pb[0]), pa[1].max(pb[1])],
        }
    }

    /// Whether a projected point lies inside this bounding box.
    fn contains_point(&self, p: [f64; 2]) -> bool {
        p[0] >= self.min[0] && p[0] <= self.max[0] && p[1] >= self.min[1] && p[1] <= self.max[1]
    }

    /// Whether another bounding box overlaps this one.
    fn overlaps(&self, other: &GeoBBox) -> bool {
        self.min[0] <= other.max[0]
            && self.max[0] >= other.min[0]
            && self.min[1] <= other.max[1]
            && self.max[1] >= other.min[1]
    }
}

/// Test whether a feature geometry intersects a geographic bounding box.
///
/// Returns `true` when any part of the geometry touches or overlaps the box.
/// The test is performed in Web Mercator projected world space.
///
/// This is the geometric predicate underlying
/// [`MapState::query_rendered_features_in_box`](crate::MapState::query_rendered_features_in_box).
pub fn geometry_intersects_bbox(geometry: &Geometry, bbox: &GeoBBox) -> bool {
    match geometry {
        Geometry::Point(point) => bbox.contains_point(world_xy(&point.coord)),
        Geometry::LineString(line) => linestring_intersects_bbox(&line.coords, bbox),
        Geometry::Polygon(polygon) => polygon_intersects_bbox(polygon, bbox),
        Geometry::MultiPoint(points) => points
            .points
            .iter()
            .any(|p| bbox.contains_point(world_xy(&p.coord))),
        Geometry::MultiLineString(lines) => lines
            .lines
            .iter()
            .any(|line| linestring_intersects_bbox(&line.coords, bbox)),
        Geometry::MultiPolygon(polygons) => polygons
            .polygons
            .iter()
            .any(|poly| polygon_intersects_bbox(poly, bbox)),
        Geometry::GeometryCollection(geometries) => {
            geometries.iter().any(|g| geometry_intersects_bbox(g, bbox))
        }
    }
}

/// Test whether a line string intersects a bounding box.
///
/// A line intersects the box if any vertex lies inside or any segment crosses
/// one of the four box edges.
fn linestring_intersects_bbox(coords: &[GeoCoord], bbox: &GeoBBox) -> bool {
    // Fast check: any vertex inside the box?
    for coord in coords {
        if bbox.contains_point(world_xy(coord)) {
            return true;
        }
    }
    // Segment-edge crossing check.
    for pair in coords.windows(2) {
        let a = world_xy(&pair[0]);
        let b = world_xy(&pair[1]);
        if segment_intersects_bbox(a, b, bbox) {
            return true;
        }
    }
    false
}

/// Test whether a polygon intersects a bounding box.
///
/// A polygon intersects the box if:
/// 1. any vertex of the exterior ring lies inside the box, or
/// 2. any exterior-ring segment crosses a box edge, or
/// 3. the centre of the box lies inside the polygon (polygon fully contains box).
fn polygon_intersects_bbox(polygon: &crate::geometry::Polygon, bbox: &GeoBBox) -> bool {
    // Quick AABB overlap check for the polygon exterior.
    let poly_bbox = ring_bbox(&polygon.exterior);
    if !bbox.overlaps(&poly_bbox) {
        return false;
    }
    // Any exterior vertex inside the box?
    for coord in &polygon.exterior {
        if bbox.contains_point(world_xy(coord)) {
            return true;
        }
    }
    // Any exterior segment crossing a box edge?
    for pair in polygon.exterior.windows(2) {
        let a = world_xy(&pair[0]);
        let b = world_xy(&pair[1]);
        if segment_intersects_bbox(a, b, bbox) {
            return true;
        }
    }
    // Polygon fully encloses the box? Test the box centre.
    let centre_world = rustial_math::WorldCoord::new(
        (bbox.min[0] + bbox.max[0]) * 0.5,
        (bbox.min[1] + bbox.max[1]) * 0.5,
        0.0,
    );
    let centre_geo = WebMercator::unproject(&centre_world);
    if point_in_ring(&polygon.exterior, &centre_geo)
        && !polygon
            .interiors
            .iter()
            .any(|hole| point_in_ring(hole, &centre_geo))
    {
        return true;
    }
    false
}

/// Compute an axis-aligned bounding box for a coordinate ring.
fn ring_bbox(ring: &[GeoCoord]) -> GeoBBox {
    let mut min = [f64::MAX, f64::MAX];
    let mut max = [f64::MIN, f64::MIN];
    for coord in ring {
        let p = world_xy(coord);
        min[0] = min[0].min(p[0]);
        min[1] = min[1].min(p[1]);
        max[0] = max[0].max(p[0]);
        max[1] = max[1].max(p[1]);
    }
    GeoBBox { min, max }
}

/// Test whether a segment (a->b) intersects an axis-aligned bounding box.
///
/// Uses the Liang-Barsky segment-AABB intersection algorithm.
fn segment_intersects_bbox(a: [f64; 2], b: [f64; 2], bbox: &GeoBBox) -> bool {
    let dx = b[0] - a[0];
    let dy = b[1] - a[1];
    let mut t_min = 0.0_f64;
    let mut t_max = 1.0_f64;

    let clips = [
        (-dx, a[0] - bbox.min[0]),
        (dx, bbox.max[0] - a[0]),
        (-dy, a[1] - bbox.min[1]),
        (dy, bbox.max[1] - a[1]),
    ];

    for &(p, q) in &clips {
        if p.abs() < f64::EPSILON {
            // Segment is parallel to this slab.
            if q < 0.0 {
                return false;
            }
        } else {
            let t = q / p;
            if p < 0.0 {
                t_min = t_min.max(t);
            } else {
                t_max = t_max.min(t);
            }
            if t_min > t_max {
                return false;
            }
        }
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::{Feature, LineString, Point, Polygon};
    use std::collections::HashMap;

    #[test]
    fn feature_id_prefers_id_property() {
        let mut properties = HashMap::new();
        properties.insert("id".into(), PropertyValue::String("abc".into()));
        let feature = Feature {
            geometry: Geometry::Point(Point {
                coord: GeoCoord::from_lat_lon(0.0, 0.0),
            }),
            properties,
        };
        assert_eq!(feature_id_for_feature(&feature, 3), "abc");
    }

    #[test]
    fn point_query_uses_tolerance() {
        let geometry = Geometry::Point(Point {
            coord: GeoCoord::from_lat_lon(0.0, 0.0),
        });
        assert!(geometry_hit_distance(&geometry, &GeoCoord::from_lat_lon(0.0, 0.0), 1.0).is_some());
    }

    #[test]
    fn line_query_measures_distance() {
        let geometry = Geometry::LineString(LineString {
            coords: vec![
                GeoCoord::from_lat_lon(0.0, 0.0),
                GeoCoord::from_lat_lon(0.0, 0.001),
            ],
        });
        assert!(
            geometry_hit_distance(&geometry, &GeoCoord::from_lat_lon(0.00001, 0.0005), 32.0)
                .is_some()
        );
    }

    #[test]
    fn polygon_query_hits_inside() {
        let geometry = Geometry::Polygon(Polygon {
            exterior: vec![
                GeoCoord::from_lat_lon(0.0, 0.0),
                GeoCoord::from_lat_lon(0.0, 0.01),
                GeoCoord::from_lat_lon(0.01, 0.01),
                GeoCoord::from_lat_lon(0.01, 0.0),
                GeoCoord::from_lat_lon(0.0, 0.0),
            ],
            interiors: vec![],
        });
        assert_eq!(
            geometry_hit_distance(&geometry, &GeoCoord::from_lat_lon(0.005, 0.005), 1.0),
            Some(0.0)
        );
    }

    // -----------------------------------------------------------------------
    // Bounding-box intersection tests
    // -----------------------------------------------------------------------

    /// Helper: build a bbox from two lat/lon corners.
    fn bbox(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> GeoBBox {
        GeoBBox::from_geo_coords(
            &GeoCoord::from_lat_lon(lat1, lon1),
            &GeoCoord::from_lat_lon(lat2, lon2),
        )
    }

    #[test]
    fn point_inside_bbox() {
        let geom = Geometry::Point(Point {
            coord: GeoCoord::from_lat_lon(0.005, 0.005),
        });
        let b = bbox(0.0, 0.0, 0.01, 0.01);
        assert!(geometry_intersects_bbox(&geom, &b));
    }

    #[test]
    fn point_outside_bbox() {
        let geom = Geometry::Point(Point {
            coord: GeoCoord::from_lat_lon(1.0, 1.0),
        });
        let b = bbox(0.0, 0.0, 0.01, 0.01);
        assert!(!geometry_intersects_bbox(&geom, &b));
    }

    #[test]
    fn line_crossing_bbox() {
        // A line that starts outside the box on one side and ends outside
        // on the other side, passing through the box.
        let geom = Geometry::LineString(LineString {
            coords: vec![
                GeoCoord::from_lat_lon(-0.01, 0.005),
                GeoCoord::from_lat_lon(0.02, 0.005),
            ],
        });
        let b = bbox(0.0, 0.0, 0.01, 0.01);
        assert!(geometry_intersects_bbox(&geom, &b));
    }

    #[test]
    fn line_fully_outside_bbox() {
        let geom = Geometry::LineString(LineString {
            coords: vec![
                GeoCoord::from_lat_lon(1.0, 1.0),
                GeoCoord::from_lat_lon(1.0, 1.01),
            ],
        });
        let b = bbox(0.0, 0.0, 0.01, 0.01);
        assert!(!geometry_intersects_bbox(&geom, &b));
    }

    #[test]
    fn polygon_overlapping_bbox() {
        let geom = Geometry::Polygon(Polygon {
            exterior: vec![
                GeoCoord::from_lat_lon(0.0, 0.0),
                GeoCoord::from_lat_lon(0.0, 0.01),
                GeoCoord::from_lat_lon(0.01, 0.01),
                GeoCoord::from_lat_lon(0.01, 0.0),
                GeoCoord::from_lat_lon(0.0, 0.0),
            ],
            interiors: vec![],
        });
        let b = bbox(0.003, 0.003, 0.007, 0.007);
        assert!(geometry_intersects_bbox(&geom, &b));
    }

    #[test]
    fn polygon_enclosing_bbox() {
        // Large polygon fully enclosing a small box -- should still intersect.
        let geom = Geometry::Polygon(Polygon {
            exterior: vec![
                GeoCoord::from_lat_lon(-1.0, -1.0),
                GeoCoord::from_lat_lon(-1.0, 1.0),
                GeoCoord::from_lat_lon(1.0, 1.0),
                GeoCoord::from_lat_lon(1.0, -1.0),
                GeoCoord::from_lat_lon(-1.0, -1.0),
            ],
            interiors: vec![],
        });
        let b = bbox(0.0, 0.0, 0.01, 0.01);
        assert!(geometry_intersects_bbox(&geom, &b));
    }

    #[test]
    fn polygon_disjoint_from_bbox() {
        let geom = Geometry::Polygon(Polygon {
            exterior: vec![
                GeoCoord::from_lat_lon(10.0, 10.0),
                GeoCoord::from_lat_lon(10.0, 10.01),
                GeoCoord::from_lat_lon(10.01, 10.01),
                GeoCoord::from_lat_lon(10.01, 10.0),
                GeoCoord::from_lat_lon(10.0, 10.0),
            ],
            interiors: vec![],
        });
        let b = bbox(0.0, 0.0, 0.01, 0.01);
        assert!(!geometry_intersects_bbox(&geom, &b));
    }
}