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
//! Canonical picking contract for Rustial `v1.0`.
//!
//! This module defines the stable engine-owned picking model that host
//! applications should depend on.  It exposes:
//!
//! - **Pick query types** -- [`PickQuery`] (screen, geo, or ray) with filtering options.
//! - **Hit result types** -- [`PickHit`] with provenance, category, and priority.
//! - **Layer queryability** -- [`PickableLayerKind`] documents which native layer
//!   families participate in normal feature picking.
//! - **Hit provenance** -- [`HitProvenance`] distinguishes geometric approximation
//!   from renderer-assisted exact results.
//!
//! # Supported picking contract for `v1.0`
//!
//! - **Terrain** -- exact or near-exact surface recovery via screen-to-geo.
//! - **Vector fill / line / circle / heatmap / fill-extrusion** -- CPU geometric
//!   hit-testing with tolerance.
//! - **Symbols** -- collision-box-based hit-testing.
//! - **Models** -- bounding-radius-based hit-testing with terrain-aware altitude.
//! - **Raster / background / hillshade** -- explicitly **not** normal feature-pick
//!   targets.  A future raster-value API may be introduced separately.
//!
//! # Result sorting rules
//!
//! Pick results ([`PickResult`]) are sorted in two stages:
//!
//! 1. **`layer_priority`** (descending) -- every [`PickHit`] carries a
//!    `layer_priority` derived from the layer's position in the layer stack.
//!    Top-most layers receive the highest priority so the visually front-most
//!    feature appears first.
//!
//! 2. **`distance_meters`** (ascending, within the same priority) -- when two
//!    hits share the same layer priority, the one closest to the query point
//!    wins.  For point and line geometries this is the Euclidean distance in
//!    Web Mercator metres; for polygons that fully contain the query point the
//!    distance is `0.0`.
//!
//! Query results from
//! [`query_rendered_features`](crate::MapState::query_rendered_features) and
//! the `_at_screen` / `_at_geo` / `_along_ray` convenience wrappers apply the
//! same sort but only by `distance_meters` (ascending), because all features
//! already come from a single layer-stack traversal in render order.
//!
//! Box queries
//! ([`query_rendered_features_in_box`](crate::MapState::query_rendered_features_in_box))
//! return features in layer-stack order without distance-based sorting because
//! every intersecting feature is equally "hit" by the rectangle.
//!
//! # Duplicate-suppression rules
//!
//! Both point queries and box queries de-duplicate features that appear in
//! multiple streamed-vector tile payloads (overlapping tile edges).
//! De-duplication is keyed on the triple
//! `(source_id, source_layer, geometry_debug_string)` so the same logical
//! feature carried by two adjacent tiles is returned only once.
//!
//! Symbol queries de-duplicate on `(source_id, source_layer, feature_id)` so
//! a symbol that is placed on multiple tiles (due to label avoidance retries)
//! is returned only once.
//!
//! These rules guarantee stable, reproducible query results regardless of
//! which tiles are currently loaded.
//!
//! # Cross-renderer parity
//!
//! Both `rustial-renderer-wgpu` and `rustial-renderer-bevy` consume the same
//! engine-owned picking surface via [`MapState`](crate::MapState).  Both
//! renderers expose identical `pick()`, `pick_at_screen()`, `pick_at_geo()`,
//! and `pick_along_ray()` convenience methods that delegate to the canonical
//! engine pipeline.  The public API, result format, and prioritization rules
//! are engine-defined and renderer-agnostic.
//!
//! Regression coverage for the stable `v1.0` picking surface now includes
//! explicit tests across both `CameraMode::Perspective` and
//! `CameraMode::Orthographic` and across both stable projections
//! (`WebMercator` and `Equirectangular`), for both screen-coordinate and
//! world-space-ray entry points.

use crate::camera_projection::CameraProjection;
use crate::geometry::PropertyValue;
use crate::query::FeatureState;
#[cfg(test)]
use crate::query::QueryOptions;
use rustial_math::{GeoCoord, TileId};
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// PickableLayerKind
// ---------------------------------------------------------------------------

/// Native layer families that participate in normal feature picking.
///
/// This enum explicitly encodes the `v1.0` picking contract so that
/// unsupported layer kinds are never silently included.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PickableLayerKind {
    /// Vector fill polygons.
    Fill,
    /// Vector line features.
    Line,
    /// Vector circle / point features.
    Circle,
    /// Heatmap source-point features.
    ///
    /// Queries hit the underlying source points, not the blended
    /// heatmap visual.
    Heatmap,
    /// Extruded polygon features.
    ///
    /// Hit-testing uses the 2D footprint in `v1.0` (not height-aware
    /// geometric or renderer-exact).
    FillExtrusion,
    /// Placed symbol features (text / icon).
    ///
    /// Hit-testing uses the placed collision box.
    Symbol,
    /// 3D model instances.
    ///
    /// Hit-testing uses a bounding-radius approximation around the
    /// model anchor, with terrain-aware altitude resolution.
    Model,
}

impl PickableLayerKind {
    /// Whether this layer kind is queryable in `v1.0`.
    #[inline]
    pub fn is_queryable(&self) -> bool {
        true
    }
}

/// Native layer families that are explicitly **not** normal feature-pick
/// targets in `v1.0`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NonPickableLayerKind {
    /// Raster tile imagery.
    Raster,
    /// Background clear / fill layer.
    Background,
    /// Hillshade overlay.
    Hillshade,
}

// ---------------------------------------------------------------------------
// HitProvenance
// ---------------------------------------------------------------------------

/// How a pick hit was resolved.
///
/// This allows callers to understand the precision class of each hit
/// without forcing them to care about internal implementation details.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HitProvenance {
    /// CPU-side feature geometry test (point-in-polygon, segment
    /// distance, bounding-radius, collision-box intersection).
    GeometricApproximation,
    /// Terrain surface recovery from cached elevation data (ray-march
    /// or bilinear interpolation).
    TerrainSurface,
    /// Renderer-owned depth / coordinate / object buffer readback
    /// (future; not yet available in `v1.0`).
    RendererExact,
}

// ---------------------------------------------------------------------------
// HitCategory
// ---------------------------------------------------------------------------

/// Broad category of a pick result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HitCategory {
    /// A terrain surface hit (screen -> geo recovery).
    Terrain,
    /// A vector feature hit (fill, line, circle, heatmap, extrusion).
    Feature,
    /// A placed symbol hit (text / icon collision box).
    Symbol,
    /// A 3D model instance hit.
    Model,
}

// ---------------------------------------------------------------------------
// PickQuery
// ---------------------------------------------------------------------------

/// Input for a pick operation.
///
/// Callers specify one of three entry-point types:
///
/// - **Screen** -- pixel coordinates relative to the viewport origin.
/// - **Geo** -- a geographic coordinate (lat/lon/alt).
/// - **Ray** -- a world-space ray in the active scene projection.
///
/// All three are resolved through the same engine-owned query pipeline.
#[derive(Debug, Clone)]
pub enum PickQuery {
    /// Pick at a screen-space pixel coordinate.
    Screen {
        /// X coordinate in logical pixels (0 = left).
        x: f64,
        /// Y coordinate in logical pixels (0 = top).
        y: f64,
    },
    /// Pick at a geographic coordinate.
    Geo {
        /// Geographic coordinate to query.
        coord: GeoCoord,
    },
    /// Pick along a world-space ray in the active scene projection.
    Ray {
        /// Ray origin in world-space meters.
        origin: glam::DVec3,
        /// Ray direction (will be normalized internally).
        direction: glam::DVec3,
    },
}

impl PickQuery {
    /// Create a screen-space pick query.
    pub fn screen(x: f64, y: f64) -> Self {
        Self::Screen { x, y }
    }

    /// Create a geographic pick query.
    pub fn geo(coord: GeoCoord) -> Self {
        Self::Geo { coord }
    }

    /// Create a ray-based pick query.
    pub fn ray(origin: glam::DVec3, direction: glam::DVec3) -> Self {
        Self::Ray { origin, direction }
    }
}

// ---------------------------------------------------------------------------
// PickOptions
// ---------------------------------------------------------------------------

/// Filtering and behavior options for a pick operation.
#[derive(Debug, Clone)]
pub struct PickOptions {
    /// Restrict results to specific layer ids.
    pub layers: Vec<String>,
    /// Restrict results to specific source ids.
    pub sources: Vec<String>,
    /// Hit tolerance in meters for point and line features.
    pub tolerance_meters: f64,
    /// Whether placed-symbol collision boxes participate in the query.
    pub include_symbols: bool,
    /// Whether 3D model instances participate in the query.
    pub include_models: bool,
    /// Whether terrain surface recovery is included as a hit.
    pub include_terrain_surface: bool,
    /// Maximum number of results to return (0 = unlimited).
    pub limit: usize,
}

impl Default for PickOptions {
    fn default() -> Self {
        Self {
            layers: Vec::new(),
            sources: Vec::new(),
            tolerance_meters: 16.0,
            include_symbols: true,
            include_models: true,
            include_terrain_surface: false,
            limit: 0,
        }
    }
}

impl PickOptions {
    /// Create default pick options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Include terrain surface recovery as a result.
    pub fn with_terrain_surface(mut self) -> Self {
        self.include_terrain_surface = true;
        self
    }

    /// Set the result limit.
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }

    /// Restrict to specific layer ids.
    pub fn with_layers(mut self, layers: Vec<String>) -> Self {
        self.layers = layers;
        self
    }

    /// Restrict to specific source ids.
    pub fn with_sources(mut self, sources: Vec<String>) -> Self {
        self.sources = sources;
        self
    }

    #[cfg(test)]
    /// Convert to the existing QueryOptions type for backward compat.
    pub(crate) fn to_query_options(&self) -> QueryOptions {
        QueryOptions {
            layers: self.layers.clone(),
            sources: self.sources.clone(),
            tolerance_meters: self.tolerance_meters,
            include_symbols: self.include_symbols,
        }
    }
}

// ---------------------------------------------------------------------------
// PickHit
// ---------------------------------------------------------------------------

/// A single hit from a pick operation.
///
/// This is the canonical result type consumed by host applications.
/// It provides identity, geometry, properties, state, distance,
/// provenance, and category metadata for every hit.
#[derive(Debug, Clone)]
pub struct PickHit {
    /// Broad category of this hit.
    pub category: HitCategory,
    /// How this hit was resolved.
    pub provenance: HitProvenance,
    /// Style layer id or runtime layer name that produced the hit.
    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 within the source.
    pub feature_id: Option<String>,
    /// Source-local feature index.
    pub feature_index: Option<usize>,
    /// Feature geometry, when available.
    pub geometry: Option<crate::geometry::Geometry>,
    /// Feature properties, when available.
    pub properties: HashMap<String, PropertyValue>,
    /// Mutable feature-state snapshot at query time.
    pub state: FeatureState,
    /// Distance from the query position in meters.
    pub distance_meters: f64,
    /// Geographic coordinate of the hit point.
    pub hit_coord: Option<GeoCoord>,
    /// Layer-order priority (lower = rendered on top / higher priority).
    ///
    /// This is derived from the reverse layer-stack index so that
    /// top-most rendered layers have the lowest priority value.
    pub layer_priority: u32,
    /// Whether the hit came from a placed symbol collision box.
    pub from_symbol: bool,
}

impl PickHit {
    /// Create a terrain-surface hit.
    pub fn terrain_surface(coord: GeoCoord, elevation: Option<f64>) -> Self {
        Self {
            category: HitCategory::Terrain,
            provenance: HitProvenance::TerrainSurface,
            layer_id: None,
            source_id: None,
            source_layer: None,
            source_tile: None,
            feature_id: None,
            feature_index: None,
            geometry: Some(crate::geometry::Geometry::Point(crate::geometry::Point {
                coord: GeoCoord::new(coord.lat, coord.lon, elevation.unwrap_or(coord.alt)),
            })),
            properties: HashMap::new(),
            state: HashMap::new(),
            distance_meters: 0.0,
            hit_coord: Some(coord),
            layer_priority: u32::MAX,
            from_symbol: false,
        }
    }
}

// ---------------------------------------------------------------------------
// PickResult
// ---------------------------------------------------------------------------

/// Complete result of a pick operation.
///
/// Contains zero or more [`PickHit`]s sorted in priority and distance order,
/// plus metadata about the query itself.
#[derive(Debug, Clone, Default)]
pub struct PickResult {
    /// Ordered hits (highest priority first, then by distance).
    pub hits: Vec<PickHit>,
    /// The resolved geographic coordinate of the query point, if available.
    pub query_coord: Option<GeoCoord>,
    /// The camera projection active at query time.
    pub projection: Option<CameraProjection>,
}

impl PickResult {
    /// Whether the pick produced any hits.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.hits.is_empty()
    }

    /// Number of hits.
    #[inline]
    pub fn len(&self) -> usize {
        self.hits.len()
    }

    /// Iterate hits in priority order.
    pub fn iter(&self) -> impl Iterator<Item = &PickHit> {
        self.hits.iter()
    }

    /// The top-priority hit, if any.
    pub fn first(&self) -> Option<&PickHit> {
        self.hits.first()
    }

    /// Filter hits by category.
    pub fn by_category(&self, category: HitCategory) -> Vec<&PickHit> {
        self.hits
            .iter()
            .filter(|h| h.category == category)
            .collect()
    }

    /// Filter hits to only terrain surface results.
    pub fn terrain_hits(&self) -> Vec<&PickHit> {
        self.by_category(HitCategory::Terrain)
    }

    /// Filter hits to only feature results.
    pub fn feature_hits(&self) -> Vec<&PickHit> {
        self.by_category(HitCategory::Feature)
    }

    /// Filter hits to only symbol results.
    pub fn symbol_hits(&self) -> Vec<&PickHit> {
        self.by_category(HitCategory::Symbol)
    }

    /// Filter hits to only model results.
    pub fn model_hits(&self) -> Vec<&PickHit> {
        self.by_category(HitCategory::Model)
    }
}

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

    #[test]
    fn pickable_layer_kinds_are_all_queryable() {
        assert!(PickableLayerKind::Fill.is_queryable());
        assert!(PickableLayerKind::Line.is_queryable());
        assert!(PickableLayerKind::Circle.is_queryable());
        assert!(PickableLayerKind::Heatmap.is_queryable());
        assert!(PickableLayerKind::FillExtrusion.is_queryable());
        assert!(PickableLayerKind::Symbol.is_queryable());
        assert!(PickableLayerKind::Model.is_queryable());
    }

    #[test]
    fn pick_query_constructors() {
        let screen = PickQuery::screen(400.0, 300.0);
        assert!(matches!(screen, PickQuery::Screen { x: 400.0, y: 300.0 }));

        let geo = PickQuery::geo(GeoCoord::from_lat_lon(51.1, 17.0));
        assert!(matches!(geo, PickQuery::Geo { .. }));

        let ray = PickQuery::ray(glam::DVec3::ZERO, -glam::DVec3::Z);
        assert!(matches!(ray, PickQuery::Ray { .. }));
    }

    #[test]
    fn pick_options_defaults() {
        let opts = PickOptions::default();
        assert!(opts.layers.is_empty());
        assert!(opts.sources.is_empty());
        assert!(opts.include_symbols);
        assert!(opts.include_models);
        assert!(!opts.include_terrain_surface);
        assert_eq!(opts.limit, 0);
    }

    #[test]
    fn pick_options_builder() {
        let opts = PickOptions::new()
            .with_terrain_surface()
            .with_limit(5)
            .with_layers(vec!["layer-a".into()]);
        assert!(opts.include_terrain_surface);
        assert_eq!(opts.limit, 5);
        assert_eq!(opts.layers, vec!["layer-a"]);
    }

    #[test]
    fn pick_result_filtering() {
        let mut result = PickResult::default();
        result.hits.push(PickHit::terrain_surface(
            GeoCoord::from_lat_lon(10.0, 20.0),
            Some(100.0),
        ));
        result.hits.push(PickHit {
            category: HitCategory::Feature,
            provenance: HitProvenance::GeometricApproximation,
            layer_id: Some("fills".into()),
            source_id: None,
            source_layer: None,
            source_tile: None,
            feature_id: Some("42".into()),
            feature_index: Some(42),
            geometry: None,
            properties: HashMap::new(),
            state: HashMap::new(),
            distance_meters: 5.0,
            hit_coord: None,
            layer_priority: 0,
            from_symbol: false,
        });

        assert_eq!(result.len(), 2);
        assert_eq!(result.terrain_hits().len(), 1);
        assert_eq!(result.feature_hits().len(), 1);
        assert_eq!(result.symbol_hits().len(), 0);
        assert_eq!(result.model_hits().len(), 0);
    }

    #[test]
    fn terrain_surface_hit_has_correct_metadata() {
        let hit = PickHit::terrain_surface(GeoCoord::new(10.0, 20.0, 50.0), Some(100.0));
        assert_eq!(hit.category, HitCategory::Terrain);
        assert_eq!(hit.provenance, HitProvenance::TerrainSurface);
        assert!(hit.layer_id.is_none());
        assert!(hit.feature_id.is_none());
        assert_eq!(hit.layer_priority, u32::MAX);
        if let Some(GeoCoord { lat, lon, alt: _ }) = hit.hit_coord {
            assert!((lat - 10.0).abs() < 1e-9);
            assert!((lon - 20.0).abs() < 1e-9);
        }
    }

    #[test]
    fn hit_provenance_distinguishes_methods() {
        assert_ne!(
            HitProvenance::GeometricApproximation,
            HitProvenance::TerrainSurface
        );
        assert_ne!(HitProvenance::TerrainSurface, HitProvenance::RendererExact);
    }

    #[test]
    fn to_query_options_preserves_fields() {
        let opts = PickOptions {
            layers: vec!["a".into()],
            sources: vec!["b".into()],
            tolerance_meters: 32.0,
            include_symbols: false,
            ..Default::default()
        };
        let qo = opts.to_query_options();
        assert_eq!(qo.layers, vec!["a"]);
        assert_eq!(qo.sources, vec!["b"]);
        assert!((qo.tolerance_meters - 32.0).abs() < 1e-9);
        assert!(!qo.include_symbols);
    }
}