// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Distances and directions on a spherical Earth. //! //! The Earth is an ellipsoid a little over a third of a per cent flatter at //! the poles than round, and a sphere of its mean radius puts a distance out //! by at most about half a per cent -- a few hundred metres on a flight //! across a continent. That is well inside what anything here is asked for, //! which is how far away a storm is and which way it lies. Anything wanting //! better measures on the ellipsoid itself, with `Ellipsoid.distance` and //! its neighbors, which follow its geodesics to the nanometre. //! //! Which sphere is a `Sphere`, and nothing about it but its radius. The free //! functions measure on `mean`, the sphere of WGS 84's and GRS 80's mean //! radius. `Ellipsoid.sphere` makes one from another reference ellipsoid or //! from another of its radii, for coordinates on a datum that uses it. The //! choice moves a distance by at most about a third of a per cent between //! the smallest sphere and the largest, and by nothing measurable between //! WGS 84 and GRS 80; it converts no coordinates between datums. //! //! Angles are in degrees at the edges and radians inside, and every function //! takes and gives decimal degrees. const std = @import("std"); const Position = @import("root.zig").Position; /// The Earth's mean radius in metres: GRS 80's R1, the mean of the /// ellipsoid's three semi-axes, (2a + b) / 3, as Moritz gives it. WGS 84's /// ellipsoid differs from GRS 80's by a tenth of a millimetre at the poles, /// so this is WGS 84's too. pub const earth_mean_radius: f64 = 6_371_008.7714; const radians = std.math.degreesToRadians; const degrees = std.math.radiansToDegrees; /// A sphere to measure on, which is to say a radius in metres. pub const Sphere = struct { radius: f64, /// The great-circle distance between two positions, in metres. /// /// The central angle is found as the arctangent of the sine and cosine of /// the angle between the two positions -- the spherical case of Vincenty's /// formula -- which is well conditioned at every distance. The two better /// known formulas each lose precision somewhere: the spherical law of /// cosines for points close together, where it takes the arccosine of a /// number near one, and the haversine formula for points nearly antipodal, /// where it takes the square root of one minus a number near one. Found by /// fuzzing, as a detour through a third point that came out a few /// centimetres shorter than the direct route. /// /// The distance from `a` to `b` is exactly the distance from `b` to `a`, to /// the last bit: the two are put in a fixed order before any arithmetic, /// since the formula's terms round differently when the ends swap places. pub fn distance(sphere: Sphere, a: Position, b: Position) f64 { const swap = a.latitude > b.latitude or (a.latitude == b.latitude and a.longitude > b.longitude); const from = if (swap) b else a; const to = if (swap) a else b; const phi1 = radians(from.latitude); const phi2 = radians(to.latitude); const dlambda = radians(to.longitude - from.longitude); const sin_phi1 = @sin(phi1); const cos_phi1 = @cos(phi1); const sin_phi2 = @sin(phi2); const cos_phi2 = @cos(phi2); const cos_dlambda = @cos(dlambda); const cross_east = cos_phi2 * @sin(dlambda); const cross_north = cos_phi1 * sin_phi2 - sin_phi1 * cos_phi2 * cos_dlambda; const sine = std.math.hypot(cross_east, cross_north); const cosine = sin_phi1 * sin_phi2 + cos_phi1 * cos_phi2 * cos_dlambda; return sphere.radius * std.math.atan2(sine, cosine); } /// Where one arrives setting off from `from` on `bearing` degrees and /// following the great circle for `metres`. /// /// The result's longitude is normalised to [-180, 180) and its altitude is /// `from`'s. /// /// Worked in three dimensions rather than by the usual spherical /// trigonometry. That formula finds the new latitude as an arcsine, and near /// the poles -- where its argument is close to one -- an arcsine loses half /// its digits: setting off for the North Pole from a few tens of kilometres /// away arrived a tenth of a metre short. Here the start is a unit vector, /// the direction of travel is a unit vector in the plane tangent to it, and /// the arrival is the one rotated towards the other by the angle travelled, /// so every step is well conditioned and the latitude comes out of an /// arctangent, which is well conditioned everywhere. pub fn destination(sphere: Sphere, from: Position, bearing: f64, metres: f64) Position { const delta = metres / sphere.radius; const theta = radians(bearing); const phi = radians(from.latitude); const lambda = radians(from.longitude); const sin_phi = @sin(phi); const cos_phi = @cos(phi); const sin_lambda = @sin(lambda); const cos_lambda = @cos(lambda); // Where we start, and the two directions along the ground from there. const start = [3]f64{ cos_phi * cos_lambda, cos_phi * sin_lambda, sin_phi }; const north = [3]f64{ -sin_phi * cos_lambda, -sin_phi * sin_lambda, cos_phi }; const east = [3]f64{ -sin_lambda, cos_lambda, 0 }; var arrived: [3]f64 = undefined; for (&arrived, start, north, east) |*out, s, n, e| { const heading = n * @cos(theta) + e * @sin(theta); out.* = s * @cos(delta) + heading * @sin(delta); } const latitude = std.math.atan2(arrived[2], std.math.hypot(arrived[0], arrived[1])); const longitude = std.math.atan2(arrived[1], arrived[0]); return .{ .longitude = normalizeLongitude(degrees(longitude)), .latitude = degrees(latitude), .altitude = from.altitude, }; } }; /// The sphere of the Earth's mean radius, `earth_mean_radius`, which the /// free functions here measure on. pub const mean: Sphere = .{ .radius = earth_mean_radius }; /// The great-circle distance between two positions, in metres, on `mean`. /// See `Sphere.distance`. pub fn distance(a: Position, b: Position) f64 { return mean.distance(a, b); } /// The direction to set off in from `from` to reach `to` along a great /// circle: degrees clockwise from true north, 0 to 360. /// /// Only the *initial* bearing. Along a great circle the bearing changes, so /// the direction at the far end is generally different; and between two /// positions that are the same, or antipodal, there is no direction to give /// and the answer is whatever the arithmetic makes of it. pub fn initialBearing(from: Position, to: Position) f64 { const phi1 = radians(from.latitude); const phi2 = radians(to.latitude); const dlambda = radians(to.longitude - from.longitude); const y = @sin(dlambda) * @cos(phi2); const x = @cos(phi1) * @sin(phi2) - @sin(phi1) * @cos(phi2) * @cos(dlambda); return normalizeBearing(degrees(std.math.atan2(y, x))); } /// Where one arrives setting off from `from` on `bearing` degrees and /// following the great circle on `mean` for `metres`. See /// `Sphere.destination`. pub fn destination(from: Position, bearing: f64, metres: f64) Position { return mean.destination(from, bearing, metres); } /// `longitude` as the equivalent in [-180, 180). pub fn normalizeLongitude(longitude: f64) f64 { return @mod(longitude + 180, 360) - 180; } /// `bearing` as the equivalent in [0, 360). pub fn normalizeBearing(bearing: f64) f64 { const b = @mod(bearing, 360); // `@mod` of a tiny negative number can round to exactly 360. return if (b >= 360) 0 else b; } const testing = std.testing; fn expectNear(expected: f64, actual: f64, tolerance: f64) !void { try testing.expectApproxEqAbs(expected, actual, tolerance); } test "distances that follow from the radius" { const origin: Position = .{ .longitude = 0, .latitude = 0 }; // A degree of any great circle. try expectNear(earth_mean_radius * std.math.pi / 180, distance(origin, .{ .longitude = 0, .latitude = 1 }), 1e-6); try expectNear(earth_mean_radius * std.math.pi / 180, distance(origin, .{ .longitude = 1, .latitude = 0 }), 1e-6); // A quarter of the way round, and halfway: the antipodes. try expectNear(earth_mean_radius * std.math.pi / 2, distance(origin, .{ .longitude = 0, .latitude = 90 }), 1e-6); try expectNear(earth_mean_radius * std.math.pi, distance(origin, .{ .longitude = 180, .latitude = 0 }), 1e-6); // Nowhere at all. try expectNear(0, distance(origin, origin), 1e-9); // Across the antimeridian, the short way. try expectNear( 2 * earth_mean_radius * std.math.pi / 180, distance(.{ .longitude = 179, .latitude = 0 }, .{ .longitude = -179, .latitude = 0 }), 1e-6, ); } test "a short distance keeps its precision" { // A metre north: where the law of cosines would round to nothing. const here: Position = .{ .longitude = -93.625, .latitude = 41.5868 }; const there: Position = .{ .longitude = -93.625, .latitude = 41.5868 + 1 / (earth_mean_radius * std.math.pi / 180) }; try expectNear(1, distance(here, there), 1e-6); } test "a nearly antipodal distance keeps its precision" { // A metre short of halfway round, where the haversine formula's square // root of one minus a number near one would lose most of it. const metre = 180 / (earth_mean_radius * std.math.pi); const here: Position = .{ .longitude = 0, .latitude = 0 }; const there: Position = .{ .longitude = 180 - metre, .latitude = 0 }; try expectNear(earth_mean_radius * std.math.pi - 1, distance(here, there), 1e-6); try testing.expectEqual(distance(here, there), distance(there, here)); } test "setting off for the pole from near it arrives there" { // The fuzzer's finding: from 48 km short of the pole, an arcsine-based // destination fell a tenth of a metre short. const near: Position = .{ .longitude = 0.0006, .latitude = 89.566 }; const pole: Position = .{ .longitude = 177.44, .latitude = 90 }; const arrived = destination(near, initialBearing(near, pole), distance(near, pole)); try expectNear(0, distance(arrived, pole), 1e-6); } test "bearings run clockwise from north" { const origin: Position = .{ .longitude = 0, .latitude = 0 }; try expectNear(0, initialBearing(origin, .{ .longitude = 0, .latitude = 1 }), 1e-9); try expectNear(90, initialBearing(origin, .{ .longitude = 1, .latitude = 0 }), 1e-9); try expectNear(180, initialBearing(origin, .{ .longitude = 0, .latitude = -1 }), 1e-9); try expectNear(270, initialBearing(origin, .{ .longitude = -1, .latitude = 0 }), 1e-9); } test "destination undoes distance and bearing" { const pairs = [_][2]Position{ .{ .{ .longitude = -93.625, .latitude = 41.5868 }, .{ .longitude = -87.6298, .latitude = 41.8781 } }, .{ .{ .longitude = 151.2, .latitude = -33.9 }, .{ .longitude = -122.4, .latitude = 37.8 } }, .{ .{ .longitude = 179.5, .latitude = 10 }, .{ .longitude = -179.5, .latitude = -10 } }, }; for (pairs) |pair| { const arrived = destination(pair[0], initialBearing(pair[0], pair[1]), distance(pair[0], pair[1])); try expectNear(0, distance(arrived, pair[1]), 1e-3); } } test "destination keeps the altitude and normalises longitude" { const start: Position = .{ .longitude = 179, .latitude = 0, .altitude = 12 }; const end = destination(start, 90, 2 * earth_mean_radius * std.math.pi / 180); try expectNear(-179, end.longitude, 1e-9); try testing.expectEqual(@as(?f64, 12), end.altitude); } test "a sphere's distances scale with its radius" { const here: Position = .{ .longitude = -93.625, .latitude = 41.5868 }; const there: Position = .{ .longitude = 151.2, .latitude = -33.9 }; const half: Sphere = .{ .radius = earth_mean_radius / 2 }; try expectNear(distance(here, there) / 2, half.distance(here, there), 1e-6); } test "destination undoes distance and bearing on another sphere" { const clarke = @import("Ellipsoid.zig").epsg.clarke_1866.sphere(.polar); const here: Position = .{ .longitude = -93.625, .latitude = 41.5868 }; const there: Position = .{ .longitude = 151.2, .latitude = -33.9 }; const arrived = clarke.destination(here, initialBearing(here, there), clarke.distance(here, there)); try expectNear(0, clarke.distance(arrived, there), 1e-3); } test normalizeLongitude { try testing.expectEqual(@as(f64, -180), normalizeLongitude(180)); try testing.expectEqual(@as(f64, -179), normalizeLongitude(181)); try testing.expectEqual(@as(f64, 179), normalizeLongitude(-181)); try testing.expectEqual(@as(f64, 10), normalizeLongitude(370)); } test normalizeBearing { try testing.expectEqual(@as(f64, 270), normalizeBearing(-90)); try testing.expectEqual(@as(f64, 0), normalizeBearing(360)); try testing.expectEqual(@as(f64, 0), normalizeBearing(-1e-300)); }