ifc_georef/site/
reference.rs1use ifc_model::value::Value;
4use ifc_model::{EntityId, Model};
5use ifc_schema::SchemaVersion;
6
7use super::angle::{read_angle, Axis, CompoundPlaneAngle};
8use crate::error::{GeorefError, GeorefResult};
9use crate::slot::site as slot;
10
11#[non_exhaustive]
13#[derive(Debug, Clone, PartialEq)]
14pub struct SiteReference {
15 pub entity: EntityId,
17 pub version: SchemaVersion,
19 pub ref_latitude: Option<CompoundPlaneAngle>,
22 pub ref_longitude: Option<CompoundPlaneAngle>,
25 pub ref_elevation: Option<f64>,
28}
29
30impl SiteReference {
31 #[must_use]
33 pub fn latitude_degrees(&self) -> Option<f64> {
34 self.ref_latitude.map(|a| a.decimal_degrees())
35 }
36
37 #[must_use]
39 pub fn longitude_degrees(&self) -> Option<f64> {
40 self.ref_longitude.map(|a| a.decimal_degrees())
41 }
42}
43
44pub fn site_reference(
54 model: &Model,
55 site: EntityId,
56 project_metres_per_unit: f64,
57) -> GeorefResult<SiteReference> {
58 let version = site_release(model)?;
59 let entity = model.get(site).ok_or(GeorefError::MissingEntity {
60 referrer: site,
61 missing: site,
62 })?;
63 if !entity.is_type("IFCSITE") {
64 return Err(GeorefError::WrongType {
65 entity: site,
66 expected: "IFCSITE",
67 actual: entity.type_name.to_string(),
68 });
69 }
70 if !project_metres_per_unit.is_finite() || project_metres_per_unit <= 0.0 {
71 return Err(GeorefError::InvalidUnit {
72 entity: site,
73 detail: "project length scale must be finite and positive",
74 });
75 }
76 let ref_latitude = read_angle(
77 entity.attribute(slot::REF_LATITUDE),
78 site,
79 slot::REF_LATITUDE,
80 Axis::Latitude,
81 version,
82 )?;
83 let ref_longitude = read_angle(
84 entity.attribute(slot::REF_LONGITUDE),
85 site,
86 slot::REF_LONGITUDE,
87 Axis::Longitude,
88 version,
89 )?;
90 let invalid_elevation = GeorefError::InvalidAttribute {
91 entity: site,
92 index: slot::REF_ELEVATION,
93 name: "RefElevation",
94 };
95 let ref_elevation = match entity
96 .attribute(slot::REF_ELEVATION)
97 .map(Value::unwrap_typed)
98 {
99 None | Some(Value::Null) => None,
100 Some(value) => {
101 let metres = value.as_f64().ok_or(invalid_elevation.clone())? * project_metres_per_unit;
102 if !metres.is_finite() {
103 return Err(invalid_elevation);
104 }
105 Some(metres)
106 }
107 };
108 Ok(SiteReference {
109 entity: site,
110 version,
111 ref_latitude,
112 ref_longitude,
113 ref_elevation,
114 })
115}
116
117fn site_release(model: &Model) -> GeorefResult<SchemaVersion> {
122 let token = match model.header().schema.as_slice() {
123 [] => return Err(GeorefError::MissingSchema),
124 [token] => token,
125 tokens => {
126 return Err(GeorefError::AmbiguousSchema {
127 tokens: tokens.to_vec(),
128 })
129 }
130 };
131 match SchemaVersion::from_header_token(token) {
132 Some(version @ (SchemaVersion::Ifc2x3 | SchemaVersion::Ifc4 | SchemaVersion::Ifc4x3)) => {
133 Ok(version)
134 }
135 _ => Err(GeorefError::UnsupportedSchema {
138 token: token.clone(),
139 }),
140 }
141}