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
//! Geodesic calculations on an ellipsoid using Vincenty formulae.
//!
//! This module solves the two classical geodesic problems on an oblate
//! ellipsoid:
//!
//! | Problem | Function | Description |
//! |---------|----------|-------------|
//! | **Inverse** | [`geodesic_distance`] | Distance and azimuths between two points. |
//! | **Direct** | [`geodesic_destination`] | Destination given start, azimuth, distance. |
//!
//! The default helpers operate on WGS-84; the `_on` variants accept any
//! [`Ellipsoid`].
//!
//! # Algorithm
//!
//! Both solvers implement the iterative Vincenty formulae as described in:
//!
//! > T. Vincenty, "Direct and Inverse Solutions of Geodesics on the Ellipsoid
//! > with Application of Nested Equations", *Survey Review* **23**(176),
//! > April 1975, pp. 88–93.
//!
//! # Numerical behavior
//!
//! - **Accuracy:** sub-millimeter for all well-conditioned pairs on WGS-84.
//! - **Convergence:** up to [`MAX_ITERATIONS`] (200) iterations with a
//!   tolerance of 1 × 10⁻¹² radians (~0.006 mm on Earth).
//! - **Near-antipodal failure:** Vincenty can fail to converge when the two
//!   points are nearly diametrically opposite.  In those cases a
//!   [`VincentyConvergenceError`] is returned instead of panicking.
//!   Callers needing guaranteed convergence for arbitrary inputs should
//!   consider a Karney-class algorithm as a future enhancement.
//! - **Coincident points:** detected early (sin σ < 10⁻¹⁵) and return
//!   distance = 0, azimuths = 0.
//! - **Equatorial paths:** the cos²α ≈ 0 guard prevents division-by-zero
//!   when both points lie on the equator.
//!
//! # Altitude
//!
//! Altitude (`alt`) is **not** used in the geodesic computation.  The direct
//! solver copies the start point's altitude to the destination unchanged.

use crate::coord::GeoCoord;
use crate::ellipsoid::Ellipsoid;
use std::f64::consts::PI;
use thiserror::Error;

// ---------------------------------------------------------------------------
// Error and result types
// ---------------------------------------------------------------------------

/// Error returned when a geodesic computation fails to converge.
///
/// This typically occurs for near-antipodal point pairs where the Vincenty
/// iteration oscillates without settling.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("Vincenty iteration did not converge after {0} iterations (near-antipodal points)")]
pub struct VincentyConvergenceError(u32);

impl VincentyConvergenceError {
    /// Number of iterations that were attempted before giving up.
    #[inline]
    pub fn iterations(&self) -> u32 {
        self.0
    }
}

/// Result of the inverse geodesic problem.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GeodesicResult {
    /// Distance between the two points in meters.
    pub distance: f64,
    /// Forward azimuth at the start point, in radians (0 = north, clockwise).
    pub azimuth_start: f64,
    /// Forward azimuth at the end point, in radians.
    pub azimuth_end: f64,
}

// ---------------------------------------------------------------------------
// Iteration parameters
// ---------------------------------------------------------------------------

/// Maximum Vincenty iterations before declaring non-convergence.
const MAX_ITERATIONS: u32 = 200;

/// Convergence threshold in radians (~0.006 mm on Earth's surface).
const CONVERGENCE: f64 = 1e-12;

// ---------------------------------------------------------------------------
// Longitude normalization helpers
// ---------------------------------------------------------------------------

/// Normalize a radian delta-longitude into `[-π, π]`.
///
/// Ensures the inverse solve always follows the shortest (antimeridian-aware)
/// great-elliptic path between the two points.
#[inline]
fn normalize_delta_lon_radians(mut lambda: f64) -> f64 {
    while lambda > PI {
        lambda -= 2.0 * PI;
    }
    while lambda < -PI {
        lambda += 2.0 * PI;
    }
    lambda
}

/// Wrap a degree longitude into `[-180, 180]`.
///
/// Used by the direct solver to keep the output coordinate in the canonical
/// geographic range.
#[inline]
fn wrap_lon_degrees(mut lon: f64) -> f64 {
    while lon > 180.0 {
        lon -= 360.0;
    }
    while lon < -180.0 {
        lon += 360.0;
    }
    lon
}

// ---------------------------------------------------------------------------
// Inverse problem (distance + azimuths)
// ---------------------------------------------------------------------------

/// Compute the geodesic distance and azimuths between two geographic
/// coordinates on the WGS-84 ellipsoid using the Vincenty inverse formula.
///
/// Returns [`Err`] only for near-antipodal pairs where the iteration
/// fails to converge.
pub fn geodesic_distance(
    from: &GeoCoord,
    to: &GeoCoord,
) -> Result<GeodesicResult, VincentyConvergenceError> {
    geodesic_distance_on(from, to, &Ellipsoid::WGS84)
}

/// Compute the geodesic distance on an arbitrary ellipsoid.
///
/// See [`geodesic_distance`] for behavioral details.
pub fn geodesic_distance_on(
    from: &GeoCoord,
    to: &GeoCoord,
    ellipsoid: &Ellipsoid,
) -> Result<GeodesicResult, VincentyConvergenceError> {
    let a = ellipsoid.a;
    let f = ellipsoid.f;
    let b = ellipsoid.b;

    // --- Reduced latitudes (parametric latitude on the auxiliary sphere) ---
    let u1 = ((1.0 - f) * from.lat.to_radians().tan()).atan();
    let u2 = ((1.0 - f) * to.lat.to_radians().tan()).atan();
    let (sin_u1, cos_u1) = u1.sin_cos();
    let (sin_u2, cos_u2) = u2.sin_cos();

    // Difference in longitude on the auxiliary sphere, normalized to [-π, π].
    let l = normalize_delta_lon_radians((to.lon - from.lon).to_radians());
    let mut lambda = l;

    let mut sin_sigma;
    let mut cos_sigma;
    let mut sigma;
    let mut sin_alpha;
    let mut cos2_alpha;
    let mut cos_2sigma_m;

    // --- Vincenty iteration ---
    for i in 0..MAX_ITERATIONS {
        let (sin_lambda, cos_lambda) = lambda.sin_cos();

        // Eq. (14): sin σ
        sin_sigma = ((cos_u2 * sin_lambda).powi(2)
            + (cos_u1 * sin_u2 - sin_u1 * cos_u2 * cos_lambda).powi(2))
        .sqrt();

        // Coincident-point fast path.
        if sin_sigma < 1e-15 {
            return Ok(GeodesicResult {
                distance: 0.0,
                azimuth_start: 0.0,
                azimuth_end: 0.0,
            });
        }

        // Eq. (15): cos σ
        cos_sigma = sin_u1 * sin_u2 + cos_u1 * cos_u2 * cos_lambda;
        // Eq. (16): σ
        sigma = sin_sigma.atan2(cos_sigma);

        // Eq. (17): sin α  (α = azimuth of the geodesic at the equator)
        sin_alpha = cos_u1 * cos_u2 * sin_lambda / sin_sigma;
        cos2_alpha = 1.0 - sin_alpha * sin_alpha;

        // Eq. (18): cos 2σ_m — guarded for equatorial paths (cos²α ≈ 0).
        cos_2sigma_m = if cos2_alpha.abs() < 1e-15 {
            0.0
        } else {
            cos_sigma - 2.0 * sin_u1 * sin_u2 / cos2_alpha
        };

        // Eq. (10): C
        let c = f / 16.0 * cos2_alpha * (4.0 + f * (4.0 - 3.0 * cos2_alpha));

        // Eq. (11): updated λ
        let lambda_prev = lambda;
        lambda = l
            + (1.0 - c)
                * f
                * sin_alpha
                * (sigma
                    + c * sin_sigma
                        * (cos_2sigma_m
                            + c * cos_sigma * (-1.0 + 2.0 * cos_2sigma_m * cos_2sigma_m)));

        if (lambda - lambda_prev).abs() < CONVERGENCE {
            // --- Converged: compute final distance and azimuths ---

            // Eq. (3): u²
            let u_sq = cos2_alpha * (a * a - b * b) / (b * b);
            // Eq. (3): A
            let cap_a =
                1.0 + u_sq / 16384.0 * (4096.0 + u_sq * (-768.0 + u_sq * (320.0 - 175.0 * u_sq)));
            // Eq. (4): B
            let cap_b = u_sq / 1024.0 * (256.0 + u_sq * (-128.0 + u_sq * (74.0 - 47.0 * u_sq)));

            // Eq. (6): Δσ
            let delta_sigma = cap_b
                * sin_sigma
                * (cos_2sigma_m
                    + cap_b / 4.0
                        * (cos_sigma * (-1.0 + 2.0 * cos_2sigma_m * cos_2sigma_m)
                            - cap_b / 6.0
                                * cos_2sigma_m
                                * (-3.0 + 4.0 * sin_sigma * sin_sigma)
                                * (-3.0 + 4.0 * cos_2sigma_m * cos_2sigma_m)));

            // Eq. (19): geodesic distance
            let distance = b * cap_a * (sigma - delta_sigma);

            // Eq. (20) & (21): forward azimuths, normalized to [0, 2π).
            let (sin_lam, cos_lam) = lambda.sin_cos();
            let az_start = (cos_u2 * sin_lam).atan2(cos_u1 * sin_u2 - sin_u1 * cos_u2 * cos_lam);
            let az_end = (cos_u1 * sin_lam).atan2(-sin_u1 * cos_u2 + cos_u1 * sin_u2 * cos_lam);

            return Ok(GeodesicResult {
                distance,
                azimuth_start: (az_start + 2.0 * PI) % (2.0 * PI),
                azimuth_end: (az_end + 2.0 * PI) % (2.0 * PI),
            });
        }

        if i == MAX_ITERATIONS - 1 {
            return Err(VincentyConvergenceError(MAX_ITERATIONS));
        }
    }

    Err(VincentyConvergenceError(MAX_ITERATIONS))
}

// ---------------------------------------------------------------------------
// Direct problem (destination from azimuth + distance)
// ---------------------------------------------------------------------------

/// Solve the direct geodesic problem: given a start point, azimuth (radians,
/// 0 = north, clockwise), and distance (meters), compute the destination
/// point on the WGS-84 ellipsoid.
///
/// Returns [`Err`] only if the iteration fails to converge (extremely rare
/// for the direct problem).
pub fn geodesic_destination(
    from: &GeoCoord,
    azimuth: f64,
    distance: f64,
) -> Result<GeoCoord, VincentyConvergenceError> {
    geodesic_destination_on(from, azimuth, distance, &Ellipsoid::WGS84)
}

/// Solve the direct geodesic problem on an arbitrary ellipsoid.
///
/// See [`geodesic_destination`] for behavioral details.
pub fn geodesic_destination_on(
    from: &GeoCoord,
    azimuth: f64,
    distance: f64,
    ellipsoid: &Ellipsoid,
) -> Result<GeoCoord, VincentyConvergenceError> {
    // Zero-distance fast path: return the start point unchanged.
    if distance.abs() < 1e-15 {
        return Ok(*from);
    }

    let a = ellipsoid.a;
    let f = ellipsoid.f;
    let b = ellipsoid.b;

    let (sin_az, cos_az) = azimuth.sin_cos();
    let tan_u1 = (1.0 - f) * from.lat.to_radians().tan();
    let cos_u1 = 1.0 / (1.0 + tan_u1 * tan_u1).sqrt();
    let sin_u1 = tan_u1 * cos_u1;

    // σ₁ = angular distance on the sphere from the equator to the start.
    let sigma1 = tan_u1.atan2(cos_az);
    let sin_alpha = cos_u1 * sin_az;
    let cos2_alpha = 1.0 - sin_alpha * sin_alpha;

    // u² and series coefficients A, B (same as inverse).
    let u_sq = cos2_alpha * (a * a - b * b) / (b * b);
    let cap_a = 1.0 + u_sq / 16384.0 * (4096.0 + u_sq * (-768.0 + u_sq * (320.0 - 175.0 * u_sq)));
    let cap_b = u_sq / 1024.0 * (256.0 + u_sq * (-128.0 + u_sq * (74.0 - 47.0 * u_sq)));

    // Initial estimate of σ (angular distance on the auxiliary sphere).
    let mut sigma = distance / (b * cap_a);

    // --- Vincenty iteration for σ ---
    for i in 0..MAX_ITERATIONS {
        let cos_2sigma_m = (2.0 * sigma1 + sigma).cos();
        let sin_sigma = sigma.sin();
        let cos_sigma = sigma.cos();

        let delta_sigma = cap_b
            * sin_sigma
            * (cos_2sigma_m
                + cap_b / 4.0
                    * (cos_sigma * (-1.0 + 2.0 * cos_2sigma_m * cos_2sigma_m)
                        - cap_b / 6.0
                            * cos_2sigma_m
                            * (-3.0 + 4.0 * sin_sigma * sin_sigma)
                            * (-3.0 + 4.0 * cos_2sigma_m * cos_2sigma_m)));

        let sigma_prev = sigma;
        sigma = distance / (b * cap_a) + delta_sigma;

        if (sigma - sigma_prev).abs() < CONVERGENCE {
            // --- Converged: compute destination lat/lon ---
            let sin_sigma = sigma.sin();
            let cos_sigma = sigma.cos();
            let cos_2sigma_m = (2.0 * sigma1 + sigma).cos();

            let lat2 = (sin_u1 * cos_sigma + cos_u1 * sin_sigma * cos_az).atan2(
                (1.0 - f)
                    * (sin_alpha * sin_alpha
                        + (sin_u1 * sin_sigma - cos_u1 * cos_sigma * cos_az).powi(2))
                    .sqrt(),
            );

            let lambda =
                (sin_sigma * sin_az).atan2(cos_u1 * cos_sigma - sin_u1 * sin_sigma * cos_az);
            let c = f / 16.0 * cos2_alpha * (4.0 + f * (4.0 - 3.0 * cos2_alpha));
            let l = lambda
                - (1.0 - c)
                    * f
                    * sin_alpha
                    * (sigma
                        + c * sin_sigma
                            * (cos_2sigma_m
                                + c * cos_sigma * (-1.0 + 2.0 * cos_2sigma_m * cos_2sigma_m)));

            let lon2 = wrap_lon_degrees((from.lon.to_radians() + l).to_degrees());

            return Ok(GeoCoord::new(lat2.to_degrees(), lon2, from.alt));
        }

        if i == MAX_ITERATIONS - 1 {
            return Err(VincentyConvergenceError(MAX_ITERATIONS));
        }
    }

    Err(VincentyConvergenceError(MAX_ITERATIONS))
}

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

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

    // -- Inverse: basic cases ---------------------------------------------

    #[test]
    fn same_point_zero_distance() {
        let p = GeoCoord::from_lat_lon(45.0, 10.0);
        let result = geodesic_distance(&p, &p).unwrap();
        assert!(result.distance < 1e-6);
    }

    #[test]
    fn known_distance_london_paris() {
        // London (51.5074 N, 0.1278 W) to Paris (48.8566 N, 2.3522 E)
        // Vincenty gives ~343.5 km.
        let london = GeoCoord::from_lat_lon(51.5074, -0.1278);
        let paris = GeoCoord::from_lat_lon(48.8566, 2.3522);
        let result = geodesic_distance(&london, &paris).unwrap();
        assert!((result.distance - 343_500.0).abs() < 1500.0);
    }

    #[test]
    fn equatorial_points() {
        // 1 degree along the equator ~ 111,319 m.
        let a = GeoCoord::from_lat_lon(0.0, 0.0);
        let b = GeoCoord::from_lat_lon(0.0, 1.0);
        let result = geodesic_distance(&a, &b).unwrap();
        assert!((result.distance - 111_319.0).abs() < 100.0);
    }

    // -- Inverse: symmetry ------------------------------------------------

    #[test]
    fn inverse_is_symmetric() {
        let a = GeoCoord::from_lat_lon(40.0, -74.0);
        let b = GeoCoord::from_lat_lon(51.5, -0.1);
        let ab = geodesic_distance(&a, &b).unwrap();
        let ba = geodesic_distance(&b, &a).unwrap();
        assert!((ab.distance - ba.distance).abs() < 1e-6);
    }

    // -- Inverse: antimeridian --------------------------------------------

    #[test]
    fn inverse_crosses_antimeridian_short_path() {
        let a = GeoCoord::from_lat_lon(10.0, 179.0);
        let b = GeoCoord::from_lat_lon(10.0, -179.0);
        let result = geodesic_distance(&a, &b).unwrap();
        // Should follow the short dateline crossing (~220 km), not almost full globe.
        assert!(result.distance > 100_000.0);
        assert!(result.distance < 500_000.0);
    }

    // -- Inverse: near-antipodal convergence failure ----------------------

    #[test]
    fn near_antipodal_returns_error() {
        let a = GeoCoord::from_lat_lon(0.0, 0.0);
        let b = GeoCoord::from_lat_lon(0.5, 179.7);
        // Near-antipodal on the equator: Vincenty may fail to converge.
        let result = geodesic_distance(&a, &b);
        // We accept either a converged result or a convergence error --
        // the important contract is that we never panic.
        if let Ok(r) = result {
            assert!(r.distance > 1e7);
        }
    }

    // -- Direct: basic cases ----------------------------------------------

    #[test]
    fn direct_roundtrip() {
        let start = GeoCoord::from_lat_lon(40.0, -74.0);
        let azimuth = 0.8; // ~45.8 degrees
        let dist = 500_000.0; // 500 km

        let dest = geodesic_destination(&start, azimuth, dist).unwrap();
        let inv = geodesic_distance(&start, &dest).unwrap();
        assert!((inv.distance - dist).abs() < 0.01);
    }

    #[test]
    fn direct_due_north() {
        let start = GeoCoord::from_lat_lon(0.0, 0.0);
        let dest = geodesic_destination(&start, 0.0, 1_000_000.0).unwrap();
        // Should be roughly 9.04 degrees north.
        assert!(dest.lat > 8.0 && dest.lat < 10.0);
        assert!(dest.lon.abs() < 0.001);
    }

    // -- Direct: zero distance --------------------------------------------

    #[test]
    fn direct_zero_distance_returns_start() {
        let start = GeoCoord::from_lat_lon(35.0, 139.0);
        let dest = geodesic_destination(&start, 1.23, 0.0).unwrap();
        assert!((dest.lat - start.lat).abs() < 1e-12);
        assert!((dest.lon - start.lon).abs() < 1e-12);
    }

    // -- Direct: longitude wrapping ---------------------------------------

    #[test]
    fn direct_wraps_longitude_range() {
        let start = GeoCoord::from_lat_lon(0.0, 179.8);
        let dest = geodesic_destination(&start, PI / 2.0, 100_000.0).unwrap();
        assert!((-180.0..=180.0).contains(&dest.lon));
    }

    // -- Altitude passthrough ---------------------------------------------

    #[test]
    fn altitude_passthrough_inverse() {
        let a = GeoCoord::new(0.0, 0.0, 1234.5);
        let b = GeoCoord::new(1.0, 1.0, 9999.0);
        let result = geodesic_distance(&a, &b).unwrap();
        // Altitude must not affect the distance calculation.
        let a0 = GeoCoord::from_lat_lon(0.0, 0.0);
        let b0 = GeoCoord::from_lat_lon(1.0, 1.0);
        let result0 = geodesic_distance(&a0, &b0).unwrap();
        assert!((result.distance - result0.distance).abs() < 1e-6);
    }

    #[test]
    fn altitude_passthrough_direct() {
        let start = GeoCoord::new(0.0, 0.0, 500.0);
        let dest = geodesic_destination(&start, 0.0, 100_000.0).unwrap();
        assert!((dest.alt - 500.0).abs() < 1e-12);
    }
}