ifc_georef/conversion/operation.rs
1//! The resolved project-to-map value and the entry points that dispatch
2//! every `IfcCoordinateOperation` subtype.
3//!
4//! | Subtype | Release | Lowered by |
5//! | --- | --- | --- |
6//! | `IfcMapConversion` | IFC4, IFC4X3 | `map.rs` |
7//! | `IfcMapConversionScaled` | IFC4X3 | `map.rs`, per-axis factors |
8//! | `IfcRigidOperation`, length coordinates | IFC4X3 | `rigid.rs`, a translation |
9//! | `IfcRigidOperation`, plane-angle coordinates | IFC4X3 | refused here; [`crate::resolve_geographic_offset_in`] |
10//!
11//! A plane-angle rigid operation offsets latitude and longitude on an
12//! `IfcGeographicCRS`. No metre-to-metre affine transform expresses that,
13//! so it is refused with [`GeorefError::CoordinateMeasureMismatch`] rather
14//! than approximated.
15//!
16//! # Kernel-free parameters
17//!
18//! [`ProjectToMap`] carries the resolved operation as plain `f64` (its
19//! authored eastings, northings and height, and the metre-to-metre linear
20//! part and translation behind [`ProjectToMap::map_point`]). The
21//! `axiolid_core::Transform3` view of the same operation exists only with
22//! the default `transform` feature, so a semantic consumer can read every
23//! parameter without linking a geometry kernel (#268).
24
25#[cfg(feature = "transform")]
26use axiolid_core::Transform3;
27use ifc_model::value::Value;
28use ifc_model::{Entity, EntityId, Model};
29
30use crate::context::{operation_source, OperationSource};
31use crate::crs::Damage;
32use crate::crs::{LengthUnit, ProjectedCrs};
33use crate::error::{GeorefError, GeorefResult};
34use crate::view::GeorefView;
35
36use super::{map, rigid};
37
38/// Which coordinate-operation subtype a [`ProjectToMap`] was lowered from.
39#[derive(Debug, Clone, Copy, PartialEq)]
40#[non_exhaustive]
41pub enum OperationKind {
42 /// `IfcMapConversion`.
43 MapConversion,
44 /// IFC4X3 `IfcMapConversionScaled`, with its `(FactorX, FactorY,
45 /// FactorZ)` as authored. They are folded into `transform`.
46 MapConversionScaled {
47 /// `(FactorX, FactorY, FactorZ)`.
48 factors: (f64, f64, f64),
49 },
50 /// IFC4X3 `IfcRigidOperation` with `IfcLengthMeasure` coordinates.
51 RigidOperation {
52 /// `Height` in map units as authored. `None` when the file states
53 /// no height: the transform then shifts heights by nothing, and
54 /// this records that no vertical offset was declared.
55 height: Option<f64>,
56 },
57}
58
59/// A resolved project-to-map coordinate operation, normalised to metres.
60#[derive(Debug, Clone, PartialEq)]
61#[non_exhaustive]
62pub struct ProjectToMap {
63 /// The operation's `SourceCRS`, an
64 /// `IfcCoordinateReferenceSystemSelect`: an
65 /// `IfcGeometricRepresentationContext` or an
66 /// `IfcCoordinateReferenceSystem`, in IFC4 and IFC4X3 alike. `source`
67 /// says which. For IFC2X3 property-set georeferencing, the
68 /// `IfcProject` or `IfcSite` carrying the sets
69 /// ([`OperationSource::PropertySet`]).
70 pub source_crs: EntityId,
71 /// The validated source, typed.
72 pub source: OperationSource,
73 /// The coordinate-operation entity this was resolved from; for IFC2X3,
74 /// the `ePSet_MapConversion` property set.
75 pub operation: EntityId,
76 /// Which subtype `operation` is, with its subtype-only attributes.
77 pub kind: OperationKind,
78 /// The target projected CRS; for IFC2X3, read from the
79 /// `ePSet_ProjectedCRS` property set, whose id is its `entity`.
80 pub target_crs: ProjectedCrs,
81 /// Affine operation from neutral project metres to neutral map metres.
82 ///
83 /// Only with the default `transform` feature. The same operation is
84 /// always available as plain numbers through [`Self::map_point`],
85 /// [`Self::linear_part`] and [`Self::translation`].
86 #[cfg(feature = "transform")]
87 pub transform: Transform3,
88 /// `Eastings` as authored, in `map_unit`. For a rigid operation,
89 /// `FirstCoordinate`, the offset along the target CRS's first axis.
90 pub eastings: f64,
91 /// `Northings` as authored, in `map_unit`. For a rigid operation,
92 /// `SecondCoordinate`, the offset along the target CRS's second axis.
93 pub northings: f64,
94 /// `OrthogonalHeight` as authored, in `map_unit`. For a rigid
95 /// operation, `Height`, or `0.0` when the file states none (see
96 /// [`OperationKind::RigidOperation`]).
97 pub orthogonal_height: f64,
98 /// Length unit the project authored its coordinates in.
99 pub project_unit: LengthUnit,
100 /// Length unit the map coordinates are expressed in, resolved: the
101 /// target CRS's `MapUnit` when stated, otherwise the project length
102 /// unit, which IFC prescribes for an omitted `MapUnit`. `transform`,
103 /// [`Self::map_point`] and [`Self::translation`] use this unit. Whether
104 /// the file stated it is [`Self::declared_map_unit`].
105 pub map_unit: LengthUnit,
106 /// IFC's declared scale before source/target unit normalization. `1.0`
107 /// for a rigid operation, which has none.
108 pub declared_scale: f64,
109 /// Normalized `(XAxisAbscissa, XAxisOrdinate)`: the project's local X
110 /// axis, as a unit vector, expressed in the map's XY plane. Exposed
111 /// (rather than only folded into `transform`) because grid-north
112 /// resolution needs the rotation alone, without `transform`'s scale
113 /// and translation. `(1, 0)` for a rigid operation.
114 pub x_axis_direction: (f64, f64),
115 /// Linear part, metres to metres, as three columns (the images of the
116 /// project's X, Y and Z axes).
117 linear: [[f64; 3]; 3],
118 /// Translation, map metres: the map position of the project origin.
119 translation: [f64; 3],
120}
121
122impl ProjectToMap {
123 /// Assemble the resolved value from its metre-to-metre affine parts,
124 /// deriving the `Transform3` view when the feature is on.
125 #[allow(clippy::too_many_arguments)]
126 pub(super) fn new(
127 source: OperationSource,
128 operation: EntityId,
129 kind: OperationKind,
130 target_crs: ProjectedCrs,
131 authored: [f64; 3],
132 units: (LengthUnit, LengthUnit),
133 declared_scale: f64,
134 x_axis_direction: (f64, f64),
135 linear: [[f64; 3]; 3],
136 translation: [f64; 3],
137 ) -> Self {
138 let (project_unit, map_unit) = units;
139 Self {
140 source_crs: source.entity(),
141 source,
142 operation,
143 kind,
144 target_crs,
145 #[cfg(feature = "transform")]
146 transform: transform3(&linear, &translation),
147 eastings: authored[0],
148 northings: authored[1],
149 orthogonal_height: authored[2],
150 project_unit,
151 map_unit,
152 declared_scale,
153 x_axis_direction,
154 linear,
155 translation,
156 }
157 }
158
159 /// Carry a point from project metres to map metres.
160 ///
161 /// Plain arithmetic on the resolved parameters, identical to
162 /// `transform.transform_point3` (same operation order, so the same
163 /// rounding) and available without the `transform` feature.
164 #[must_use]
165 pub fn map_point(&self, point: [f64; 3]) -> [f64; 3] {
166 let [c0, c1, c2] = self.linear;
167 let t = self.translation;
168 std::array::from_fn(|i| c0[i] * point[0] + c1[i] * point[1] + c2[i] * point[2] + t[i])
169 }
170
171 /// The linear part, metres to metres, as three columns: the images of
172 /// the project's unit X, Y and Z axes. Scale, unit conversion, per-axis
173 /// factors and rotation are folded in.
174 #[must_use]
175 pub fn linear_part(&self) -> [[f64; 3]; 3] {
176 self.linear
177 }
178
179 /// The target CRS's `MapUnit` exactly as authored: `None` when the
180 /// file leaves it unset, even though [`Self::map_unit`] then resolves
181 /// to the project length unit. With `MapUnit` stated, this and
182 /// `map_unit` are the same unit.
183 ///
184 /// The value is [`ProjectedCrs::map_unit`] of [`Self::target_crs`];
185 /// this accessor names it next to the resolved unit (#296).
186 #[must_use]
187 pub fn declared_map_unit(&self) -> Option<&LengthUnit> {
188 self.target_crs.map_unit.as_ref()
189 }
190
191 /// The translation in map metres: where the project origin lands.
192 /// `[eastings, northings, orthogonal_height]` converted from
193 /// `map_unit` to metres.
194 #[must_use]
195 pub fn translation(&self) -> [f64; 3] {
196 self.translation
197 }
198}
199
200/// The `Transform3` view of an affine operation held as plain numbers.
201#[cfg(feature = "transform")]
202fn transform3(linear: &[[f64; 3]; 3], translation: &[f64; 3]) -> Transform3 {
203 use axiolid_core::{Mat3, Vec3};
204 let column = |c: &[f64; 3]| Vec3::new(c[0], c[1], c[2]);
205 Transform3::from_mat3_translation(
206 Mat3::from_cols(column(&linear[0]), column(&linear[1]), column(&linear[2])),
207 column(translation),
208 )
209}
210
211/// Resolve a project-to-map coordinate operation and normalize both frames
212/// to metres.
213///
214/// `project_metres_per_unit` is the project's `IfcUnitAssignment` length scale.
215/// It is explicit here because project units are owned by the caller's model
216/// loading boundary, while `MapUnit` is owned by the target CRS.
217///
218/// When the header pins IFC4 or IFC4X3 this is
219/// [`resolve_project_to_map_in`] on that view, so an IFC4X3-only entity in
220/// an IFC4 file is refused as undeclared. Without a usable header the
221/// IFC4X3 set is accepted unpinned: the attribute layouts coincide (see
222/// `view.rs`), but "not declared in this schema" cannot be told apart.
223pub fn resolve_project_to_map(
224 model: &Model,
225 id: EntityId,
226 project_metres_per_unit: f64,
227) -> GeorefResult<ProjectToMap> {
228 match GeorefView::for_model(model) {
229 Ok(view) => resolve_project_to_map_in(&view, id, project_metres_per_unit),
230 Err(_) => dispatch(model, None, id, project_metres_per_unit),
231 }
232}
233
234/// Resolve a project-to-map coordinate operation within a schema-pinned
235/// [`GeorefView`].
236///
237/// Refuses an entity the pinned schema does not declare
238/// (`IfcMapConversionScaled`, `IfcRigidOperation` or `IfcGeographicCRS`
239/// read from an IFC4 file) with [`GeorefError::UnsupportedOperation`]
240/// naming the release, and checks the operation's source against the
241/// pinned release's `IfcCoordinateReferenceSystemSelect`.
242pub fn resolve_project_to_map_in(
243 view: &GeorefView,
244 id: EntityId,
245 project_metres_per_unit: f64,
246) -> GeorefResult<ProjectToMap> {
247 view.require_known_type(id)?;
248 dispatch(view.model, Some(view), id, project_metres_per_unit)
249}
250
251fn dispatch(
252 model: &Model,
253 view: Option<&GeorefView>,
254 id: EntityId,
255 project_metres_per_unit: f64,
256) -> GeorefResult<ProjectToMap> {
257 let entity = model.get(id).ok_or(GeorefError::MissingEntity {
258 referrer: id,
259 missing: id,
260 })?;
261 if !project_metres_per_unit.is_finite() || project_metres_per_unit <= 0.0 {
262 return Err(GeorefError::InvalidUnit {
263 entity: id,
264 detail: "project length scale must be finite and positive",
265 });
266 }
267 let project_unit = LengthUnit {
268 name: "PROJECT_LENGTH_UNIT".into(),
269 metres_per_unit: project_metres_per_unit,
270 };
271 let actual_type = entity.type_name.to_ascii_uppercase();
272 let damage = Damage::of(model)?;
273 damage.check(id)?;
274 let operation = Operation {
275 model,
276 view,
277 id,
278 entity,
279 damage: &damage,
280 };
281 let lowered = match actual_type.as_str() {
282 "IFCMAPCONVERSION" => map::lower(&operation, project_unit, false),
283 "IFCMAPCONVERSIONSCALED" => map::lower(&operation, project_unit, true),
284 "IFCRIGIDOPERATION" => rigid::lower(&operation, project_unit),
285 _ => Err(GeorefError::WrongType {
286 entity: id,
287 expected: "IFCCOORDINATEOPERATION",
288 actual: entity.type_name.to_string(),
289 }),
290 }?;
291 damage.settle(lowered)
292}
293
294/// The operation being lowered, with the view that pinned it (if any).
295pub(super) struct Operation<'m, 'v> {
296 pub model: &'m Model,
297 pub view: Option<&'v GeorefView<'m>>,
298 pub id: EntityId,
299 pub entity: &'m Entity,
300 /// The entry point's reader damage (#690), shared by every record read.
301 pub damage: &'v Damage,
302}
303
304impl Operation<'_, '_> {
305 /// Read the operation's source, refusing the operation record and the
306 /// source when the reader reported either (#690).
307 pub fn source(&self) -> GeorefResult<OperationSource> {
308 self.damage.check(self.id)?;
309 let source = operation_source(self.model, self.view, self.id, Some(self.damage))?;
310 self.damage.check(source.entity())?;
311 Ok(source)
312 }
313
314 pub fn required_ref(&self, index: usize, name: &'static str) -> GeorefResult<EntityId> {
315 self.entity
316 .reference(index)
317 .ok_or(GeorefError::MissingAttribute {
318 entity: self.id,
319 index,
320 name,
321 })
322 }
323
324 pub fn required_number(&self, index: usize, name: &'static str) -> GeorefResult<f64> {
325 self.entity
326 .attribute(index)
327 .and_then(|v| v.unwrap_typed().as_f64())
328 .ok_or(GeorefError::MissingAttribute {
329 entity: self.id,
330 index,
331 name,
332 })
333 }
334
335 pub fn optional_number(&self, index: usize, name: &'static str) -> GeorefResult<Option<f64>> {
336 match self.entity.attribute(index).map(Value::unwrap_typed) {
337 None | Some(Value::Null) => Ok(None),
338 Some(value) => value
339 .as_f64()
340 .map(Some)
341 .ok_or(GeorefError::InvalidAttribute {
342 entity: self.id,
343 index,
344 name,
345 }),
346 }
347 }
348
349 /// Refuse a non-finite value, naming the slot it came from.
350 pub fn finite(&self, index: usize, name: &'static str, value: f64) -> GeorefResult<f64> {
351 if value.is_finite() {
352 Ok(value)
353 } else {
354 Err(GeorefError::InvalidAttribute {
355 entity: self.id,
356 index,
357 name,
358 })
359 }
360 }
361}