Skip to main content

openbim_ifc_binding_core/
georef.rs

1//! Georeferencing (feature `georef`, #123).
2//!
3//! The facade's `georeferencing` resolves every coordinate operation of a
4//! model (`IfcMapConversion`, and in IFC4X3 `IfcMapConversionScaled` and a
5//! length `IfcRigidOperation`) with the project length unit, as
6//! `ifc-georef` resolves them: the target projected CRS, the authored
7//! eastings, northings and height, the axis direction and scale, and the
8//! resolved operation from project metres to map metres. These are
9//! resolved parameters, not IFC values, so they cross as host numbers.
10//!
11//! IFC4 and IFC4X3 declare georeferencing as entities. IFC2X3 states it in
12//! the `ePSet_MapConversion` and `ePSet_ProjectedCRS` property sets of the
13//! buildingSMART geo-referencing guide (#451): each pair, on the
14//! `IfcProject` or else on each `IfcSite`, crosses as one `map-conversion`
15//! whose `source_kind` is `property-set`, `source` the host object,
16//! `operation` the `ePSet_MapConversion` set and `target_crs.id` the
17//! `ePSet_ProjectedCRS` set. Any other release is refused with
18//! `unsupported-schema`. A model without a coordinate operation has an
19//! empty list.
20
21use crate::record::{Field, Record, ToRecord};
22use crate::{BindingError, IfcModel};
23
24/// One coordinate operation, resolved.
25#[derive(Debug, Clone, PartialEq)]
26pub struct MapConversion {
27    /// The coordinate-operation entity; for IFC2X3, the
28    /// `ePSet_MapConversion` property set.
29    pub operation: u64,
30    /// `map-conversion`, `map-conversion-scaled` or `rigid-operation`.
31    pub kind: String,
32    /// `SourceCRS`: a representation context or a CRS; for IFC2X3, the
33    /// `IfcProject` or `IfcSite` carrying the property sets.
34    pub source: u64,
35    /// `context`, `crs` or (IFC2X3) `property-set`.
36    pub source_kind: String,
37    /// The target `IfcProjectedCRS`.
38    pub target_crs: ProjectedCrs,
39    /// `Eastings` as authored, in `map_unit`.
40    pub eastings: f64,
41    /// `Northings` as authored, in `map_unit`.
42    pub northings: f64,
43    /// `OrthogonalHeight` as authored, in `map_unit` (a rigid operation's
44    /// `Height`, or 0 when it states none).
45    pub orthogonal_height: f64,
46    /// `(XAxisAbscissa, XAxisOrdinate)`, normalised.
47    pub x_axis: (f64, f64),
48    /// `Scale` as declared (1 when unset or for a rigid operation).
49    pub scale: f64,
50    /// IFC4X3 `IfcMapConversionScaled` `(FactorX, FactorY, FactorZ)`.
51    pub factors: Option<(f64, f64, f64)>,
52    /// The project length unit the operation was resolved with.
53    pub project_unit: LengthUnit,
54    /// The map unit: the CRS's `MapUnit`, or the project unit when unset.
55    pub map_unit: LengthUnit,
56    /// Whether the CRS states `MapUnit` itself.
57    pub map_unit_declared: bool,
58    /// The operation from project metres to map metres as three columns,
59    /// the images of the project's X, Y and Z axes.
60    pub linear: [[f64; 3]; 3],
61    /// Where the project origin lands, in map metres.
62    pub translation: [f64; 3],
63}
64
65/// An `IfcProjectedCRS`.
66#[derive(Debug, Clone, PartialEq)]
67pub struct ProjectedCrs {
68    /// Its entity id.
69    pub id: u64,
70    /// `Name`, e.g. `EPSG:25832`.
71    pub name: Option<String>,
72    /// `Description`.
73    pub description: Option<String>,
74    /// `GeodeticDatum`.
75    pub geodetic_datum: Option<String>,
76    /// `VerticalDatum`.
77    pub vertical_datum: Option<String>,
78    /// `MapProjection`.
79    pub map_projection: Option<String>,
80    /// `MapZone`.
81    pub map_zone: Option<String>,
82    /// IFC4X3 `WellKnownText`, when it defines the CRS.
83    pub well_known_text: Option<String>,
84}
85
86/// A length unit reduced to metres.
87#[derive(Debug, Clone, PartialEq)]
88pub struct LengthUnit {
89    /// The unit's name as resolved, e.g. `METRE`, `MILLIMETRE`.
90    pub name: String,
91    /// Metres per one of this unit.
92    pub metres_per_unit: f64,
93}
94
95impl IfcModel {
96    /// Every coordinate operation, resolved, in file order.
97    ///
98    /// Refused with `unsupported-schema` for a release other than IFC2X3,
99    /// IFC4 or IFC4X3, `unsupported` for an operation with no project-to-map
100    /// form, `invalid-model` for a malformed operation, an incomplete,
101    /// ambiguous or malformed IFC2X3 property set, or a malformed project
102    /// length unit,
103    /// `missing-reference` for a dangling one, and `feature-disabled`
104    /// without the `georef` feature.
105    pub fn georeferencing(&self) -> Result<Vec<MapConversion>, BindingError> {
106        #[cfg(feature = "georef")]
107        {
108            read::georeferencing(self)
109        }
110        #[cfg(not(feature = "georef"))]
111        {
112            Err(BindingError::FeatureDisabled("georef"))
113        }
114    }
115}
116
117#[cfg(feature = "georef")]
118mod read {
119    use ifc::georef::{GeorefError, OperationKind, OperationSource};
120    use ifc::GeoreferencingError;
121
122    use super::{LengthUnit, MapConversion, ProjectedCrs};
123    use crate::{BindingError, IfcModel};
124
125    pub(super) fn georeferencing(model: &IfcModel) -> Result<Vec<MapConversion>, BindingError> {
126        let operations = ifc::georeferencing(&model.inner).map_err(error)?;
127        Ok(operations
128            .into_iter()
129            .map(|map| {
130                let (kind, factors) = match map.kind {
131                    OperationKind::MapConversion => ("map-conversion", None),
132                    OperationKind::MapConversionScaled { factors } => {
133                        ("map-conversion-scaled", Some(factors))
134                    }
135                    OperationKind::RigidOperation { .. } => ("rigid-operation", None),
136                    _ => ("other", None),
137                };
138                let (source, source_kind) = match map.source {
139                    OperationSource::Context(id) => (id.0, "context"),
140                    OperationSource::CoordinateReferenceSystem(id) => (id.0, "crs"),
141                    OperationSource::PropertySet(id) => (id.0, "property-set"),
142                    _ => (map.source_crs.0, "other"),
143                };
144                let unit = |unit: &ifc::georef::LengthUnit| LengthUnit {
145                    name: unit.name.clone(),
146                    metres_per_unit: unit.metres_per_unit,
147                };
148                let crs = &map.target_crs;
149                MapConversion {
150                    operation: map.operation.0,
151                    kind: kind.to_owned(),
152                    source,
153                    source_kind: source_kind.to_owned(),
154                    target_crs: ProjectedCrs {
155                        id: crs.entity.0,
156                        name: crs.name.clone(),
157                        description: crs.description.clone(),
158                        geodetic_datum: crs.geodetic_datum.clone(),
159                        vertical_datum: crs.vertical_datum.clone(),
160                        map_projection: crs.map_projection.clone(),
161                        map_zone: crs.map_zone.clone(),
162                        well_known_text: crs.well_known_text.clone(),
163                    },
164                    eastings: map.eastings,
165                    northings: map.northings,
166                    orthogonal_height: map.orthogonal_height,
167                    x_axis: map.x_axis_direction,
168                    scale: map.declared_scale,
169                    factors,
170                    project_unit: unit(&map.project_unit),
171                    map_unit: unit(&map.map_unit),
172                    map_unit_declared: map.declared_map_unit().is_some(),
173                    linear: map.linear_part(),
174                    translation: map.translation(),
175                }
176            })
177            .collect())
178    }
179
180    fn error(error: GeoreferencingError) -> BindingError {
181        let detail = error.to_string();
182        match error {
183            GeoreferencingError::Georef(error) => match error {
184                GeorefError::UnsupportedSchema { token } => BindingError::UnsupportedSchema(token),
185                GeorefError::MissingSchema => BindingError::UnsupportedSchema(String::new()),
186                GeorefError::AmbiguousSchema { .. } => BindingError::UnsupportedSchema(detail),
187                GeorefError::MissingEntity { .. } => BindingError::MissingReference(detail),
188                GeorefError::UnsupportedOperation { .. }
189                | GeorefError::CoordinateMeasureMismatch { .. } => {
190                    BindingError::Unsupported(detail)
191                }
192                GeorefError::UnitCycle { .. } => BindingError::BudgetExceeded(detail),
193                _ => BindingError::InvalidModel(detail),
194            },
195            GeoreferencingError::ProjectLengthUnit(error) => {
196                crate::properties::read::unit_error(error)
197            }
198            GeoreferencingError::OffsetLengthUnit { .. } => BindingError::Unsupported(detail),
199            _ => BindingError::InvalidModel(detail),
200        }
201    }
202}
203
204impl ToRecord for MapConversion {
205    fn to_record(&self) -> Record {
206        let triple =
207            |[x, y, z]: [f64; 3]| Field::List(vec![Field::Real(x), Field::Real(y), Field::Real(z)]);
208        Record::new(
209            "MapConversion",
210            vec![
211                ("operation", Field::Id(self.operation)),
212                ("kind", Field::Text(self.kind.clone())),
213                ("source", Field::Id(self.source)),
214                ("source_kind", Field::Text(self.source_kind.clone())),
215                ("target_crs", Field::Record(self.target_crs.to_record())),
216                ("eastings", Field::Real(self.eastings)),
217                ("northings", Field::Real(self.northings)),
218                ("orthogonal_height", Field::Real(self.orthogonal_height)),
219                (
220                    "x_axis",
221                    Field::List(vec![Field::Real(self.x_axis.0), Field::Real(self.x_axis.1)]),
222                ),
223                ("scale", Field::Real(self.scale)),
224                (
225                    "factors",
226                    Field::optional(self.factors, |(x, y, z)| triple([x, y, z])),
227                ),
228                ("project_unit", Field::Record(self.project_unit.to_record())),
229                ("map_unit", Field::Record(self.map_unit.to_record())),
230                ("map_unit_declared", Field::Bool(self.map_unit_declared)),
231                (
232                    "linear",
233                    Field::List(self.linear.iter().map(|column| triple(*column)).collect()),
234                ),
235                ("translation", triple(self.translation)),
236            ],
237        )
238    }
239}
240
241impl ToRecord for ProjectedCrs {
242    fn to_record(&self) -> Record {
243        Record::new(
244            "ProjectedCrs",
245            vec![
246                ("id", Field::Id(self.id)),
247                ("name", Field::text(self.name.clone())),
248                ("description", Field::text(self.description.clone())),
249                ("geodetic_datum", Field::text(self.geodetic_datum.clone())),
250                ("vertical_datum", Field::text(self.vertical_datum.clone())),
251                ("map_projection", Field::text(self.map_projection.clone())),
252                ("map_zone", Field::text(self.map_zone.clone())),
253                ("well_known_text", Field::text(self.well_known_text.clone())),
254            ],
255        )
256    }
257}
258
259impl ToRecord for LengthUnit {
260    fn to_record(&self) -> Record {
261        Record::new(
262            "LengthUnit",
263            vec![
264                ("name", Field::Text(self.name.clone())),
265                ("metres_per_unit", Field::Real(self.metres_per_unit)),
266            ],
267        )
268    }
269}