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
//! Geographic and projected coordinate types.
//!
//! # Overview
//!
//! This module defines the two fundamental coordinate types used
//! throughout the rustial workspace:
//!
//! - [`GeoCoord`] -- a position on the Earth's surface in WGS-84
//!   degrees + altitude.
//! - [`WorldCoord`] -- a position in projected world space (meters),
//!   typically EPSG:3857 (Web Mercator).
//!
//! The conversion between them is performed by a [`Projection`]
//! implementation (e.g. [`WebMercator`], [`Equirectangular`]).
//!
//! ```text
//! GeoCoord (lat/lon degrees, WGS-84)
//!     |  Projection::project()
//!     v
//! WorldCoord (meters, EPSG:3857, right-handed Z-up)
//! ```
//!
//! # Coordinate conventions
//!
//! | Type | X / lon | Y / lat | Z / alt |
//! |------|---------|---------|---------|
//! | `GeoCoord` | east (+) / west (-) | north (+) / south (-) | meters above ellipsoid |
//! | `WorldCoord` | east | north | up |
//!
//! # Web Mercator latitude limit
//!
//! The constant [`MAX_MERCATOR_LAT`] (~85.051 129 degrees) is the
//! latitude at which the Mercator projection reaches +/-pi * R.
//! It is derived from `atan(sinh(pi))` converted to degrees.
//! Coordinates beyond this limit produce infinite projected values
//! and are rejected by [`GeoCoord::is_web_mercator_valid`].
//!
//! [`Projection`]: crate::Projection
//! [`WebMercator`]: crate::WebMercator
//! [`Equirectangular`]: crate::Equirectangular

use glam::DVec3;
use std::fmt;

/// Maximum latitude supported by Web Mercator (~85.051 129 degrees).
///
/// Derived from `atan(sinh(pi))` in degrees.  Beyond this latitude the
/// Mercator projection yields infinite Y values.  Used by
/// [`GeoCoord::is_web_mercator_valid`] and
/// [`GeoCoord::clamped_mercator`].
pub(crate) const MAX_MERCATOR_LAT: f64 = 85.051_129;

// ---------------------------------------------------------------------------
// GeoCoord
// ---------------------------------------------------------------------------

/// A geographic coordinate in WGS-84 (latitude / longitude in degrees,
/// altitude in meters).
///
/// # Construction
///
/// | Method | Validation | Altitude |
/// |--------|-----------|----------|
/// | [`new`](Self::new) | `debug_assert` only | explicit |
/// | [`from_lat_lon`](Self::from_lat_lon) | `debug_assert` only | 0.0 |
/// | [`new_checked`](Self::new_checked) | returns `Option` | explicit |
/// | `From<(f64, f64)>` | `debug_assert` only | 0.0 |
/// | `From<(f64, f64, f64)>` | `debug_assert` only | explicit |
/// | `From<[f64; 2]>` | `debug_assert` only | 0.0 |
/// | `From<[f64; 3]>` | `debug_assert` only | explicit |
///
/// # Default
///
/// `Default` returns Null Island: `(0, 0, 0)`.
///
/// # Display
///
/// Formats as `"51.100000 N 17.000000 E 100.0m"` (absolute lat/lon
/// with hemisphere suffix).
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GeoCoord {
    /// Latitude in degrees, positive north (`[-90, 90]`).
    pub lat: f64,
    /// Longitude in degrees, positive east (`[-180, 180]`).
    pub lon: f64,
    /// Altitude above the WGS-84 ellipsoid, in meters.
    pub alt: f64,
}

impl GeoCoord {
    /// Create a new geographic coordinate.
    ///
    /// # Panics (debug only)
    ///
    /// Debug-asserts that latitude is in `[-90, 90]` and longitude is
    /// in `[-180, 180]`, with a small tolerance for floating-point
    /// rounding.  In release builds the values are unchecked -- use
    /// [`new_checked`](Self::new_checked) when the inputs come from
    /// untrusted sources.
    #[inline]
    pub fn new(lat: f64, lon: f64, alt: f64) -> Self {
        const EPS: f64 = 1e-10;
        debug_assert!(
            (-90.0 - EPS..=90.0 + EPS).contains(&lat),
            "latitude {lat} out of range [-90, 90]"
        );
        debug_assert!(
            (-180.0 - EPS..=180.0 + EPS).contains(&lon),
            "longitude {lon} out of range [-180, 180]"
        );
        Self { lat, lon, alt }
    }

    /// Convenience constructor without altitude (defaults to 0.0).
    #[inline]
    pub fn from_lat_lon(lat: f64, lon: f64) -> Self {
        Self::new(lat, lon, 0.0)
    }

    /// Checked constructor that returns `None` for out-of-range values.
    ///
    /// Valid ranges: latitude `[-90, 90]`, longitude `[-180, 180]`.
    /// Altitude is unrestricted.
    #[inline]
    pub fn new_checked(lat: f64, lon: f64, alt: f64) -> Option<Self> {
        if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
            return None;
        }
        Some(Self { lat, lon, alt })
    }

    /// Whether this coordinate is within the valid range for Web
    /// Mercator projection.
    ///
    /// Returns `true` when `|lat| <= 85.051129` and `|lon| <= 180`.
    #[inline]
    pub fn is_web_mercator_valid(&self) -> bool {
        self.lat.abs() <= MAX_MERCATOR_LAT && self.lon.abs() <= 180.0
    }

    /// Clamp latitude to the Web Mercator valid range and **wrap**
    /// longitude to `[-180, 180]`.
    ///
    /// Note: latitude is *clamped* (saturated), but longitude is
    /// *wrapped* via modular arithmetic so that e.g. 200.0 becomes
    /// -160.0.  Altitude is preserved unchanged.
    #[inline]
    pub fn clamped_mercator(&self) -> Self {
        let lat = self.lat.clamp(-MAX_MERCATOR_LAT, MAX_MERCATOR_LAT);
        let mut lon = self.lon % 360.0;
        if lon > 180.0 {
            lon -= 360.0;
        }
        if lon < -180.0 {
            lon += 360.0;
        }
        Self {
            lat,
            lon,
            alt: self.alt,
        }
    }
}

impl Default for GeoCoord {
    /// Returns Null Island: `(lat=0, lon=0, alt=0)`.
    fn default() -> Self {
        Self {
            lat: 0.0,
            lon: 0.0,
            alt: 0.0,
        }
    }
}

impl fmt::Display for GeoCoord {
    /// Formats as `"51.100000 N 17.000000 E 100.0m"`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ns = if self.lat >= 0.0 { 'N' } else { 'S' };
        let ew = if self.lon >= 0.0 { 'E' } else { 'W' };
        write!(
            f,
            "{:.6} {} {:.6} {} {:.1}m",
            self.lat.abs(),
            ns,
            self.lon.abs(),
            ew,
            self.alt
        )
    }
}

// -- From conversions for GeoCoord ----------------------------------------

impl From<(f64, f64)> for GeoCoord {
    /// Create from `(lat, lon)` with altitude 0.
    #[inline]
    fn from((lat, lon): (f64, f64)) -> Self {
        Self::from_lat_lon(lat, lon)
    }
}

impl From<(f64, f64, f64)> for GeoCoord {
    /// Create from `(lat, lon, alt)`.
    #[inline]
    fn from((lat, lon, alt): (f64, f64, f64)) -> Self {
        Self::new(lat, lon, alt)
    }
}

impl From<[f64; 2]> for GeoCoord {
    /// Create from `[lat, lon]` with altitude 0.
    #[inline]
    fn from(arr: [f64; 2]) -> Self {
        Self::from_lat_lon(arr[0], arr[1])
    }
}

impl From<[f64; 3]> for GeoCoord {
    /// Create from `[lat, lon, alt]`.
    #[inline]
    fn from(arr: [f64; 3]) -> Self {
        Self::new(arr[0], arr[1], arr[2])
    }
}

impl From<GeoCoord> for (f64, f64, f64) {
    /// Convert to `(lat, lon, alt)`.
    #[inline]
    fn from(c: GeoCoord) -> Self {
        (c.lat, c.lon, c.alt)
    }
}

impl From<GeoCoord> for [f64; 3] {
    /// Convert to `[lat, lon, alt]`.
    #[inline]
    fn from(c: GeoCoord) -> Self {
        [c.lat, c.lon, c.alt]
    }
}

// ---------------------------------------------------------------------------
// WorldCoord
// ---------------------------------------------------------------------------

/// A position in projected world space (meters, typically EPSG:3857).
///
/// The coordinate system is **right-handed Z-up**:
///
/// - **X** points east
/// - **Y** points north
/// - **Z** points up (altitude / terrain elevation)
///
/// Backed by a [`glam::DVec3`] for f64 precision.  The engine performs
/// all math in f64 and only casts to f32 at GPU upload time
/// (camera-relative to avoid jitter).
///
/// # Default
///
/// `Default` returns the origin `(0, 0, 0)`.
///
/// # Display
///
/// Formats as `"(1234.56, 5678.90, 0.00)m"`.
///
/// # Serde
///
/// When the `serde` feature is enabled, serializes as
/// `{ "x": ..., "y": ..., "z": ... }` (manual impl because `DVec3`
/// does not derive serde).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct WorldCoord {
    /// The 3D position vector in meters (X=east, Y=north, Z=up).
    pub position: DVec3,
}

impl WorldCoord {
    /// Create a new world coordinate from meters.
    #[inline]
    pub fn new(x: f64, y: f64, z: f64) -> Self {
        Self {
            position: DVec3::new(x, y, z),
        }
    }
}

impl Default for WorldCoord {
    /// Returns the origin `(0, 0, 0)`.
    fn default() -> Self {
        Self {
            position: DVec3::ZERO,
        }
    }
}

impl fmt::Display for WorldCoord {
    /// Formats as `"(x, y, z)m"` with 2 decimal places.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "({:.2}, {:.2}, {:.2})m",
            self.position.x, self.position.y, self.position.z
        )
    }
}

// -- From conversions for WorldCoord --------------------------------------

impl From<DVec3> for WorldCoord {
    /// Wrap a `DVec3` as a `WorldCoord`.
    #[inline]
    fn from(v: DVec3) -> Self {
        Self { position: v }
    }
}

impl From<WorldCoord> for DVec3 {
    /// Extract the inner `DVec3`.
    #[inline]
    fn from(c: WorldCoord) -> Self {
        c.position
    }
}

impl From<[f64; 3]> for WorldCoord {
    /// Create from `[x, y, z]` in meters.
    #[inline]
    fn from(arr: [f64; 3]) -> Self {
        Self::new(arr[0], arr[1], arr[2])
    }
}

impl From<WorldCoord> for [f64; 3] {
    /// Convert to `[x, y, z]` in meters.
    #[inline]
    fn from(c: WorldCoord) -> Self {
        [c.position.x, c.position.y, c.position.z]
    }
}

// -- Serde for WorldCoord (manual, because DVec3 has no serde derive) -----

#[cfg(feature = "serde")]
impl serde::Serialize for WorldCoord {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut s = serializer.serialize_struct("WorldCoord", 3)?;
        s.serialize_field("x", &self.position.x)?;
        s.serialize_field("y", &self.position.y)?;
        s.serialize_field("z", &self.position.z)?;
        s.end()
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for WorldCoord {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(serde::Deserialize)]
        struct Helper {
            x: f64,
            y: f64,
            z: f64,
        }
        let h = Helper::deserialize(deserializer)?;
        Ok(Self::new(h.x, h.y, h.z))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- GeoCoord construction --------------------------------------------

    #[test]
    fn default_geo_coord() {
        let c = GeoCoord::default();
        assert_eq!(c.lat, 0.0);
        assert_eq!(c.lon, 0.0);
        assert_eq!(c.alt, 0.0);
    }

    #[test]
    fn geo_coord_checked_valid() {
        assert!(GeoCoord::new_checked(45.0, 90.0, 0.0).is_some());
    }

    #[test]
    fn geo_coord_checked_invalid_lat() {
        assert!(GeoCoord::new_checked(91.0, 0.0, 0.0).is_none());
    }

    #[test]
    fn geo_coord_checked_invalid_lon() {
        assert!(GeoCoord::new_checked(0.0, 181.0, 0.0).is_none());
    }

    #[test]
    fn geo_coord_checked_boundary_values() {
        // Exact boundary values must be accepted.
        assert!(GeoCoord::new_checked(90.0, 180.0, 0.0).is_some());
        assert!(GeoCoord::new_checked(-90.0, -180.0, 0.0).is_some());
    }

    // -- GeoCoord Display -------------------------------------------------

    #[test]
    fn geo_coord_display_north_east() {
        let c = GeoCoord::new(51.1, 17.0, 100.0);
        let s = format!("{c}");
        assert!(s.contains('N'));
        assert!(s.contains('E'));
        assert!(s.contains("100.0m"));
    }

    #[test]
    fn geo_coord_display_south_west() {
        let c = GeoCoord::new(-33.9, -70.6, 0.0);
        let s = format!("{c}");
        assert!(s.contains('S'));
        assert!(s.contains('W'));
    }

    // -- GeoCoord From conversions ----------------------------------------

    #[test]
    fn from_tuple_2() {
        let c: GeoCoord = (51.1, 17.0).into();
        assert_eq!(c.lat, 51.1);
        assert_eq!(c.lon, 17.0);
        assert_eq!(c.alt, 0.0);
    }

    #[test]
    fn from_tuple_3() {
        let c: GeoCoord = (51.1, 17.0, 500.0).into();
        assert_eq!(c.lat, 51.1);
        assert_eq!(c.lon, 17.0);
        assert_eq!(c.alt, 500.0);
    }

    #[test]
    fn from_array_2() {
        let c: GeoCoord = [51.1, 17.0].into();
        assert_eq!(c.lat, 51.1);
        assert_eq!(c.lon, 17.0);
        assert_eq!(c.alt, 0.0);
    }

    #[test]
    fn from_array_3() {
        let c: GeoCoord = [51.1, 17.0, 100.0].into();
        assert_eq!(c.lat, 51.1);
        assert_eq!(c.alt, 100.0);
    }

    #[test]
    fn into_tuple() {
        let c = GeoCoord::new(51.1, 17.0, 100.0);
        let (lat, lon, alt): (f64, f64, f64) = c.into();
        assert_eq!(lat, 51.1);
        assert_eq!(lon, 17.0);
        assert_eq!(alt, 100.0);
    }

    #[test]
    fn into_array() {
        let c = GeoCoord::new(51.1, 17.0, 100.0);
        let arr: [f64; 3] = c.into();
        assert_eq!(arr, [51.1, 17.0, 100.0]);
    }

    // -- GeoCoord Mercator helpers ----------------------------------------

    #[test]
    fn is_web_mercator_valid() {
        assert!(GeoCoord::from_lat_lon(51.0, 17.0).is_web_mercator_valid());
        assert!(!GeoCoord::from_lat_lon(86.0, 17.0).is_web_mercator_valid());
    }

    #[test]
    fn clamped_mercator_positive_overflow() {
        let c = GeoCoord {
            lat: 89.0,
            lon: 200.0,
            alt: 42.0,
        };
        let m = c.clamped_mercator();
        assert!(m.lat <= MAX_MERCATOR_LAT);
        assert!(m.lon >= -180.0 && m.lon <= 180.0);
        // 200 % 360 = 200, then 200 - 360 = -160.
        assert!((m.lon - (-160.0)).abs() < 1e-10);
        // Altitude must be preserved.
        assert_eq!(m.alt, 42.0);
    }

    #[test]
    fn clamped_mercator_negative_overflow() {
        let c = GeoCoord {
            lat: -89.0,
            lon: -200.0,
            alt: 0.0,
        };
        let m = c.clamped_mercator();
        assert!(m.lat >= -MAX_MERCATOR_LAT);
        // -200 % 360 = -200, then -200 + 360 = 160.
        assert!((m.lon - 160.0).abs() < 1e-10);
    }

    #[test]
    fn clamped_mercator_already_valid() {
        let c = GeoCoord::from_lat_lon(51.0, 17.0);
        let m = c.clamped_mercator();
        assert!((m.lat - 51.0).abs() < 1e-10);
        assert!((m.lon - 17.0).abs() < 1e-10);
    }

    // -- WorldCoord construction ------------------------------------------

    #[test]
    fn default_world_coord() {
        let c = WorldCoord::default();
        assert_eq!(c.position, DVec3::ZERO);
    }

    // -- WorldCoord Display -----------------------------------------------

    #[test]
    fn world_coord_display() {
        let c = WorldCoord::new(1.0, 2.0, 3.0);
        let s = format!("{c}");
        assert!(s.contains("1.00"));
        assert!(s.contains("2.00"));
        assert!(s.contains("3.00"));
        assert!(s.ends_with(")m"));
    }

    // -- WorldCoord From conversions --------------------------------------

    #[test]
    fn world_coord_from_dvec3() {
        let v = DVec3::new(1.0, 2.0, 3.0);
        let c: WorldCoord = v.into();
        assert_eq!(c.position, v);
        let back: DVec3 = c.into();
        assert_eq!(back, v);
    }

    #[test]
    fn world_coord_from_array() {
        let c: WorldCoord = [10.0, 20.0, 30.0].into();
        assert_eq!(c.position.x, 10.0);
        assert_eq!(c.position.y, 20.0);
        assert_eq!(c.position.z, 30.0);
    }

    #[test]
    fn world_coord_into_array() {
        let c = WorldCoord::new(10.0, 20.0, 30.0);
        let arr: [f64; 3] = c.into();
        assert_eq!(arr, [10.0, 20.0, 30.0]);
    }
}