proj-core 0.8.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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
use crate::coord::{
    Bounds, Coord, Coord3D, Transformable, Transformable3D, MAX_BOUNDS_DENSIFY_POINTS,
};
use crate::crs::CrsDef;
use crate::error::{Error, Result};
use crate::grid::{GridError, GridRuntime};
use crate::operation::{
    CoordinateOperation, CoordinateOperationId, CoordinateOperationMetadata, GridCoverageMiss,
    OperationSelectionDiagnostics, OperationStepDirection, SelectionOptions, TransformOutcome,
    VerticalTransformAction, VerticalTransformDiagnostics,
};
use crate::registry;

#[cfg(feature = "geo-types")]
mod geo_adapters;
mod pipeline;
mod selection;
#[cfg(test)]
mod tests;
mod vertical;

use pipeline::{
    compile_pipeline, execute_pipeline_xy, validate_output_len, validate_pipeline_coord3d,
    validate_transform_crs_definition, validate_vertical_ordinate, CompiledOperationFallback,
    CompiledOperationPipeline, PipelineExecutionOutcome,
};
use selection::{
    compile_selected_pipelines, grid_coverage_miss_detail, is_grid_coverage_miss, selected_metadata,
};
use vertical::{compile_vertical_transform, vertical_diagnostics, VerticalTransform};

#[cfg(feature = "rayon")]
use pipeline::should_parallelize;

#[cfg(all(test, feature = "rayon"))]
use pipeline::PARALLEL_MIN_ITEMS_PER_THREAD;
#[cfg(test)]
use pipeline::{PipelineSourceXyUnits, PipelineTargetXyUnits};

/// A reusable coordinate transformation between two CRS.
pub struct Transform {
    source: CrsDef,
    target: CrsDef,
    selected_operation_definition: CoordinateOperation,
    selected_direction: OperationStepDirection,
    selected_operation: CoordinateOperationMetadata,
    diagnostics: OperationSelectionDiagnostics,
    vertical_transform: VerticalTransform,
    selection_options: SelectionOptions,
    pipeline: CompiledOperationPipeline,
    fallback_pipelines: Vec<CompiledOperationFallback>,
}

/// Trait for `geo-types` geometries that can be transformed as whole values.
///
/// Implementations transform coordinates in storage order and return the first
/// coordinate error without producing a partially transformed geometry.
#[cfg(feature = "geo-types")]
pub trait TransformableGeometry: Sized {
    fn transform_geometry(self, transform: &Transform) -> Result<Self>;
}

fn validate_wrapped_geographic_transform_bounds(bounds: Bounds) -> Result<()> {
    if !bounds.min_x.is_finite()
        || !bounds.min_y.is_finite()
        || !bounds.max_x.is_finite()
        || !bounds.max_y.is_finite()
        || bounds.min_x <= bounds.max_x
        || bounds.min_y > bounds.max_y
    {
        return Err(Error::OutOfRange(
            "wrapped geographic bounds must be finite and satisfy west > east and south <= north"
                .into(),
        ));
    }

    for point in [
        Coord::new(bounds.min_x, bounds.min_y),
        Coord::new(bounds.min_x, bounds.max_y),
        Coord::new(bounds.max_x, bounds.min_y),
        Coord::new(bounds.max_x, bounds.max_y),
    ] {
        if !(-180.0..=180.0).contains(&point.x) {
            return Err(Error::OutOfRange(format!(
                "wrapped geographic bounds longitude {:.8} degrees is outside [-180, 180]",
                point.x
            )));
        }
        if !(-90.0..=90.0).contains(&point.y) {
            return Err(Error::OutOfRange(format!(
                "wrapped geographic bounds latitude {:.8} degrees is outside [-90, 90]",
                point.y
            )));
        }
    }

    Ok(())
}

impl Transform {
    /// Create a transform from authority code strings (e.g., `"EPSG:4326"`).
    pub fn new(from_crs: &str, to_crs: &str) -> Result<Self> {
        Self::with_selection_options(from_crs, to_crs, SelectionOptions::default())
    }

    /// Create a transform with explicit selection options.
    pub fn with_selection_options(
        from_crs: &str,
        to_crs: &str,
        options: SelectionOptions,
    ) -> Result<Self> {
        let source = registry::lookup_authority_code(from_crs)?;
        let target = registry::lookup_authority_code(to_crs)?;
        Self::from_crs_defs_with_selection_options(&source, &target, options)
    }

    /// Create a transform from an explicit registry operation id.
    pub fn from_operation(
        operation_id: CoordinateOperationId,
        from_crs: &str,
        to_crs: &str,
    ) -> Result<Self> {
        Self::with_selection_options(
            from_crs,
            to_crs,
            SelectionOptions::new().with_operation(operation_id),
        )
    }

    /// Create a transform from EPSG codes directly.
    pub fn from_epsg(from: u32, to: u32) -> Result<Self> {
        let source = registry::lookup_epsg(from)
            .ok_or_else(|| Error::UnknownCrs(format!("unknown EPSG code: {from}")))?;
        let target = registry::lookup_epsg(to)
            .ok_or_else(|| Error::UnknownCrs(format!("unknown EPSG code: {to}")))?;
        Self::from_crs_defs(&source, &target)
    }

    /// Create a transform from explicit CRS definitions.
    pub fn from_crs_defs(from: &CrsDef, to: &CrsDef) -> Result<Self> {
        Self::from_crs_defs_with_selection_options(from, to, SelectionOptions::default())
    }

    /// Create a horizontal-only transform from explicit CRS definitions.
    ///
    /// Compound CRS inputs are reduced to their horizontal component before
    /// operation selection. This is intended for XY-only workflows where
    /// vertical transformation is deliberately out of scope.
    pub fn from_horizontal_components(from: &CrsDef, to: &CrsDef) -> Result<Self> {
        Self::from_horizontal_components_with_selection_options(
            from,
            to,
            SelectionOptions::default(),
        )
    }

    /// Create a horizontal-only transform from explicit CRS definitions with
    /// operation-selection options.
    pub fn from_horizontal_components_with_selection_options(
        from: &CrsDef,
        to: &CrsDef,
        options: SelectionOptions,
    ) -> Result<Self> {
        let source = from.horizontal_crs().ok_or_else(|| {
            Error::InvalidDefinition("source CRS does not contain a horizontal component".into())
        })?;
        let target = to.horizontal_crs().ok_or_else(|| {
            Error::InvalidDefinition("target CRS does not contain a horizontal component".into())
        })?;
        Self::from_crs_defs_with_selection_options(&source, &target, options)
    }

    /// Create a transform from explicit CRS definitions with operation-selection options.
    ///
    /// Use this when a custom CRS references grid resources and the transform
    /// needs an application-supplied [`crate::grid::GridProvider`].
    pub fn from_crs_defs_with_selection_options(
        from: &CrsDef,
        to: &CrsDef,
        options: SelectionOptions,
    ) -> Result<Self> {
        validate_transform_crs_definition(from)?;
        validate_transform_crs_definition(to)?;

        let grid_runtime = GridRuntime::new(options.grid_provider.clone());
        let vertical_transform = compile_vertical_transform(from, to, &options, &grid_runtime)?;
        let selected = compile_selected_pipelines(from, to, &options, &grid_runtime)?;
        Ok(Self {
            source: from.clone(),
            target: to.clone(),
            selected_operation_definition: selected.operation,
            selected_direction: selected.direction,
            selected_operation: selected.metadata,
            diagnostics: selected.diagnostics,
            vertical_transform,
            selection_options: options,
            pipeline: selected.pipeline,
            fallback_pipelines: selected.fallback_pipelines,
        })
    }

    /// Transform a single coordinate.
    pub fn convert<T: Transformable>(&self, coord: T) -> Result<T> {
        let c = coord.into_coord();
        let result = self.convert_coord(c)?;
        Ok(T::from_coord(result))
    }

    /// Transform a whole `geo-types` geometry.
    ///
    /// This method is available only with the `geo-types` feature. It
    /// transforms coordinates in geometry storage order and returns the first
    /// coordinate error without producing a partial result.
    ///
    /// `geo_types::Rect` is treated as a source bounds envelope and converted
    /// to sampled axis-aligned target bounds with 21 intermediate points per
    /// edge. This is an approximation for nonlinear projections: extrema can
    /// occur between samples. Use [`Self::convert_rect`] when the rect sampling
    /// density should be chosen by the caller.
    #[cfg(feature = "geo-types")]
    pub fn convert_geometry<T: TransformableGeometry>(&self, geometry: T) -> Result<T> {
        geometry.transform_geometry(self)
    }

    /// Transform a `geo_types::Rect` to sampled axis-aligned target bounds.
    ///
    /// This method is available only with the `geo-types` feature. A rect
    /// represents an envelope, not a true geometry, so nonlinear projections can
    /// have edge extrema between samples. Increase `densify_points` to sample
    /// edges more finely for higher-fidelity bounds, or use
    /// [`Self::transform_bounds`] directly when working with [`Bounds`].
    ///
    /// `densify_points` is the number of intermediate samples added per edge
    /// and must be no larger than [`MAX_BOUNDS_DENSIFY_POINTS`].
    #[cfg(feature = "geo-types")]
    pub fn convert_rect(
        &self,
        rect: geo_types::Rect<f64>,
        densify_points: usize,
    ) -> Result<geo_types::Rect<f64>> {
        geo_adapters::transform_geo_rect_with_densification(self, rect, densify_points)
    }

    /// Transform a single 3D coordinate.
    pub fn convert_3d<T: Transformable3D>(&self, coord: T) -> Result<T> {
        let c = coord.into_coord3d();
        let result = self.convert_coord3d(c)?;
        Ok(T::from_coord3d(result))
    }

    /// Transform a single coordinate and report the operation actually used.
    ///
    /// This 2D API is XY-only: it does not apply or sample configured vertical
    /// transforms.
    ///
    /// When the selected grid-backed operation misses grid coverage, this
    /// reports the coverage misses and the lower-ranked fallback operation that
    /// produced the result.
    pub fn convert_with_diagnostics<T: Transformable>(
        &self,
        coord: T,
    ) -> Result<TransformOutcome<T>> {
        let c = coord.into_coord();
        let outcome = self.convert_coord_with_diagnostics(c)?;
        Ok(TransformOutcome {
            coord: T::from_coord(outcome.coord),
            operation: outcome.operation,
            vertical: outcome.vertical,
            grid_coverage_misses: outcome.grid_coverage_misses,
        })
    }

    /// Transform a single 3D coordinate and report the operation actually used.
    ///
    /// When the selected grid-backed operation misses grid coverage, this
    /// reports the coverage misses and the lower-ranked fallback operation that
    /// produced the result.
    pub fn convert_3d_with_diagnostics<T: Transformable3D>(
        &self,
        coord: T,
    ) -> Result<TransformOutcome<T>> {
        let c = coord.into_coord3d();
        let outcome = self.convert_coord3d_with_diagnostics(c)?;
        Ok(TransformOutcome {
            coord: T::from_coord3d(outcome.coord),
            operation: outcome.operation,
            vertical: outcome.vertical,
            grid_coverage_misses: outcome.grid_coverage_misses,
        })
    }

    /// Return the source CRS definition for this transform.
    pub fn source_crs(&self) -> &CrsDef {
        &self.source
    }

    /// Return the target CRS definition for this transform.
    pub fn target_crs(&self) -> &CrsDef {
        &self.target
    }

    /// Return metadata for the selected coordinate operation.
    pub fn selected_operation(&self) -> &CoordinateOperationMetadata {
        &self.selected_operation
    }

    /// Return selection diagnostics for this transform.
    pub fn selection_diagnostics(&self) -> &OperationSelectionDiagnostics {
        &self.diagnostics
    }

    /// Return diagnostics for the vertical component of this transform.
    pub fn vertical_diagnostics(&self) -> &VerticalTransformDiagnostics {
        self.vertical_transform.diagnostics()
    }

    /// Build the inverse transform by swapping the source and target CRS.
    pub fn inverse(&self) -> Result<Self> {
        let grid_runtime = GridRuntime::new(self.selection_options.grid_provider.clone());
        let inverse_options = self.selection_options.inverse();
        let vertical_transform = compile_vertical_transform(
            &self.target,
            &self.source,
            &inverse_options,
            &grid_runtime,
        )?;
        let selected_direction = self.selected_direction.inverse();
        let pipeline = compile_pipeline(
            &self.target,
            &self.source,
            &self.selected_operation_definition,
            selected_direction,
            &grid_runtime,
        )?;
        let selected_operation = selected_metadata(
            &self.selected_operation_definition,
            selected_direction,
            self.selected_operation.area_of_use.clone(),
        );
        let mut fallback_pipelines = Vec::with_capacity(self.fallback_pipelines.len());
        for fallback in &self.fallback_pipelines {
            let direction = fallback.direction.inverse();
            let pipeline = compile_pipeline(
                &self.target,
                &self.source,
                &fallback.operation,
                direction,
                &grid_runtime,
            )?;
            let metadata = selected_metadata(
                &fallback.operation,
                direction,
                fallback.metadata.area_of_use.clone(),
            );
            fallback_pipelines.push(CompiledOperationFallback {
                operation: fallback.operation.clone(),
                direction,
                metadata,
                pipeline,
            });
        }
        let diagnostics = OperationSelectionDiagnostics {
            selected_operation: selected_operation.clone(),
            selected_match_kind: self.diagnostics.selected_match_kind,
            selected_reasons: self.diagnostics.selected_reasons.clone(),
            fallback_operations: fallback_pipelines
                .iter()
                .map(|fallback| fallback.metadata.clone())
                .collect(),
            skipped_operations: Vec::new(),
            approximate: self.diagnostics.approximate,
            missing_required_grid: self.diagnostics.missing_required_grid.clone(),
        };
        Ok(Self {
            source: self.target.clone(),
            target: self.source.clone(),
            selected_operation_definition: self.selected_operation_definition.clone(),
            selected_direction,
            selected_operation,
            diagnostics,
            vertical_transform,
            selection_options: inverse_options,
            pipeline,
            fallback_pipelines,
        })
    }

    /// Reproject a 2D bounding box by sampling its perimeter.
    ///
    /// `densify_points` is the number of intermediate samples added per edge
    /// and must be no larger than [`MAX_BOUNDS_DENSIFY_POINTS`].
    pub fn transform_bounds(&self, bounds: Bounds, densify_points: usize) -> Result<Bounds> {
        if !bounds.is_valid() {
            return Err(Error::OutOfRange(
                "bounds must be finite and satisfy min <= max".into(),
            ));
        }

        self.transform_valid_bounds(bounds, densify_points)
    }

    /// Reproject a geographic bounding box that crosses the antimeridian.
    ///
    /// `bounds` is interpreted as west/south/east/north in source geographic
    /// degrees and must satisfy `west > east`. Projected and normal
    /// non-wrapped bounds should use [`Self::transform_bounds`].
    ///
    /// `densify_points` is the number of intermediate samples added per edge
    /// and must be no larger than [`MAX_BOUNDS_DENSIFY_POINTS`].
    pub fn transform_geographic_wrapped_bounds(
        &self,
        bounds: Bounds,
        densify_points: usize,
    ) -> Result<Bounds> {
        if !self.source.is_geographic() {
            return Err(Error::InvalidDefinition(
                "wrapped geographic bounds require a geographic source CRS".into(),
            ));
        }
        validate_wrapped_geographic_transform_bounds(bounds)?;

        let west_segment = Bounds::new(bounds.min_x, bounds.min_y, 180.0, bounds.max_y);
        let east_segment = Bounds::new(-180.0, bounds.min_y, bounds.max_x, bounds.max_y);
        let mut transformed = self.transform_valid_bounds(west_segment, densify_points)?;
        let east_transformed = self.transform_valid_bounds(east_segment, densify_points)?;
        transformed.expand_to_include(Coord::new(east_transformed.min_x, east_transformed.min_y));
        transformed.expand_to_include(Coord::new(east_transformed.max_x, east_transformed.max_y));
        Ok(transformed)
    }

    fn transform_valid_bounds(&self, bounds: Bounds, densify_points: usize) -> Result<Bounds> {
        let segments = bounds_densify_segments(densify_points)?;

        let mut transformed: Option<Bounds> = None;
        for i in 0..=segments {
            let t = i as f64 / segments as f64;
            let x = bounds.min_x + bounds.width() * t;
            let y = bounds.min_y + bounds.height() * t;

            for sample in [
                Coord::new(x, bounds.min_y),
                Coord::new(x, bounds.max_y),
                Coord::new(bounds.min_x, y),
                Coord::new(bounds.max_x, y),
            ] {
                let coord = self.convert_coord(sample)?;
                if let Some(accum) = &mut transformed {
                    accum.expand_to_include(coord);
                } else {
                    transformed = Some(Bounds::new(coord.x, coord.y, coord.x, coord.y));
                }
            }
        }

        transformed.ok_or_else(|| Error::OutOfRange("failed to sample bounds".into()))
    }

    fn convert_coord(&self, c: Coord) -> Result<Coord> {
        match execute_pipeline_xy(&self.pipeline, Coord3D::new(c.x, c.y, 0.0)) {
            Ok(coord) => return Ok(coord),
            Err(error) => {
                if !is_grid_coverage_miss(&error) {
                    return Err(error);
                }
            }
        }

        for fallback in &self.fallback_pipelines {
            match execute_pipeline_xy(&fallback.pipeline, Coord3D::new(c.x, c.y, 0.0)) {
                Ok(coord) => return Ok(coord),
                Err(error) => {
                    if !is_grid_coverage_miss(&error) {
                        return Err(error);
                    }
                }
            }
        }

        Err(Error::Grid(GridError::OutsideCoverage(
            "grid coverage miss".into(),
        )))
    }

    fn convert_coord3d(&self, c: Coord3D) -> Result<Coord3D> {
        match self.execute_pipeline_coord3d(&self.pipeline, c) {
            Ok(coord) => return Ok(coord),
            Err(error) => {
                if !is_grid_coverage_miss(&error) {
                    return Err(error);
                }
            }
        }

        for fallback in &self.fallback_pipelines {
            match self.execute_pipeline_coord3d(&fallback.pipeline, c) {
                Ok(coord) => return Ok(coord),
                Err(error) => {
                    if !is_grid_coverage_miss(&error) {
                        return Err(error);
                    }
                }
            }
        }

        Err(Error::Grid(GridError::OutsideCoverage(
            "grid coverage miss".into(),
        )))
    }

    fn convert_coord_with_diagnostics(&self, c: Coord) -> Result<TransformOutcome<Coord>> {
        let mut grid_coverage_misses = Vec::new();
        let c = Coord3D::new(c.x, c.y, 0.0);

        match execute_pipeline_xy(&self.pipeline, c) {
            Ok(coord) => {
                return Ok(TransformOutcome {
                    coord,
                    operation: self.selected_operation.clone(),
                    vertical: vertical_diagnostics(VerticalTransformAction::None, None, None, None),
                    grid_coverage_misses,
                });
            }
            Err(error) => {
                if let Some(detail) = grid_coverage_miss_detail(&error) {
                    grid_coverage_misses.push(GridCoverageMiss {
                        operation: self.selected_operation.clone(),
                        detail,
                    });
                } else {
                    return Err(error);
                }
            }
        }

        for fallback in &self.fallback_pipelines {
            match execute_pipeline_xy(&fallback.pipeline, c) {
                Ok(coord) => {
                    return Ok(TransformOutcome {
                        coord,
                        operation: fallback.metadata.clone(),
                        vertical: vertical_diagnostics(
                            VerticalTransformAction::None,
                            None,
                            None,
                            None,
                        ),
                        grid_coverage_misses,
                    });
                }
                Err(error) => {
                    if let Some(detail) = grid_coverage_miss_detail(&error) {
                        grid_coverage_misses.push(GridCoverageMiss {
                            operation: fallback.metadata.clone(),
                            detail,
                        });
                    } else {
                        return Err(error);
                    }
                }
            }
        }

        Err(Error::Grid(GridError::OutsideCoverage(
            grid_coverage_misses
                .last()
                .map(|miss| miss.detail.clone())
                .unwrap_or_else(|| "grid coverage miss".into()),
        )))
    }

    fn convert_coord3d_with_diagnostics(&self, c: Coord3D) -> Result<TransformOutcome<Coord3D>> {
        let mut grid_coverage_misses = Vec::new();
        match self.execute_pipeline(&self.pipeline, c) {
            Ok(outcome) => {
                return Ok(TransformOutcome {
                    coord: outcome.coord,
                    operation: self.selected_operation.clone(),
                    vertical: outcome.vertical,
                    grid_coverage_misses,
                });
            }
            Err(error) => {
                if let Some(detail) = grid_coverage_miss_detail(&error) {
                    grid_coverage_misses.push(GridCoverageMiss {
                        operation: self.selected_operation.clone(),
                        detail,
                    });
                } else {
                    return Err(error);
                }
            }
        }

        for fallback in &self.fallback_pipelines {
            match self.execute_pipeline(&fallback.pipeline, c) {
                Ok(outcome) => {
                    return Ok(TransformOutcome {
                        coord: outcome.coord,
                        operation: fallback.metadata.clone(),
                        vertical: outcome.vertical,
                        grid_coverage_misses,
                    });
                }
                Err(error) => {
                    if let Some(detail) = grid_coverage_miss_detail(&error) {
                        grid_coverage_misses.push(GridCoverageMiss {
                            operation: fallback.metadata.clone(),
                            detail,
                        });
                    } else {
                        return Err(error);
                    }
                }
            }
        }

        Err(Error::Grid(GridError::OutsideCoverage(
            grid_coverage_misses
                .last()
                .map(|miss| miss.detail.clone())
                .unwrap_or_else(|| "grid coverage miss".into()),
        )))
    }

    fn execute_pipeline(
        &self,
        pipeline: &CompiledOperationPipeline,
        c: Coord3D,
    ) -> Result<PipelineExecutionOutcome> {
        validate_vertical_ordinate(c.z)?;
        let xy = execute_pipeline_xy(pipeline, c)?;
        let vertical = self.vertical_transform.apply(c)?;
        let coord = Coord3D::new(xy.x, xy.y, vertical.z);
        validate_pipeline_coord3d("pipeline final output", coord)?;
        Ok(PipelineExecutionOutcome {
            coord,
            vertical: vertical.diagnostics,
        })
    }

    fn execute_pipeline_coord3d(
        &self,
        pipeline: &CompiledOperationPipeline,
        c: Coord3D,
    ) -> Result<Coord3D> {
        validate_vertical_ordinate(c.z)?;
        let xy = execute_pipeline_xy(pipeline, c)?;
        let z = self.vertical_transform.apply_z(c)?;
        let coord = Coord3D::new(xy.x, xy.y, z);
        validate_pipeline_coord3d("pipeline final output", coord)?;
        Ok(coord)
    }

    /// Batch transform (sequential).
    pub fn convert_batch<T: Transformable + Clone>(&self, coords: &[T]) -> Result<Vec<T>> {
        coords.iter().map(|c| self.convert(c.clone())).collect()
    }

    /// Batch transform of 3D coordinates (sequential).
    pub fn convert_batch_3d<T: Transformable3D + Clone>(&self, coords: &[T]) -> Result<Vec<T>> {
        coords.iter().map(|c| self.convert_3d(c.clone())).collect()
    }

    /// Transform 2D coordinates in place without allocating.
    ///
    /// Coordinates before a failing coordinate are left converted; the failing
    /// coordinate and subsequent coordinates are left unchanged.
    pub fn convert_coords_in_place(&self, coords: &mut [Coord]) -> Result<()> {
        for coord in coords {
            *coord = self.convert_coord(*coord)?;
        }
        Ok(())
    }

    /// Transform 3D coordinates in place without allocating.
    ///
    /// Coordinates before a failing coordinate are left converted; the failing
    /// coordinate and subsequent coordinates are left unchanged.
    pub fn convert_coords_3d_in_place(&self, coords: &mut [Coord3D]) -> Result<()> {
        for coord in coords {
            *coord = self.convert_coord3d(*coord)?;
        }
        Ok(())
    }

    /// Transform 2D coordinates from `input` into an existing `output` slice.
    ///
    /// `output` must have exactly the same length as `input`. This API performs
    /// no allocation and does not require cloning input coordinates.
    pub fn convert_coords_into(&self, input: &[Coord], output: &mut [Coord]) -> Result<()> {
        validate_output_len(input.len(), output.len())?;
        for (source, target) in input.iter().zip(output.iter_mut()) {
            *target = self.convert_coord(*source)?;
        }
        Ok(())
    }

    /// Transform 3D coordinates from `input` into an existing `output` slice.
    ///
    /// `output` must have exactly the same length as `input`. This API performs
    /// no allocation and does not require cloning input coordinates.
    pub fn convert_coords_3d_into(&self, input: &[Coord3D], output: &mut [Coord3D]) -> Result<()> {
        validate_output_len(input.len(), output.len())?;
        for (source, target) in input.iter().zip(output.iter_mut()) {
            *target = self.convert_coord3d(*source)?;
        }
        Ok(())
    }

    /// Batch transform with Rayon parallelism.
    #[cfg(feature = "rayon")]
    pub fn convert_batch_parallel<T: Transformable + Send + Sync + Clone>(
        &self,
        coords: &[T],
    ) -> Result<Vec<T>> {
        if !should_parallelize(coords.len()) {
            return self.convert_batch(coords);
        }

        use rayon::prelude::*;

        coords
            .par_iter()
            .map(|coord| self.convert(coord.clone()))
            .collect()
    }

    /// Batch transform of 3D coordinates with adaptive Rayon parallelism.
    #[cfg(feature = "rayon")]
    pub fn convert_batch_parallel_3d<T: Transformable3D + Send + Sync + Clone>(
        &self,
        coords: &[T],
    ) -> Result<Vec<T>> {
        if !should_parallelize(coords.len()) {
            return self.convert_batch_3d(coords);
        }

        use rayon::prelude::*;

        coords
            .par_iter()
            .map(|coord| self.convert_3d(coord.clone()))
            .collect()
    }
}

pub(crate) fn bounds_densify_segments(densify_points: usize) -> Result<usize> {
    if densify_points > MAX_BOUNDS_DENSIFY_POINTS {
        return Err(Error::OutOfRange(format!(
            "densify point count {densify_points} exceeds maximum {MAX_BOUNDS_DENSIFY_POINTS}"
        )));
    }
    densify_points
        .checked_add(1)
        .ok_or_else(|| Error::OutOfRange("densify point count is too large".into()))
}