Skip to main content

ifc_georef/context/
source.rs

1//! The source side of a coordinate operation, and its inverse.
2//!
3//! `IfcCoordinateOperation.SourceCRS` is typed
4//! `IfcCoordinateReferenceSystemSelect = SELECT
5//! (IfcCoordinateReferenceSystem, IfcGeometricRepresentationContext)` in
6//! both IFC4 ADD2 TC1 and IFC4X3 ADD2. Both releases declare the matching
7//! inverse `HasCoordinateOperation : SET [0:1] OF IfcCoordinateOperation
8//! FOR SourceCRS` on `IfcCoordinateReferenceSystem` and on
9//! `IfcGeometricRepresentationContext`, and
10//! `IfcGeometricRepresentationSubContext` adds
11//! `WHERE NoCoordOperation : SIZEOF(...HasCoordinateOperation) = 0`.
12//!
13//! What differs is which CRS subtypes exist: IFC4 declares only
14//! `IfcProjectedCRS`; IFC4X3 adds `IfcGeographicCRS`. A schema-pinned read
15//! asks the pinned table; an unpinned read (no usable header) accepts the
16//! union and cannot tell the two apart.
17//!
18//! The inverse is not stored in a STEP file: it is recovered by scanning
19//! every `IfcCoordinateOperation` subtype for a `SourceCRS` naming the
20//! entity. More than one breaks the `SET [0:1]` and is refused rather than
21//! one operation being picked.
22
23use ifc_model::value::Value;
24use ifc_model::{EntityId, Model};
25
26use crate::crs::Damage;
27use crate::error::{GeorefError, GeorefResult};
28use crate::slot::map_conversion as slot;
29use crate::view::GeorefView;
30
31/// The rule label reported when a source has more than one operation.
32pub(crate) const HAS_COORDINATE_OPERATION: &str =
33    "HasCoordinateOperation : SET [0:1] OF IfcCoordinateOperation";
34
35/// Coordinate-operation types an unpinned read recognizes: the IFC4X3 set,
36/// which contains IFC4's.
37const UNPINNED_OPERATIONS: &[&str] = &[
38    "IFCMAPCONVERSION",
39    "IFCMAPCONVERSIONSCALED",
40    "IFCRIGIDOPERATION",
41];
42
43/// CRS types an unpinned read recognizes as a source.
44const UNPINNED_CRS: &[&str] = &["IFCPROJECTEDCRS", "IFCGEOGRAPHICCRS"];
45
46/// The validated `SourceCRS` of a coordinate operation.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48#[non_exhaustive]
49pub enum OperationSource {
50    /// An `IfcGeometricRepresentationContext` (never a sub-context, which
51    /// `NoCoordOperation` forbids): the usual case, the project's own
52    /// engineering frame.
53    Context(EntityId),
54    /// An `IfcCoordinateReferenceSystem` subtype: an operation chained from
55    /// another CRS.
56    CoordinateReferenceSystem(EntityId),
57    /// IFC2X3: the `IfcProject` (or, as a legacy fallback, the `IfcSite`)
58    /// whose `ePSet_MapConversion` and `ePSet_ProjectedCRS` state the
59    /// operation. IFC2X3 has no `SourceCRS`; the property sets apply to the
60    /// object they are attached to (see
61    /// [`crate::resolve_property_set_georeferencing`]).
62    PropertySet(EntityId),
63}
64
65impl OperationSource {
66    /// The source entity, whichever select member it is.
67    #[must_use]
68    pub const fn entity(&self) -> EntityId {
69        match self {
70            Self::Context(id) | Self::CoordinateReferenceSystem(id) | Self::PropertySet(id) => *id,
71        }
72    }
73}
74
75/// Read and validate the `SourceCRS` of the coordinate operation
76/// `operation` in a schema-pinned view.
77///
78/// # Errors
79///
80/// [`GeorefError::WrongType`] when `operation` is not an
81/// `IfcCoordinateOperation`, or its source is not a member of
82/// `IfcCoordinateReferenceSystemSelect`;
83/// [`GeorefError::UnsupportedOperation`] when either type is not declared
84/// in the pinned release (an `IfcGeographicCRS` under IFC4);
85/// [`GeorefError::MissingAttribute`] / [`GeorefError::InvalidAttribute`]
86/// for an unset or non-reference `SourceCRS`;
87/// [`GeorefError::MissingEntity`] for a dangling one;
88/// [`GeorefError::RuleViolation`] for a sub-context source
89/// (`NoCoordOperation`) or a source with more than one operation
90/// (`HasCoordinateOperation`).
91pub fn resolve_operation_source(
92    view: &GeorefView,
93    operation: EntityId,
94) -> GeorefResult<OperationSource> {
95    let actual = view.require_known_type(operation)?;
96    if !view.schema.is_a(actual, "IfcCoordinateOperation") {
97        return Err(GeorefError::WrongType {
98            entity: operation,
99            expected: "IFCCOORDINATEOPERATION",
100            actual: actual.to_owned(),
101        });
102    }
103    operation_source(view.model, Some(view), operation, None)
104}
105
106/// The one coordinate operation whose `SourceCRS` is `source`: the
107/// `HasCoordinateOperation` inverse, read in a schema-pinned view.
108///
109/// `Ok(None)` means `source` is a valid source with no operation.
110///
111/// # Errors
112///
113/// [`GeorefError::MissingEntity`] when `source` is not in the model;
114/// [`GeorefError::WrongType`] / [`GeorefError::UnsupportedOperation`] when
115/// it is not an `IfcCoordinateReferenceSystemSelect` member in the pinned
116/// release; [`GeorefError::RuleViolation`] when more than one operation
117/// names it, or a sub-context has any.
118pub fn coordinate_operation_for(
119    view: &GeorefView,
120    source: EntityId,
121) -> GeorefResult<Option<EntityId>> {
122    let model = view.model;
123    if model.get(source).is_none() {
124        return Err(GeorefError::MissingEntity {
125            referrer: source,
126            missing: source,
127        });
128    }
129    classify(model, Some(view), source)?;
130    let operations = operations_from(model, Some(view), source, None)?;
131    match operations.as_slice() {
132        [] => Ok(None),
133        [one] => {
134            forbid_sub_context(model, source)?;
135            Ok(Some(*one))
136        }
137        _ => Err(GeorefError::RuleViolation {
138            entity: source,
139            rule: HAS_COORDINATE_OPERATION,
140        }),
141    }
142}
143
144/// Read, type-check and inverse-check `operation`'s `SourceCRS`. `view`
145/// pins the release; `None` accepts the IFC4X3 union.
146pub(crate) fn operation_source(
147    model: &Model,
148    view: Option<&GeorefView>,
149    operation: EntityId,
150    damage: Option<&Damage>,
151) -> GeorefResult<OperationSource> {
152    let entity = model.get(operation).ok_or(GeorefError::MissingEntity {
153        referrer: operation,
154        missing: operation,
155    })?;
156    let source = match entity.attribute(slot::SOURCE_CRS) {
157        None | Some(Value::Null) => {
158            return Err(GeorefError::MissingAttribute {
159                entity: operation,
160                index: slot::SOURCE_CRS,
161                name: "SourceCRS",
162            })
163        }
164        Some(value) => value.as_ref_id().ok_or(GeorefError::InvalidAttribute {
165            entity: operation,
166            index: slot::SOURCE_CRS,
167            name: "SourceCRS",
168        })?,
169    };
170    if model.get(source).is_none() {
171        return Err(GeorefError::MissingEntity {
172            referrer: operation,
173            missing: source,
174        });
175    }
176    let classified = classify(model, view, source)?;
177    forbid_sub_context(model, source)?;
178    if operations_from(model, view, source, damage)?.len() > 1 {
179        return Err(GeorefError::RuleViolation {
180            entity: source,
181            rule: HAS_COORDINATE_OPERATION,
182        });
183    }
184    Ok(classified)
185}
186
187/// Which `IfcCoordinateReferenceSystemSelect` member `id` is.
188fn classify(
189    model: &Model,
190    view: Option<&GeorefView>,
191    id: EntityId,
192) -> GeorefResult<OperationSource> {
193    let entity = model.get(id).ok_or(GeorefError::MissingEntity {
194        referrer: id,
195        missing: id,
196    })?;
197    let type_name = entity.type_name.as_ref();
198    let (is_context, is_crs) = match view {
199        Some(view) => {
200            let declared = view.require_known_type(id)?;
201            (
202                view.schema
203                    .is_a(declared, "IfcGeometricRepresentationContext"),
204                view.schema.is_a(declared, "IfcCoordinateReferenceSystem"),
205            )
206        }
207        None => (
208            entity.is_type("IFCGEOMETRICREPRESENTATIONCONTEXT")
209                || entity.is_type("IFCGEOMETRICREPRESENTATIONSUBCONTEXT"),
210            UNPINNED_CRS.iter().any(|crs| entity.is_type(crs)),
211        ),
212    };
213    if is_context {
214        Ok(OperationSource::Context(id))
215    } else if is_crs {
216        Ok(OperationSource::CoordinateReferenceSystem(id))
217    } else {
218        Err(GeorefError::WrongType {
219            entity: id,
220            expected: "IFCCOORDINATEREFERENCESYSTEM or IFCGEOMETRICREPRESENTATIONCONTEXT",
221            actual: type_name.to_owned(),
222        })
223    }
224}
225
226/// `IfcGeometricRepresentationSubContext.NoCoordOperation`.
227fn forbid_sub_context(model: &Model, source: EntityId) -> GeorefResult<()> {
228    match model.get(source) {
229        Some(entity) if entity.is_type("IFCGEOMETRICREPRESENTATIONSUBCONTEXT") => {
230            Err(GeorefError::RuleViolation {
231                entity: source,
232                rule: "NoCoordOperation",
233            })
234        }
235        _ => Ok(()),
236    }
237}
238
239/// Every coordinate operation whose `SourceCRS` references `source`, in
240/// ascending id order.
241///
242/// With `damage`, every operation scanned is checked before its source is
243/// read (#690): a reported operation may be the copy that named `source`.
244fn operations_from(
245    model: &Model,
246    view: Option<&GeorefView>,
247    source: EntityId,
248    damage: Option<&Damage>,
249) -> GeorefResult<Vec<EntityId>> {
250    let types: Vec<&str> = match view {
251        Some(view) => view.schema.subtypes("IfcCoordinateOperation"),
252        None => UNPINNED_OPERATIONS.to_vec(),
253    };
254    let mut found = Vec::new();
255    for (id, operation) in types
256        .into_iter()
257        .flat_map(|type_name| model.of_type(type_name))
258    {
259        if let Some(damage) = damage {
260            damage.check(id)?;
261        }
262        if operation.reference(slot::SOURCE_CRS) == Some(source) {
263            found.push(id);
264        }
265    }
266    found.sort_unstable();
267    found.dedup();
268    Ok(found)
269}