Skip to main content

openbim_ifc_binding_core/geometry/
graph.rs

1//! Geometry, Level 2 (#367, ADR 0021): each product's Body as Axiolid's
2//! neutral geometry graph, serialised in Axiolid's versioned wire format.
3//!
4//! The payload is the envelope Axiolid defines (axiolid/kernel#267, Axiolid
5//! ADR 0085), JSON text or CBOR bytes:
6//!
7//! ```json
8//! {"format":"axiolid-geometry-graph","version":"1.0","graph":{"nodes":[...],"roots":[...]}}
9//! ```
10//!
11//! Nodes are in insertion order and a reference is the index of an earlier
12//! node; the graph is in world coordinates, metres, with the product's
13//! placement already applied. A host evaluates it with its own kernel, or
14//! reads it back with `GeometryGraph::from_json` / `from_cbor` in Rust.
15//! The envelope's `version` is the lowest wire format version its content
16//! needs: `1.0` unless a station in it carries a seam-snapping window
17//! (#423; a station on an offset whose length is a quadrature), then `1.1`,
18//! or a run's sections do (#429; a sectioned solid or surface along such
19//! an offset), then `1.2`, or an offset run continues to a basis end the
20//! kernel measures (#433; an `IfcOffsetCurveByDistances` along such an
21//! offset), then `1.3`, or a polygonal bounded half-space clips (#515; an
22//! `IfcPolygonalBoundedHalfSpace`, bounded along its `Position`'s Z), then
23//! `1.4` (axiolid/kernel#297, #301, #303, #321). A reader on
24//! `axiolid-model` 0.3.8 or older reads a `1.0` payload and refuses a
25//! `1.1` one; a reader on 0.3.10 or older refuses a `1.2` one, one on
26//! 0.3.11 or older a `1.3` one, and one on 0.3.13 or older a `1.4` one.
27//! [`GEOMETRY_FORMAT_VERSION`] is the newest version this build writes. A
28//! minor version of the wire format reaches every binding as a minor
29//! release, a major one is a breaking change of every binding (ADR 0021).
30
31use crate::record::{Field, Record, ToRecord};
32
33use super::GeometryRefusal;
34#[cfg(feature = "graph")]
35use super::{ids, product_identity, refusal};
36use crate::{BindingError, IfcModel};
37
38/// The wire format's name, the envelope's `format` entry.
39pub const GEOMETRY_FORMAT: &str = "axiolid-geometry-graph";
40
41/// The newest wire format version this build writes, `MAJOR.MINOR`. A
42/// payload's envelope carries the lowest version its content needs, so its
43/// `version` entry is this or an older minor of the same major (module
44/// documentation).
45pub const GEOMETRY_FORMAT_VERSION: &str = "1.5";
46
47/// How [`IfcModel::product_geometry`](crate::IfcModel::product_geometry)
48/// encodes each graph.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
50#[non_exhaustive]
51pub enum GeometryEncoding {
52    /// JSON text (RFC 8259), UTF-8.
53    #[default]
54    Json,
55    /// CBOR bytes (RFC 8949), smaller than the JSON.
56    Cbor,
57}
58
59impl GeometryEncoding {
60    /// `json` or `cbor`; `None` for anything else.
61    #[must_use]
62    pub fn parse(name: &str) -> Option<Self> {
63        match name {
64            "json" => Some(Self::Json),
65            "cbor" => Some(Self::Cbor),
66            _ => None,
67        }
68    }
69
70    /// `json` or `cbor`.
71    #[must_use]
72    pub const fn name(self) -> &'static str {
73        match self {
74            Self::Json => "json",
75            Self::Cbor => "cbor",
76        }
77    }
78}
79
80/// One product's Body as a serialised neutral geometry graph.
81#[derive(Debug, Clone, PartialEq)]
82pub struct ProductGeometry {
83    /// The product's entity id.
84    pub id: u64,
85    /// Its `GlobalId`.
86    pub global_id: Option<String>,
87    /// Its entity type, upper-case.
88    pub type_name: String,
89    /// The world placement, 4x4 column-major, metres: the graph already has
90    /// it applied, so a host never applies it again. `None` when refused.
91    pub transform: Option<[f64; 16]>,
92    /// The encoding of `payload`.
93    pub encoding: GeometryEncoding,
94    /// The wire payload: UTF-8 JSON text or CBOR bytes. `None` with no
95    /// refusal is a product with no Body representation (an axis only).
96    pub payload: Option<Vec<u8>>,
97    /// Why there is no graph.
98    pub refusal: Option<GeometryRefusal>,
99}
100
101impl ProductGeometry {
102    /// The payload as text, for [`GeometryEncoding::Json`].
103    #[must_use]
104    pub fn json(&self) -> Option<&str> {
105        match self.encoding {
106            GeometryEncoding::Json => std::str::from_utf8(self.payload.as_deref()?).ok(),
107            GeometryEncoding::Cbor => None,
108        }
109    }
110}
111
112impl IfcModel {
113    /// The Body of each of `products`, or, with `None`, of every product
114    /// that has a shape, in id order, as Axiolid's geometry graph encoded
115    /// as `encoding` ([`GEOMETRY_FORMAT`] [`GEOMETRY_FORMAT_VERSION`]).
116    ///
117    /// A product whose placement, lowering or encoding is refused is a
118    /// record with a typed refusal. Refused as a whole only as
119    /// [`Self::product_placements`] is, and with `feature-disabled` without
120    /// the `graph` feature.
121    pub fn product_geometry(
122        &self,
123        products: Option<&[u64]>,
124        encoding: GeometryEncoding,
125    ) -> Result<Vec<ProductGeometry>, BindingError> {
126        #[cfg(feature = "graph")]
127        {
128            graphs(self, products, encoding)
129        }
130        #[cfg(not(feature = "graph"))]
131        {
132            let _ = (products, encoding);
133            Err(BindingError::FeatureDisabled("graph"))
134        }
135    }
136}
137
138#[cfg(feature = "graph")]
139fn graphs(
140    model: &IfcModel,
141    products: Option<&[u64]>,
142    encoding: GeometryEncoding,
143) -> Result<Vec<ProductGeometry>, BindingError> {
144    let products = ids(products);
145    let mut out = Vec::new();
146    for (product, graph) in ifc::product_graphs(&model.inner, products.as_deref()) {
147        let (global_id, type_name) = product_identity(model, product.0)?;
148        let mut record = ProductGeometry {
149            id: product.0,
150            global_id,
151            type_name,
152            transform: None,
153            encoding,
154            payload: None,
155            refusal: None,
156        };
157        match graph {
158            Ok(lowered) => {
159                let payload = lowered.graph.as_ref().map(|g| encode(g, encoding));
160                match payload.transpose() {
161                    Ok(payload) => {
162                        record.transform = Some(ifc::column_major(&lowered.world));
163                        record.payload = payload;
164                    }
165                    Err(error) => record.refusal = Some(wire_refusal(product.0, &error)),
166                }
167            }
168            Err(error) => record.refusal = Some(refusal(&error)),
169        }
170        out.push(record);
171    }
172    Ok(out)
173}
174
175#[cfg(feature = "graph")]
176fn encode(
177    graph: &ifc::geometry::GeometryGraph,
178    encoding: GeometryEncoding,
179) -> Result<Vec<u8>, ifc::geometry::wire::WireError> {
180    match encoding {
181        GeometryEncoding::Json => graph.to_json().map(String::into_bytes),
182        GeometryEncoding::Cbor => graph.to_cbor(),
183    }
184}
185
186/// A graph the wire writer refuses: in practice a non-finite number the
187/// file stated, which neither encoding carries. The file's fault.
188#[cfg(feature = "graph")]
189fn wire_refusal(product: u64, error: &ifc::geometry::wire::WireError) -> GeometryRefusal {
190    GeometryRefusal {
191        code: "invalid-model".to_owned(),
192        entity: Some(product),
193        message: format!("the geometry graph cannot be written: {error}"),
194    }
195}
196
197/// The record's metadata: the payload crosses separately, as a string or
198/// a byte array in each host's idiom, never inside the record.
199impl ToRecord for ProductGeometry {
200    fn to_record(&self) -> Record {
201        Record::new(
202            "ProductGeometry",
203            vec![
204                ("id", Field::Id(self.id)),
205                ("global_id", Field::text(self.global_id.clone())),
206                ("type_name", Field::Text(self.type_name.clone())),
207                ("transform", super::matrix(self.transform.as_ref())),
208                ("encoding", Field::Text(self.encoding.name().to_owned())),
209                (
210                    "payload_size",
211                    Field::Count(self.payload.as_ref().map_or(0, Vec::len)),
212                ),
213                ("refusal", Field::record(self.refusal.as_ref())),
214            ],
215        )
216    }
217}
218
219#[cfg(all(test, feature = "graph"))]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn the_constants_are_the_wire_formats() {
225        use ifc::geometry::wire::{FORMAT_NAME, FORMAT_VERSION};
226        assert_eq!(GEOMETRY_FORMAT, FORMAT_NAME);
227        assert_eq!(GEOMETRY_FORMAT_VERSION, FORMAT_VERSION.to_string());
228    }
229}