proj-core 0.2.0

Pure-Rust coordinate transformation library with no C dependencies
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
//! Embedded EPSG database — zero-allocation lookup from a compact binary blob.
//!
//! The binary data is generated by `gen-reference/src/gen_registry.rs` from proj.db
//! and embedded at compile time via `include_bytes!()`.
//!
//! ## Binary format
//!
//! All multi-byte integers are little-endian. All floats are IEEE 754 little-endian.
//!
//! ```text
//! Header (16 bytes):
//!   [0..4]   u32  magic = 0x45505347 ("EPSG")
//!   [4..6]   u16  version = 2
//!   [6..8]   u16  num_ellipsoids
//!   [8..10]  u16  num_datums
//!   [10..12] u16  num_geographic_crs
//!   [12..16] u32  num_projected_crs
//!
//! Ellipsoid table (sorted by EPSG code):
//!   Each record = 20 bytes:
//!     [0..4]   u32  epsg_code
//!     [4..12]  f64  semi_major_axis (meters)
//!     [12..20] f64  inverse_flattening (0.0 = sphere)
//!
//! Datum table (sorted by EPSG code):
//!   Each record = 64 bytes:
//!     [0..4]   u32  epsg_code
//!     [4..8]   u32  ellipsoid_epsg_code
//!     [8..16]  f64  dx (Helmert translation, meters)
//!     [16..24] f64  dy
//!     [24..32] f64  dz
//!     [32..40] f64  rx (rotation, arc-seconds)
//!     [40..48] f64  ry
//!     [48..56] f64  rz
//!     [56..64] f64  ds (scale, ppm)
//!     (all zeros = no Helmert / WGS84-compatible)
//!
//! Geographic CRS table (sorted by EPSG code):
//!   Each record = 8 bytes:
//!     [0..4]   u32  epsg_code
//!     [4..8]   u32  datum_epsg_code
//!
//! Projected CRS table (sorted by EPSG code):
//!   Each record = 80 bytes:
//!     [0..4]   u32  epsg_code
//!     [4..8]   u32  datum_epsg_code
//!     [8..9]   u8   method_id (see METHOD_* constants)
//!     [9..16]  [u8; 7] reserved/padding
//!     [16..24] f64  linear_unit_to_meter
//!     [24..32] f64  param0 (lon0 / central_meridian, degrees)
//!     [32..40] f64  param1 (lat0 / lat_ts, degrees)
//!     [40..48] f64  param2 (k0 / lat1, depends on method)
//!     [48..56] f64  param3 (false_easting, meters)
//!     [56..64] f64  param4 (false_northing, meters)
//!     [64..72] f64  param5 (extra: lat2 for LCC/Albers)
//!     [72..80] f64  param6 (extra: false_northing for LCC/Albers when lat2 used)
//! ```

use crate::crs::*;
use crate::datum::{Datum, HelmertParams};
use crate::ellipsoid::Ellipsoid;

/// Embedded EPSG database binary.
static EPSG_DATA: &[u8] = include_bytes!("../data/epsg.bin");

const MAGIC: u32 = 0x45505347; // "EPSG"
const HEADER_SIZE: usize = 16;
const ELLIPSOID_RECORD_SIZE: usize = 20;
const DATUM_RECORD_SIZE: usize = 64;
const GEO_CRS_RECORD_SIZE: usize = 8;
const PROJ_CRS_RECORD_SIZE: usize = 80;

// Method IDs (must match generator)
pub(crate) const METHOD_WEB_MERCATOR: u8 = 1;
pub(crate) const METHOD_TRANSVERSE_MERCATOR: u8 = 2;
pub(crate) const METHOD_MERCATOR: u8 = 3;
pub(crate) const METHOD_LCC: u8 = 4;
pub(crate) const METHOD_ALBERS: u8 = 5;
pub(crate) const METHOD_POLAR_STEREO: u8 = 6;
pub(crate) const METHOD_EQUIDISTANT_CYL: u8 = 7;

fn read_u16(data: &[u8], offset: usize) -> u16 {
    u16::from_le_bytes([data[offset], data[offset + 1]])
}

fn read_u32(data: &[u8], offset: usize) -> u32 {
    u32::from_le_bytes([
        data[offset],
        data[offset + 1],
        data[offset + 2],
        data[offset + 3],
    ])
}

fn read_f64(data: &[u8], offset: usize) -> f64 {
    f64::from_le_bytes([
        data[offset],
        data[offset + 1],
        data[offset + 2],
        data[offset + 3],
        data[offset + 4],
        data[offset + 5],
        data[offset + 6],
        data[offset + 7],
    ])
}

struct DbLayout {
    num_ellipsoids: usize,
    num_datums: usize,
    num_geo_crs: usize,
    num_proj_crs: usize,
    ellipsoid_offset: usize,
    datum_offset: usize,
    geo_crs_offset: usize,
    proj_crs_offset: usize,
}

fn layout() -> DbLayout {
    let data = EPSG_DATA;
    assert!(data.len() >= HEADER_SIZE, "EPSG database too small");
    assert_eq!(read_u32(data, 0), MAGIC, "invalid EPSG database magic");
    assert_eq!(read_u16(data, 4), 2, "unsupported EPSG database version");

    let num_ellipsoids = read_u16(data, 6) as usize;
    let num_datums = read_u16(data, 8) as usize;
    let num_geo_crs = read_u16(data, 10) as usize;
    let num_proj_crs = read_u32(data, 12) as usize;

    let ellipsoid_offset = HEADER_SIZE;
    let datum_offset = ellipsoid_offset + num_ellipsoids * ELLIPSOID_RECORD_SIZE;
    let geo_crs_offset = datum_offset + num_datums * DATUM_RECORD_SIZE;
    let proj_crs_offset = geo_crs_offset + num_geo_crs * GEO_CRS_RECORD_SIZE;

    DbLayout {
        num_ellipsoids,
        num_datums,
        num_geo_crs,
        num_proj_crs,
        ellipsoid_offset,
        datum_offset,
        geo_crs_offset,
        proj_crs_offset,
    }
}

/// Binary search a sorted table of fixed-size records by the u32 EPSG code at offset 0.
fn binary_search_table(
    data: &[u8],
    table_offset: usize,
    record_size: usize,
    count: usize,
    target: u32,
) -> Option<usize> {
    let mut lo = 0usize;
    let mut hi = count;
    while lo < hi {
        let mid = lo + (hi - lo) / 2;
        let offset = table_offset + mid * record_size;
        let code = read_u32(data, offset);
        if code < target {
            lo = mid + 1;
        } else if code > target {
            hi = mid;
        } else {
            return Some(offset);
        }
    }
    None
}

fn lookup_ellipsoid(db: &DbLayout, epsg: u32) -> Option<Ellipsoid> {
    let offset = binary_search_table(
        EPSG_DATA,
        db.ellipsoid_offset,
        ELLIPSOID_RECORD_SIZE,
        db.num_ellipsoids,
        epsg,
    )?;
    let a = read_f64(EPSG_DATA, offset + 4);
    let inv_f = read_f64(EPSG_DATA, offset + 12);
    if inv_f == 0.0 {
        Some(Ellipsoid::sphere(a))
    } else {
        Some(Ellipsoid::from_a_rf(a, inv_f))
    }
}

fn lookup_datum(db: &DbLayout, epsg: u32) -> Option<Datum> {
    let offset = binary_search_table(
        EPSG_DATA,
        db.datum_offset,
        DATUM_RECORD_SIZE,
        db.num_datums,
        epsg,
    )?;
    let ellipsoid_code = read_u32(EPSG_DATA, offset + 4);
    let ellipsoid = lookup_ellipsoid(db, ellipsoid_code)?;

    let dx = read_f64(EPSG_DATA, offset + 8);
    let dy = read_f64(EPSG_DATA, offset + 16);
    let dz = read_f64(EPSG_DATA, offset + 24);
    let rx = read_f64(EPSG_DATA, offset + 32);
    let ry = read_f64(EPSG_DATA, offset + 40);
    let rz = read_f64(EPSG_DATA, offset + 48);
    let ds = read_f64(EPSG_DATA, offset + 56);

    let has_helmert =
        dx != 0.0 || dy != 0.0 || dz != 0.0 || rx != 0.0 || ry != 0.0 || rz != 0.0 || ds != 0.0;

    let to_wgs84 = if has_helmert {
        Some(HelmertParams {
            dx,
            dy,
            dz,
            rx,
            ry,
            rz,
            ds,
        })
    } else {
        None
    };

    Some(Datum {
        ellipsoid,
        to_wgs84,
    })
}

/// Look up a geographic CRS by EPSG code from the embedded database.
pub(crate) fn lookup_geographic(code: u32) -> Option<CrsDef> {
    let db = layout();
    let offset = binary_search_table(
        EPSG_DATA,
        db.geo_crs_offset,
        GEO_CRS_RECORD_SIZE,
        db.num_geo_crs,
        code,
    )?;
    let datum_code = read_u32(EPSG_DATA, offset + 4);
    let datum = lookup_datum(&db, datum_code)?;
    Some(CrsDef::Geographic(GeographicCrsDef::new(code, datum, "")))
}

/// Look up a projected CRS by EPSG code from the embedded database.
pub(crate) fn lookup_projected(code: u32) -> Option<CrsDef> {
    let db = layout();
    let offset = binary_search_table(
        EPSG_DATA,
        db.proj_crs_offset,
        PROJ_CRS_RECORD_SIZE,
        db.num_proj_crs,
        code,
    )?;
    let datum_code = read_u32(EPSG_DATA, offset + 4);
    let datum = lookup_datum(&db, datum_code)?;
    let method_id = EPSG_DATA[offset + 8];

    let linear_unit_to_meter = read_f64(EPSG_DATA, offset + 16);
    let p0 = read_f64(EPSG_DATA, offset + 24);
    let p1 = read_f64(EPSG_DATA, offset + 32);
    let p2 = read_f64(EPSG_DATA, offset + 40);
    let p3 = read_f64(EPSG_DATA, offset + 48);
    let p4 = read_f64(EPSG_DATA, offset + 56);
    let p5 = read_f64(EPSG_DATA, offset + 64);
    let p6 = read_f64(EPSG_DATA, offset + 72);

    let method = match method_id {
        METHOD_WEB_MERCATOR => ProjectionMethod::WebMercator,
        METHOD_TRANSVERSE_MERCATOR => ProjectionMethod::TransverseMercator {
            lon0: p0,
            lat0: p1,
            k0: p2,
            false_easting: p3,
            false_northing: p4,
        },
        METHOD_MERCATOR => ProjectionMethod::Mercator {
            lon0: p0,
            lat_ts: p1,
            k0: p2,
            false_easting: p3,
            false_northing: p4,
        },
        METHOD_LCC => ProjectionMethod::LambertConformalConic {
            lon0: p0,
            lat0: p1,
            lat1: p2,
            lat2: p5,
            false_easting: p3,
            false_northing: p6,
        },
        METHOD_ALBERS => ProjectionMethod::AlbersEqualArea {
            lon0: p0,
            lat0: p1,
            lat1: p2,
            lat2: p5,
            false_easting: p3,
            false_northing: p6,
        },
        METHOD_POLAR_STEREO => ProjectionMethod::PolarStereographic {
            lon0: p0,
            lat_ts: p1,
            k0: p2,
            false_easting: p3,
            false_northing: p4,
        },
        METHOD_EQUIDISTANT_CYL => ProjectionMethod::EquidistantCylindrical {
            lon0: p0,
            lat_ts: p1,
            false_easting: p3,
            false_northing: p4,
        },
        _ => return None,
    };

    let linear_unit = LinearUnit::from_meters_per_unit(linear_unit_to_meter).ok()?;
    Some(CrsDef::Projected(ProjectedCrsDef::new(
        code,
        datum,
        method,
        linear_unit,
        "",
    )))
}

/// Look up any EPSG code (geographic or projected).
pub(crate) fn lookup(code: u32) -> Option<CrsDef> {
    lookup_geographic(code).or_else(|| lookup_projected(code))
}

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

    #[test]
    fn db_header_valid() {
        let db = layout();
        assert!(db.num_ellipsoids > 30, "ellipsoids: {}", db.num_ellipsoids);
        assert!(db.num_datums > 100, "datums: {}", db.num_datums);
        assert!(db.num_geo_crs > 400, "geo CRS: {}", db.num_geo_crs);
        assert!(db.num_proj_crs > 4000, "proj CRS: {}", db.num_proj_crs);
    }

    #[test]
    fn lookup_wgs84() {
        let crs = lookup(4326).expect("4326");
        assert!(crs.is_geographic());
    }

    #[test]
    fn lookup_web_mercator() {
        let crs = lookup(3857).expect("3857");
        assert!(crs.is_projected());
    }

    #[test]
    fn lookup_utm_18n() {
        let crs = lookup(32618).expect("32618");
        assert!(crs.is_projected());
        if let CrsDef::Projected(p) = crs {
            if let ProjectionMethod::TransverseMercator { lon0, k0, .. } = p.method() {
                assert!((lon0 - (-75.0)).abs() < 0.01, "lon0 = {lon0}");
                assert!((k0 - 0.9996).abs() < 0.0001, "k0 = {k0}");
            } else {
                panic!("expected TM");
            }
        }
    }

    #[test]
    fn lookup_nz_tm() {
        // EPSG:2193 — New Zealand Transverse Mercator
        let crs = lookup(2193).expect("2193");
        assert!(crs.is_projected());
    }

    #[test]
    fn lookup_nc_state_plane() {
        // EPSG:32119 — NAD83 / North Carolina
        let crs = lookup(32119).expect("32119");
        assert!(crs.is_projected());
    }

    #[test]
    fn lookup_nc_state_plane_feet_unit() {
        // EPSG:2264 — NAD83 / North Carolina (ftUS)
        let crs = lookup(2264).expect("2264");
        let CrsDef::Projected(projected) = crs else {
            panic!("expected projected CRS");
        };

        assert!(
            (projected.linear_unit_to_meter() - 0.3048006096012192).abs() < 1e-15,
            "linear unit = {}",
            projected.linear_unit_to_meter()
        );
    }

    #[test]
    fn lookup_unknown() {
        assert!(lookup(99999).is_none());
    }
}