1use std::collections::BTreeMap;
79
80use ifc_model::value::Value;
81use ifc_model::{Entity, EntityId, Model};
82use ifc_schema::{for_version, SchemaVersion};
83
84use crate::context::OperationSource;
85use crate::crs::{resolve_length_unit, Damage, LengthUnit, ProjectedCrs};
86use crate::error::{GeorefError, GeorefResult};
87use crate::slot::{property_set, property_single_value, rel_defines_by_properties};
88use crate::view::declared_release;
89
90use super::map::linear_part;
91use super::operation::{OperationKind, ProjectToMap};
92
93pub const MAP_CONVERSION_PSET: &str = "ePSet_MapConversion";
95pub const PROJECTED_CRS_PSET: &str = "ePSet_ProjectedCRS";
97
98#[must_use]
104pub fn has_property_set_georeferencing(model: &Model) -> bool {
105 model
106 .of_type("IFCPROPERTYSET")
107 .any(|(_, set)| pset_kind(set).is_some())
108}
109
110pub fn resolve_property_set_georeferencing(
132 model: &Model,
133 project_metres_per_unit: f64,
134) -> GeorefResult<Vec<ProjectToMap>> {
135 let (token, version) = declared_release(model)?;
136 if version != SchemaVersion::Ifc2x3 || for_version(version).is_err() {
137 return Err(GeorefError::UnsupportedSchema {
138 token: token.clone(),
139 });
140 }
141 let damage = Damage::of(model)?;
142 let hosts = hosts(model, &damage)?;
143 if hosts.is_empty() {
144 if damage.records_lost() && has_property_set_georeferencing(model) {
147 return Err(GeorefError::RecordsIncomplete {
148 diagnostics: damage.diagnostics(),
149 });
150 }
151 return damage.settle(Vec::new());
152 }
153 if !project_metres_per_unit.is_finite() || project_metres_per_unit <= 0.0 {
154 let (&host, _) = hosts.iter().next().expect("not empty");
155 return Err(GeorefError::InvalidUnit {
156 entity: host,
157 detail: "project length scale must be finite and positive",
158 });
159 }
160 let project_unit = LengthUnit {
161 name: "PROJECT_LENGTH_UNIT".into(),
162 metres_per_unit: project_metres_per_unit,
163 };
164 let any_project = hosts.values().any(|sets| sets.is_project);
165 let resolved = hosts
166 .iter()
167 .filter(|(_, sets)| sets.is_project == any_project)
168 .map(|(&host, sets)| resolve_host(model, host, sets, &project_unit, &damage))
169 .collect::<GeorefResult<Vec<_>>>()?;
170 damage.settle(resolved)
171}
172
173#[derive(Clone, Copy, PartialEq, Eq)]
175enum Kind {
176 MapConversion,
177 ProjectedCrs,
178}
179
180fn pset_kind(set: &Entity) -> Option<Kind> {
181 let name = set.text(property_set::NAME)?;
182 if name.eq_ignore_ascii_case(MAP_CONVERSION_PSET) {
183 Some(Kind::MapConversion)
184 } else if name.eq_ignore_ascii_case(PROJECTED_CRS_PSET) {
185 Some(Kind::ProjectedCrs)
186 } else {
187 None
188 }
189}
190
191#[derive(Default)]
193struct HostSets {
194 is_project: bool,
195 map_conversion: Vec<EntityId>,
196 projected_crs: Vec<EntityId>,
197}
198
199fn hosts(model: &Model, damage: &Damage) -> GeorefResult<BTreeMap<EntityId, HostSets>> {
203 let mut hosts: BTreeMap<EntityId, HostSets> = BTreeMap::new();
204 for (rel_id, rel) in model.of_type("IFCRELDEFINESBYPROPERTIES") {
205 damage.check(rel_id)?;
206 let Some(set_id) = rel.reference(rel_defines_by_properties::RELATING_PROPERTY_DEFINITION)
207 else {
208 continue;
209 };
210 damage.check(set_id)?;
211 let Some(kind) = model
212 .get(set_id)
213 .filter(|set| set.is_type("IFCPROPERTYSET"))
214 .and_then(pset_kind)
215 else {
216 continue;
217 };
218 let related = rel
219 .attribute(rel_defines_by_properties::RELATED_OBJECTS)
220 .and_then(Value::as_list)
221 .unwrap_or(&[]);
222 for object in related.iter().filter_map(Value::as_ref_id) {
223 damage.check(object)?;
224 let host = model.get(object).ok_or(GeorefError::MissingEntity {
225 referrer: rel_id,
226 missing: object,
227 })?;
228 let is_project = host.is_type("IFCPROJECT");
229 if !is_project && !host.is_type("IFCSITE") {
230 continue;
231 }
232 let sets = hosts.entry(object).or_default();
233 sets.is_project = is_project;
234 let list = match kind {
235 Kind::MapConversion => &mut sets.map_conversion,
236 Kind::ProjectedCrs => &mut sets.projected_crs,
237 };
238 if !list.contains(&set_id) {
239 list.push(set_id);
240 }
241 }
242 }
243 Ok(hosts)
244}
245
246fn one(host: EntityId, name: &'static str, sets: &[EntityId]) -> GeorefResult<EntityId> {
248 match sets {
249 [] => Err(GeorefError::IncompletePropertySets {
250 host,
251 missing: name,
252 }),
253 [one] => Ok(*one),
254 _ => {
255 let mut sets = sets.to_vec();
256 sets.sort_unstable();
257 Err(GeorefError::AmbiguousPropertySets { host, name, sets })
258 }
259 }
260}
261
262fn resolve_host(
263 model: &Model,
264 host: EntityId,
265 sets: &HostSets,
266 project_unit: &LengthUnit,
267 damage: &Damage,
268) -> GeorefResult<ProjectToMap> {
269 if sets.map_conversion.len() > 1 {
272 one(host, MAP_CONVERSION_PSET, &sets.map_conversion)?;
273 }
274 if sets.projected_crs.len() > 1 {
275 one(host, PROJECTED_CRS_PSET, &sets.projected_crs)?;
276 }
277 let conversion = Properties::read(
278 model,
279 one(host, MAP_CONVERSION_PSET, &sets.map_conversion)?,
280 damage,
281 )?;
282 let crs = Properties::read(
283 model,
284 one(host, PROJECTED_CRS_PSET, &sets.projected_crs)?,
285 damage,
286 )?;
287
288 let target_crs = projected_crs(&crs)?;
289 let map_unit = target_crs
290 .map_unit
291 .clone()
292 .unwrap_or_else(|| project_unit.clone());
293
294 let eastings = conversion.length(model, "Eastings", &map_unit)?;
295 let northings = conversion.length(model, "Northings", &map_unit)?;
296 let height = conversion.length(model, "OrthogonalHeight", &map_unit)?;
297 let a = conversion.real("XAxisAbscissa")?.map_or(1.0, |(_, v)| v);
298 let b = conversion.real("XAxisOrdinate")?.map_or(0.0, |(_, v)| v);
299 let norm = a.hypot(b);
300 if !norm.is_finite() || norm <= f64::EPSILON {
301 return Err(GeorefError::DegenerateAxis {
302 entity: conversion.set,
303 });
304 }
305 let (a, b) = (a / norm, b / norm);
306 let declared_scale = conversion.real("Scale")?.map_or(1.0, |(_, v)| v);
307 if declared_scale <= 0.0 {
308 return Err(GeorefError::InvalidScale {
309 entity: conversion.set,
310 value: declared_scale,
311 });
312 }
313 let scale = declared_scale * map_unit.metres_per_unit / project_unit.metres_per_unit;
314 if !scale.is_finite() || scale <= 0.0 {
315 return Err(GeorefError::InvalidScale {
316 entity: conversion.set,
317 value: scale,
318 });
319 }
320 let linear = linear_part(scale, (a, b), (1.0, 1.0, 1.0));
321 let metres = map_unit.metres_per_unit;
322 let translation = [eastings * metres, northings * metres, height * metres];
323 for (value, name) in translation
324 .iter()
325 .zip(["Eastings", "Northings", "OrthogonalHeight"])
326 {
327 if !value.is_finite() {
328 let (property, _) = conversion.get(name).expect("read above");
329 return Err(GeorefError::InvalidProperty {
330 property_set: conversion.set,
331 property,
332 name,
333 expected: "a length whose value in metres is finite",
334 });
335 }
336 }
337
338 Ok(ProjectToMap::new(
339 OperationSource::PropertySet(host),
340 conversion.set,
341 OperationKind::MapConversion,
342 target_crs,
343 [eastings, northings, height],
344 (project_unit.clone(), map_unit),
345 declared_scale,
346 (a, b),
347 linear,
348 translation,
349 ))
350}
351
352fn projected_crs(crs: &Properties) -> GeorefResult<ProjectedCrs> {
354 let name = crs.text("Name")?.ok_or(GeorefError::MissingProperty {
355 property_set: crs.set,
356 name: "Name",
357 })?;
358 let map_unit = match crs.text("MapUnit")? {
359 None => None,
360 Some(text) => {
361 let (property, _) = crs.get("MapUnit").expect("read above");
362 Some(si_length_unit(&text).ok_or(GeorefError::InvalidProperty {
363 property_set: crs.set,
364 property,
365 name: "MapUnit",
366 expected: "the name of an SI length unit, such as METRE or MILLIMETRE",
367 })?)
368 }
369 };
370 Ok(ProjectedCrs {
371 entity: crs.set,
372 name: Some(name),
373 description: crs.text("Description")?,
374 geodetic_datum: crs.text("GeodeticDatum")?,
375 vertical_datum: crs.text("VerticalDatum")?,
376 map_projection: crs.text("MapProjection")?,
377 map_zone: crs.text("MapZone")?,
378 map_unit,
379 well_known_text: None,
380 })
381}
382
383fn si_length_unit(text: &str) -> Option<LengthUnit> {
386 const PREFIXES: &[(&str, f64)] = &[
387 ("", 1.0),
388 ("EXA", 1e18),
389 ("PETA", 1e15),
390 ("TERA", 1e12),
391 ("GIGA", 1e9),
392 ("MEGA", 1e6),
393 ("KILO", 1e3),
394 ("HECTO", 1e2),
395 ("DECA", 1e1),
396 ("DECI", 1e-1),
397 ("CENTI", 1e-2),
398 ("MILLI", 1e-3),
399 ("MICRO", 1e-6),
400 ("NANO", 1e-9),
401 ("PICO", 1e-12),
402 ("FEMTO", 1e-15),
403 ("ATTO", 1e-18),
404 ];
405 let upper = text.trim().to_ascii_uppercase();
406 let prefix = upper.strip_suffix("METRE")?;
407 PREFIXES
408 .iter()
409 .find(|(p, _)| *p == prefix)
410 .map(|&(_, metres_per_unit)| LengthUnit {
411 name: upper.clone(),
412 metres_per_unit,
413 })
414}
415
416struct Properties<'m> {
418 set: EntityId,
419 damage: &'m Damage,
420 by_name: BTreeMap<&'m str, (EntityId, &'m Entity)>,
421}
422
423impl<'m> Properties<'m> {
424 fn read(model: &'m Model, set: EntityId, damage: &'m Damage) -> GeorefResult<Self> {
427 damage.check(set)?;
428 let entity = model.get(set).ok_or(GeorefError::MissingEntity {
429 referrer: set,
430 missing: set,
431 })?;
432 let members = entity
433 .attribute(property_set::HAS_PROPERTIES)
434 .and_then(Value::as_list)
435 .ok_or(GeorefError::InvalidAttribute {
436 entity: set,
437 index: property_set::HAS_PROPERTIES,
438 name: "HasProperties",
439 })?;
440 let mut by_name = BTreeMap::new();
441 for member in members {
442 let id = member.as_ref_id().ok_or(GeorefError::InvalidAttribute {
443 entity: set,
444 index: property_set::HAS_PROPERTIES,
445 name: "HasProperties",
446 })?;
447 damage.check(id)?;
448 let property = model.get(id).ok_or(GeorefError::MissingEntity {
449 referrer: set,
450 missing: id,
451 })?;
452 let Some(name) = property.text(property_single_value::NAME) else {
453 return Err(GeorefError::InvalidAttribute {
454 entity: id,
455 index: property_single_value::NAME,
456 name: "Name",
457 });
458 };
459 if by_name.insert(name, (id, property)).is_some() {
460 return Err(GeorefError::RuleViolation {
461 entity: set,
462 rule: "WR32 : IfcUniquePropertyName(HasProperties)",
463 });
464 }
465 }
466 Ok(Self {
467 set,
468 damage,
469 by_name,
470 })
471 }
472
473 fn get(&self, name: &str) -> Option<(EntityId, &'m Entity)> {
474 self.by_name.get(name).copied()
475 }
476
477 fn nominal(
480 &self,
481 name: &'static str,
482 expected: &'static str,
483 ) -> GeorefResult<Option<(EntityId, &'m Entity, &'m Value)>> {
484 let Some((id, property)) = self.get(name) else {
485 return Ok(None);
486 };
487 if !property.is_type("IFCPROPERTYSINGLEVALUE") {
488 return Err(self.invalid(id, name, expected));
489 }
490 match property.attribute(property_single_value::NOMINAL_VALUE) {
491 None | Some(Value::Null) => Ok(None),
492 Some(value) => Ok(Some((id, property, value))),
493 }
494 }
495
496 fn invalid(
497 &self,
498 property: EntityId,
499 name: &'static str,
500 expected: &'static str,
501 ) -> GeorefError {
502 GeorefError::InvalidProperty {
503 property_set: self.set,
504 property,
505 name,
506 expected,
507 }
508 }
509
510 fn measure(
512 &self,
513 name: &'static str,
514 measure: &'static str,
515 expected: &'static str,
516 ) -> GeorefResult<Option<(EntityId, &'m Entity, f64)>> {
517 let Some((id, property, value)) = self.nominal(name, expected)? else {
518 return Ok(None);
519 };
520 match value {
521 Value::Typed { type_name, value } if type_name.eq_ignore_ascii_case(measure) => {
522 match value.as_f64() {
523 Some(number) if number.is_finite() => Ok(Some((id, property, number))),
524 _ => Err(self.invalid(id, name, expected)),
525 }
526 }
527 _ => Err(self.invalid(id, name, expected)),
528 }
529 }
530
531 fn length(
534 &self,
535 model: &Model,
536 name: &'static str,
537 map_unit: &LengthUnit,
538 ) -> GeorefResult<f64> {
539 const EXPECTED: &str = "an IfcPropertySingleValue with a finite IfcLengthMeasure";
540 let (id, property, value) = self.measure(name, "IFCLENGTHMEASURE", EXPECTED)?.ok_or(
541 GeorefError::MissingProperty {
542 property_set: self.set,
543 name,
544 },
545 )?;
546 match property.attribute(property_single_value::UNIT) {
547 None | Some(Value::Null) => {}
548 Some(unit) => {
549 let unit = unit.as_ref_id().ok_or(GeorefError::InvalidAttribute {
550 entity: id,
551 index: property_single_value::UNIT,
552 name: "Unit",
553 })?;
554 let stated = resolve_length_unit(model, unit, self.damage)?;
555 if stated.metres_per_unit != map_unit.metres_per_unit {
556 return Err(self.invalid(
557 id,
558 name,
559 "a length in the map unit: its Unit states another",
560 ));
561 }
562 }
563 }
564 Ok(value)
565 }
566
567 fn real(&self, name: &'static str) -> GeorefResult<Option<(EntityId, f64)>> {
569 const EXPECTED: &str = "an IfcPropertySingleValue with a finite IfcReal and no Unit";
570 let Some((id, property, value)) = self.measure(name, "IFCREAL", EXPECTED)? else {
571 return Ok(None);
572 };
573 if !matches!(
574 property.attribute(property_single_value::UNIT),
575 None | Some(Value::Null)
576 ) {
577 return Err(self.invalid(id, name, EXPECTED));
578 }
579 Ok(Some((id, value)))
580 }
581
582 fn text(&self, name: &'static str) -> GeorefResult<Option<String>> {
584 const EXPECTED: &str =
585 "an IfcPropertySingleValue with an IfcLabel, IfcText or IfcIdentifier";
586 let Some((id, _, value)) = self.nominal(name, EXPECTED)? else {
587 return Ok(None);
588 };
589 match value {
590 Value::Typed { type_name, value }
591 if ["IFCLABEL", "IFCTEXT", "IFCIDENTIFIER"]
592 .iter()
593 .any(|t| type_name.eq_ignore_ascii_case(t)) =>
594 {
595 value
596 .as_text()
597 .map(|text| Some(text.to_owned()))
598 .ok_or_else(|| self.invalid(id, name, EXPECTED))
599 }
600 _ => Err(self.invalid(id, name, EXPECTED)),
601 }
602 }
603}
604
605#[cfg(test)]
606mod tests {
607 use super::si_length_unit;
608
609 #[test]
610 fn map_unit_names_resolve_only_si_length_units() {
611 assert_eq!(si_length_unit("METRE").unwrap().metres_per_unit, 1.0);
612 assert_eq!(si_length_unit("millimetre").unwrap().metres_per_unit, 1e-3);
613 assert_eq!(si_length_unit("KILOMETRE").unwrap().metres_per_unit, 1e3);
614 for refused in ["FOOT", "METER", "SQUARE_METRE", "MILLI", "", "XMETRE"] {
615 assert!(si_length_unit(refused).is_none(), "{refused}");
616 }
617 }
618}