ifc_lite_core/
georef_site.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Two reads of the model's geographic placement that are not a coordinate
6//! operation: `IfcSite.RefLatitude` / `RefLongitude` / `RefElevation`, and the
7//! model context's `TrueNorth`.
8//!
9//! The site read is the one the legacy georeferencing fallback
10//! (`GeoRefExtractor::extract_from_site`) uses, exposed so a consumer that
11//! needs the site location even when an `IfcMapConversion` exists (an earth
12//! anchor point) reads the same numbers. `TrueNorth` had no reader outside the
13//! map-conversion STEP rewrite, whose refusal policy is its own.
14
15use super::georef_parse::{compound_angle_has_literal_negative_zero, compound_plane_angle_to_degrees};
16use crate::decoder::EntityDecoder;
17use crate::error::Result;
18use crate::parser::{keyword_eq, EntityScanner};
19use crate::slot;
20
21/// `IfcSite`'s reference location.
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub struct SiteRefLocation {
24    /// WGS84 degrees, north positive.
25    pub latitude: f64,
26    /// WGS84 degrees, east positive.
27    pub longitude: f64,
28    /// `RefElevation` as authored, in the file's length unit; `0.0` when absent.
29    pub elevation: f64,
30}
31
32/// The reference location of site `site_id`, or `None` when it lacks a
33/// readable latitude or longitude.
34pub fn site_ref_location(decoder: &mut EntityDecoder, site_id: u32) -> Result<Option<SiteRefLocation>> {
35    let site = decoder.decode_by_id(site_id)?;
36    let latitude = compound_plane_angle_to_degrees(&site, slot::IfcSite::REF_LATITUDE.index());
37    let longitude = compound_plane_angle_to_degrees(&site, slot::IfcSite::REF_LONGITUDE.index());
38    let (Some(mut latitude), Some(mut longitude)) = (latitude, longitude) else {
39        return Ok(None);
40    };
41    // The `-0` leniency (TS parity, see `compoundPlaneAngleToDecimalDegrees`
42    // in `georef-extractor.ts`): a writer that signs a zero-magnitude
43    // component of the compound angle (e.g. `(-0, 30, 0)` for 0°30'S)
44    // survives only via the entity's RAW record bytes, because the shared
45    // tokenizer parses `-0` as an `i64` with no negative zero. Re-scanning
46    // this one attribute pair recovers the sign without touching the hot
47    // tokenizer.
48    if let Some(bytes) = decoder.get_raw_bytes(site_id) {
49        if latitude >= 0.0 && compound_angle_has_literal_negative_zero(bytes, slot::IfcSite::REF_LATITUDE.index()) {
50            latitude = -latitude;
51        }
52        if longitude >= 0.0 && compound_angle_has_literal_negative_zero(bytes, slot::IfcSite::REF_LONGITUDE.index()) {
53            longitude = -longitude;
54        }
55    }
56    let elevation = site.real_at(slot::IfcSite::REF_ELEVATION).unwrap_or(0.0);
57    Ok(Some(SiteRefLocation { latitude, longitude, elevation }))
58}
59
60/// The model context's `TrueNorth`: the unit XY direction of true north in
61/// the project's world coordinates.
62///
63/// Read from the first `IfcGeometricRepresentationContext` (not a
64/// sub-context) whose `ContextType` is `Model`, else the first context. `None`
65/// when that context has no `TrueNorth`, it names a missing record, or its XY
66/// part is zero, and a counted
67/// refusal when the slot is not a reference or the direction fails the
68/// `IfcDirection` leaf rule; IFC then means +Y, which the caller supplies. A
69/// three-ratio direction keeps its XY part.
70///
71/// `decoder` must be over `content`; pass one that already holds an entity
72/// index, or the direction lookup builds one.
73pub fn model_true_north(content: &[u8], decoder: &mut EntityDecoder) -> Option<[f64; 2]> {
74    let mut scanner = EntityScanner::new(content);
75    let mut chosen = None;
76    while let Some((id, type_name, start, end)) = scanner.next_entity() {
77        if !keyword_eq(type_name, "IFCGEOMETRICREPRESENTATIONCONTEXT") {
78            continue;
79        }
80        let Ok(context) = decoder.decode_at_with_id(id, start, end) else { continue };
81        let is_model = context
82            .string_at(slot::IfcGeometricRepresentationContext::CONTEXT_TYPE)
83            .is_some_and(|t| t.eq_ignore_ascii_case("model"));
84        if chosen.is_none() || is_model {
85            chosen = Some(context);
86        }
87        if is_model {
88            break;
89        }
90    }
91    let [x, y, _] = decoder.direction3_at(&chosen?, slot::IfcGeometricRepresentationContext::TRUE_NORTH.index()).ok()??;
92    unit_xy(x, y)
93}
94
95/// `(x, y)` scaled to unit length, or `None` when its length is zero or not
96/// finite. The normalisation [`model_true_north`] applies to a `TrueNorth`,
97/// shared with callers that turn another XY direction (a map conversion's
98/// grid north) into a north.
99pub fn unit_xy(x: f64, y: f64) -> Option<[f64; 2]> {
100    let length = x.hypot(y);
101    (length.is_finite() && length > 0.0).then(|| [x / length, y / length])
102}