n3gb-rs 0.2.2

A Rust implementation of a hierarchical hex-based spatial indexing system based on the OSGB National Grid.
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
use crate::coord::ConversionMethod;
use crate::error::N3gbError;
use geo_types::{Coord, LineString, MultiPolygon, Point, Polygon};
use proj::Proj;
use rayon::prelude::*;
use std::cell::RefCell;

/// Select conversion backend at runtime based on [`ConversionMethod`].
///
/// # Arguments
/// * `coord` - The WGS84 (longitude, latitude) coordinate to convert.
/// * `method` - Which conversion backend to use.
///
/// # Returns
/// The coordinate reprojected to British National Grid as a [`Point<f64>`].
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the underlying PROJ or OSTN15
/// conversion fails.
pub(crate) fn convert_to_bng<C: super::Coordinate>(
    coord: &C,
    method: ConversionMethod,
) -> Result<Point<f64>, N3gbError> {
    match method {
        ConversionMethod::Proj => wgs84_to_bng(coord),
        ConversionMethod::Ostn15 => {
            #[cfg(feature = "ostn15")]
            {
                wgs84_to_bng_ostn15(coord)
            }
            #[cfg(not(feature = "ostn15"))]
            {
                Err(ostn15_disabled())
            }
        }
    }
}

/// Reproject a [`LineString`] from WGS84 to British National Grid.
///
/// # Arguments
/// * `line` - The WGS84 (longitude, latitude) line to convert.
/// * `method` - Which conversion backend to use.
///
/// # Returns
/// The line reprojected to British National Grid.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the underlying PROJ or OSTN15
/// conversion fails for any vertex.
pub(crate) fn convert_line_to_bng(
    line: &LineString,
    method: ConversionMethod,
) -> Result<LineString, N3gbError> {
    match method {
        ConversionMethod::Proj => wgs84_line_to_bng(line),
        ConversionMethod::Ostn15 => {
            #[cfg(feature = "ostn15")]
            {
                wgs84_line_to_bng_ostn15(line)
            }
            #[cfg(not(feature = "ostn15"))]
            {
                Err(ostn15_disabled())
            }
        }
    }
}

/// Reproject a [`Polygon`] from WGS84 to British National Grid.
///
/// # Arguments
/// * `polygon` - The WGS84 (longitude, latitude) polygon to convert.
/// * `method` - Which conversion backend to use.
///
/// # Returns
/// The polygon reprojected to British National Grid.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the underlying PROJ or OSTN15
/// conversion fails for any vertex.
pub(crate) fn convert_polygon_to_bng(
    polygon: &Polygon<f64>,
    method: ConversionMethod,
) -> Result<Polygon<f64>, N3gbError> {
    match method {
        ConversionMethod::Proj => wgs84_polygon_to_bng(polygon),
        ConversionMethod::Ostn15 => {
            #[cfg(feature = "ostn15")]
            {
                wgs84_polygon_to_bng_ostn15(polygon)
            }
            #[cfg(not(feature = "ostn15"))]
            {
                Err(ostn15_disabled())
            }
        }
    }
}

/// Reproject a [`MultiPolygon`] from WGS84 to British National Grid.
///
/// # Arguments
/// * `multipolygon` - The WGS84 (longitude, latitude) multipolygon to convert.
/// * `method` - Which conversion backend to use.
///
/// # Returns
/// The multipolygon reprojected to British National Grid.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the underlying PROJ or OSTN15
/// conversion fails for any vertex.
pub(crate) fn convert_multipolygon_to_bng(
    multipolygon: &MultiPolygon<f64>,
    method: ConversionMethod,
) -> Result<MultiPolygon<f64>, N3gbError> {
    match method {
        ConversionMethod::Proj => wgs84_multipolygon_to_bng(multipolygon),
        ConversionMethod::Ostn15 => {
            #[cfg(feature = "ostn15")]
            {
                wgs84_multipolygon_to_bng_ostn15(multipolygon)
            }
            #[cfg(not(feature = "ostn15"))]
            {
                Err(ostn15_disabled())
            }
        }
    }
}

// Hacky work around for now!
thread_local! {
    static WGS84_TO_BNG_PROJ_OBJECT: RefCell<Option<Proj>> = const { RefCell::new(None) };
}

/// Run a closure with the thread-local WGS84-to-BNG PROJ object, creating it on
/// first use.
///
/// # Arguments
/// * `proj_closure` - Closure invoked with a reference to the cached [`Proj`] object.
///
/// # Returns
/// The value returned by `proj_closure`.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the [`Proj`] object cannot be
/// constructed, or propagates any [`N3gbError`] returned by `proj_closure`.
fn with_wgs84_to_bng_proj<T, F>(proj_closure: F) -> Result<T, N3gbError>
where
    F: FnOnce(&Proj) -> Result<T, N3gbError>,
{
    WGS84_TO_BNG_PROJ_OBJECT.with(|cell| {
        let mut borrow = cell.borrow_mut();
        if borrow.is_none() {
            *borrow = Some(
                Proj::new_known_crs("EPSG:4326", "EPSG:27700", None)
                    .map_err(|e| N3gbError::ProjectionError(e.to_string()))?,
            );
        }
        proj_closure(borrow.as_ref().unwrap())
    })
}

/// Converts WGS84 (longitude, latitude) coordinates to British National Grid using PROJ.
///
/// Requires the `libproj` system library. When the OSTN15 grid file
/// (`uk_os_OSTN15_NTv2_OSGBtoETRS.tif`) is installed, accuracy is ~1mm.
/// Without grid files, PROJ silently falls back to a Helmert transform (~5m accuracy).
///
/// If you need guaranteed OSTN15 accuracy without system dependencies, use
/// [`wgs84_to_bng_ostn15`] instead.
///
/// To verify which pipeline PROJ is using at runtime, set `PROJ_DEBUG=2`:
/// ```text
/// PROJ_DEBUG=2 cargo run
/// ```
/// Look for `uk_os_OSTN15_NTv2_OSGBtoETRS.tif - succeeded` (grid active)
/// or `OSGB 1936 to WGS 84 (6)` (Helmert fallback).
///
/// # Arguments
/// * `coord` - The WGS84 (longitude, latitude) coordinate to convert.
///
/// # Returns
/// The coordinate reprojected to British National Grid as a [`Point<f64>`].
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the PROJ object cannot be built or
/// the conversion fails.
pub(crate) fn wgs84_to_bng<C: super::Coordinate>(coord: &C) -> Result<Point<f64>, N3gbError> {
    with_wgs84_to_bng_proj(|proj| {
        let (easting, northing) = proj
            .convert((coord.x(), coord.y()))
            .map_err(|e| N3gbError::ProjectionError(e.to_string()))?;
        Ok(Point::new(easting, northing))
    })
}

/// Reproject a [`LineString`] from WGS84 to British National Grid using PROJ.
///
/// # Arguments
/// * `line` - The WGS84 (longitude, latitude) line to convert.
///
/// # Returns
/// The line reprojected to British National Grid.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the PROJ object cannot be built or
/// the conversion fails for any vertex.
pub(crate) fn wgs84_line_to_bng(line: &LineString) -> Result<LineString, N3gbError> {
    let coords: Result<Vec<Coord>, N3gbError> = line
        .0
        .par_iter()
        .map(|c| {
            with_wgs84_to_bng_proj(|proj| {
                let (e, n) = proj
                    .convert((c.x, c.y))
                    .map_err(|e| N3gbError::ProjectionError(e.to_string()))?;
                Ok(Coord { x: e, y: n })
            })
        })
        .collect();
    Ok(LineString::new(coords?))
}

/// Reproject a [`Polygon`] from WGS84 to British National Grid using PROJ.
///
/// # Arguments
/// * `polygon` - The WGS84 (longitude, latitude) polygon to convert.
///
/// # Returns
/// The polygon reprojected to British National Grid.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the PROJ object cannot be built or
/// the conversion fails for any vertex.
pub(crate) fn wgs84_polygon_to_bng(polygon: &Polygon<f64>) -> Result<Polygon<f64>, N3gbError> {
    let exterior = wgs84_line_to_bng(polygon.exterior())?;
    let interiors: Result<Vec<LineString>, N3gbError> =
        polygon.interiors().iter().map(wgs84_line_to_bng).collect();
    Ok(Polygon::new(exterior, interiors?))
}

/// Reproject a [`MultiPolygon`] from WGS84 to British National Grid using PROJ.
///
/// # Arguments
/// * `multipolygon` - The WGS84 (longitude, latitude) multipolygon to convert.
///
/// # Returns
/// The multipolygon reprojected to British National Grid.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the PROJ object cannot be built or
/// the conversion fails for any vertex.
pub(crate) fn wgs84_multipolygon_to_bng(
    multipolygon: &MultiPolygon<f64>,
) -> Result<MultiPolygon<f64>, N3gbError> {
    let polygons: Result<Vec<Polygon<f64>>, N3gbError> =
        multipolygon.0.iter().map(wgs84_polygon_to_bng).collect();
    Ok(MultiPolygon::new(polygons?))
}

/// Builds the error returned when the OSTN15 backend is requested but the
/// `ostn15` feature is disabled (e.g. in the docs.rs build).
///
/// # Returns
/// A [`N3gbError::ProjectionError`] explaining that the `ostn15` feature is off.
#[cfg(not(feature = "ostn15"))]
fn ostn15_disabled() -> N3gbError {
    N3gbError::ProjectionError(
        "OSTN15 backend unavailable: enable the `ostn15` feature (on by default) \
         or use ConversionMethod::Proj"
            .into(),
    )
}

/// Converts WGS84 (longitude, latitude) coordinates to British National Grid using OSTN15.
///
/// Uses the `lonlat_bng` crate with embedded OSTN15 grid shift data.
/// No system PROJ library required. Suitable for surveying-grade accuracy.
///
/// # Arguments
/// * `coord` - The WGS84 (longitude, latitude) coordinate to convert.
///
/// # Returns
/// The coordinate reprojected to British National Grid as a [`Point<f64>`].
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the OSTN15 conversion fails.
#[cfg(feature = "ostn15")]
pub(crate) fn wgs84_to_bng_ostn15<C: super::Coordinate>(
    coord: &C,
) -> Result<Point<f64>, N3gbError> {
    lonlat_bng::convert_osgb36(coord.x(), coord.y())
        .map(|(e, n)| Point::new(e, n))
        .map_err(|_| N3gbError::ProjectionError("OSTN15 conversion failed".into()))
}

/// Reproject a [`LineString`] from WGS84 to British National Grid using OSTN15.
///
/// # Arguments
/// * `line` - The WGS84 (longitude, latitude) line to convert.
///
/// # Returns
/// The line reprojected to British National Grid.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the OSTN15 conversion fails for any
/// vertex.
#[cfg(feature = "ostn15")]
pub(crate) fn wgs84_line_to_bng_ostn15(line: &LineString) -> Result<LineString, N3gbError> {
    let coords: Result<Vec<Coord>, N3gbError> = line
        .0
        .par_iter()
        .map(|c| {
            lonlat_bng::convert_osgb36(c.x, c.y)
                .map(|(e, n)| Coord { x: e, y: n })
                .map_err(|_| N3gbError::ProjectionError("OSTN15 conversion failed".into()))
        })
        .collect();
    Ok(LineString::new(coords?))
}

/// Reproject a [`Polygon`] from WGS84 to British National Grid using OSTN15.
///
/// # Arguments
/// * `polygon` - The WGS84 (longitude, latitude) polygon to convert.
///
/// # Returns
/// The polygon reprojected to British National Grid.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the OSTN15 conversion fails for any
/// vertex.
#[cfg(feature = "ostn15")]
pub(crate) fn wgs84_polygon_to_bng_ostn15(
    polygon: &Polygon<f64>,
) -> Result<Polygon<f64>, N3gbError> {
    let exterior = wgs84_line_to_bng_ostn15(polygon.exterior())?;
    let interiors: Result<Vec<LineString>, N3gbError> = polygon
        .interiors()
        .iter()
        .map(wgs84_line_to_bng_ostn15)
        .collect();
    Ok(Polygon::new(exterior, interiors?))
}

/// Reproject a [`MultiPolygon`] from WGS84 to British National Grid using OSTN15.
///
/// # Arguments
/// * `multipolygon` - The WGS84 (longitude, latitude) multipolygon to convert.
///
/// # Returns
/// The multipolygon reprojected to British National Grid.
///
/// # Errors
/// Returns [`N3gbError::ProjectionError`] if the OSTN15 conversion fails for any
/// vertex.
#[cfg(feature = "ostn15")]
pub(crate) fn wgs84_multipolygon_to_bng_ostn15(
    multipolygon: &MultiPolygon<f64>,
) -> Result<MultiPolygon<f64>, N3gbError> {
    let polygons: Result<Vec<Polygon<f64>>, N3gbError> = multipolygon
        .0
        .iter()
        .map(wgs84_polygon_to_bng_ostn15)
        .collect();
    Ok(MultiPolygon::new(polygons?))
}

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

    #[test]
    fn test_wgs84_to_bng() -> Result<(), N3gbError> {
        let bng = wgs84_to_bng(&(-2.2479699500757597, 53.48082746395233))?;

        assert!(bng.x() > 380000.0 && bng.x() < 390000.0);
        assert!(bng.y() > 390000.0 && bng.y() < 400000.0);
        Ok(())
    }

    #[test]
    fn test_same_result_tuple_and_point() -> Result<(), N3gbError> {
        let lon = -2.2479699500757597;
        let lat = 53.48082746395233;

        let from_tuple = wgs84_to_bng(&(lon, lat))?;
        let from_point = wgs84_to_bng(&Point::new(lon, lat))?;

        assert_eq!(from_tuple.x(), from_point.x());
        assert_eq!(from_tuple.y(), from_point.y());
        Ok(())
    }

    #[test]
    fn test_generic_function_accepts_both_types() -> Result<(), N3gbError> {
        fn convert_and_sum<C: Coordinate>(coord: &C) -> Result<f64, N3gbError> {
            let bng = wgs84_to_bng(coord)?;
            Ok(bng.x() + bng.y())
        }

        let tuple_result = convert_and_sum(&(-2.248, 53.481))?;
        let point_result = convert_and_sum(&Point::new(-2.248, 53.481))?;

        assert_eq!(tuple_result, point_result);
        Ok(())
    }

    #[test]
    #[cfg(feature = "ostn15")]
    fn test_wgs84_to_bng_ostn15() -> Result<(), N3gbError> {
        let bng = wgs84_to_bng_ostn15(&(-2.2479699500757597, 53.48082746395233))?;

        assert!(bng.x() > 380000.0 && bng.x() < 390000.0);
        assert!(bng.y() > 390000.0 && bng.y() < 400000.0);
        Ok(())
    }

    #[test]
    #[cfg(feature = "ostn15")]
    fn test_ostn15_same_result_tuple_and_point() -> Result<(), N3gbError> {
        let lon = -2.2479699500757597;
        let lat = 53.48082746395233;

        let from_tuple = wgs84_to_bng_ostn15(&(lon, lat))?;
        let from_point = wgs84_to_bng_ostn15(&Point::new(lon, lat))?;

        assert_eq!(from_tuple.x(), from_point.x());
        assert_eq!(from_tuple.y(), from_point.y());
        Ok(())
    }

    #[test]
    #[cfg(feature = "ostn15")]
    fn test_proj_and_ostn15_close_agreement() -> Result<(), N3gbError> {
        let coord = (-2.2479699500757597, 53.48082746395233);
        let proj_result = wgs84_to_bng(&coord)?;
        let ostn15_result = wgs84_to_bng_ostn15(&coord)?;

        // Both paths should agree within 10 metres
        // (PROJ falls back to a Helmert transform in CI where grid files are absent)
        assert!((proj_result.x() - ostn15_result.x()).abs() < 10.0);
        assert!((proj_result.y() - ostn15_result.y()).abs() < 10.0);
        Ok(())
    }

    #[test]
    #[cfg(feature = "ostn15")]
    fn test_wgs84_line_to_bng_ostn15() -> Result<(), N3gbError> {
        use geo_types::LineString;
        let line: LineString = vec![(-2.248, 53.481), (-1.5, 53.8)].into();
        let bng_line = wgs84_line_to_bng_ostn15(&line)?;

        assert_eq!(bng_line.0.len(), 2);
        assert!(bng_line.0[0].x > 300000.0);
        assert!(bng_line.0[0].y > 300000.0);
        Ok(())
    }

    #[test]
    #[cfg(feature = "ostn15")]
    fn test_wgs84_polygon_to_bng_ostn15() -> Result<(), N3gbError> {
        use geo_types::{LineString, Polygon};
        let exterior: LineString = vec![
            (-2.248, 53.481),
            (-2.240, 53.481),
            (-2.240, 53.488),
            (-2.248, 53.488),
            (-2.248, 53.481),
        ]
        .into();
        let polygon = Polygon::new(exterior, vec![]);
        let bng_polygon = wgs84_polygon_to_bng_ostn15(&polygon)?;

        assert_eq!(bng_polygon.exterior().0.len(), 5);
        Ok(())
    }
}