Skip to main content

openbim_ifc_capi/
graph.rs

1//! Geometry, Level 2 (#367, ADR 0021): each product's Body as Axiolid's
2//! neutral geometry graph, in Axiolid's versioned wire format (1.0 to 1.5).
3//!
4//! As for meshes, lowering and encoding are the expensive step and the C
5//! protocol sizes every buffer with a first call, so the graphs are
6//! encoded once into an opaque set ([`OpenbimIfcGraphs`], a non-zero `u64`
7//! like a model handle) that the host reads record by record and payload
8//! by payload, then destroys. The set owns its data: it stays valid after
9//! the model changes or is destroyed.
10
11use openbim_ifc_binding_core::value::Tagged;
12use openbim_ifc_binding_core::{GeometryEncoding, ProductGeometry, ToRecord};
13
14use crate::buffer::{fill, put};
15use crate::domains::Out;
16use crate::geometry::selection;
17use crate::model::{with_model, OpenbimIfcModel};
18use crate::registry;
19use crate::status::{boundary, OpenbimIfcStatus};
20use crate::tape::OpenbimIfcValueNode;
21
22/// Opaque handle to an encoded graph set. Zero is never a valid handle.
23pub type OpenbimIfcGraphs = u64;
24
25/// `encoding` for `openbim_ifc_v0_1_model_product_geometry`: JSON text
26/// (RFC 8259), UTF-8, not NUL-terminated.
27pub const OPENBIM_IFC_GEOMETRY_JSON: u32 = 0;
28/// `encoding` for `openbim_ifc_v0_1_model_product_geometry`: CBOR bytes
29/// (RFC 8949).
30pub const OPENBIM_IFC_GEOMETRY_CBOR: u32 = 1;
31
32/// Lower the Body of each of `ids` (`id_count` of them) or, with `ids` null
33/// and `id_count` 0, of every product with a shape, encode each graph in
34/// Axiolid's wire format as `encoding` (`OPENBIM_IFC_GEOMETRY_JSON` or
35/// `_CBOR`), and write the new set's handle to `out_graphs`. Read it with
36/// `openbim_ifc_v0_1_graphs_records` and `_graphs_payload`; destroy it with
37/// `openbim_ifc_v0_1_graphs_destroy`.
38///
39/// The payload is the envelope `{"format":"axiolid-geometry-graph",
40/// "version":"1.0","graph":{"nodes":[...],"roots":[...]}}`, in world
41/// coordinates, metres; its version is the lowest the content needs,
42/// "1.0"; "1.1" when a station carries a seam-snapping window, "1.2" when a run's sections do, "1.3" when an offset run continues to a basis end the kernel measures, "1.4" when a polygonal bounded half-space clips, "1.5" when a graph holds a ruled surface (axiolid/kernel#402). A product that cannot be lowered is a record with
43/// a refusal, not a failed call. `InvalidArgument` for another `encoding`;
44/// `UnsupportedSchema`; `FeatureDisabled` in a library built without the
45/// `graph` feature.
46///
47/// # Safety
48/// `ids` valid for `id_count` reads when non-null; `out_graphs` valid for
49/// one write.
50#[no_mangle]
51pub unsafe extern "C" fn openbim_ifc_v0_1_model_product_geometry(
52    model: OpenbimIfcModel,
53    ids: *const u64,
54    id_count: usize,
55    encoding: u32,
56    out_graphs: *mut OpenbimIfcGraphs,
57) -> OpenbimIfcStatus {
58    boundary(|| {
59        if out_graphs.is_null() {
60            return OpenbimIfcStatus::NullPointer;
61        }
62        let encoding = match encoding {
63            OPENBIM_IFC_GEOMETRY_JSON => GeometryEncoding::Json,
64            OPENBIM_IFC_GEOMETRY_CBOR => GeometryEncoding::Cbor,
65            _ => return OpenbimIfcStatus::InvalidArgument,
66        };
67        // SAFETY: caller contract above.
68        let ids = match unsafe { selection(ids, id_count) } {
69            Ok(ids) => ids,
70            Err(status) => return status,
71        };
72        with_model(model, |m| {
73            let handle = registry::insert_graphs(m.product_geometry(ids, encoding)?);
74            // SAFETY: checked non-null; caller contract above.
75            Ok(unsafe { put(out_graphs, handle) }
76                .err()
77                .unwrap_or(OpenbimIfcStatus::Ok))
78        })
79    })
80}
81
82/// Run `read` on the live set behind `graphs`.
83fn with_graphs(
84    graphs: OpenbimIfcGraphs,
85    read: impl FnOnce(&[ProductGeometry]) -> OpenbimIfcStatus,
86) -> OpenbimIfcStatus {
87    boundary(|| match registry::graphs(graphs) {
88        Some(set) => read(&set),
89        None => OpenbimIfcStatus::InvalidHandle,
90    })
91}
92
93/// The set's `ProductGeometry` records as a tape, in the order lowered;
94/// `out_count` gets their number. `ProductGeometry`: id (`REF`), global
95/// id, type name, transform (`LIST` of 16 `REAL`s, column-major, metres,
96/// already applied to the graph, or `NULL`), encoding (`json` or `cbor`),
97/// payload size (`INTEGER`, bytes), refusal (`GeometryRefusal` or `NULL`).
98/// A payload size of 0 and no refusal is a product with no Body
99/// representation.
100///
101/// # Safety
102/// `out_count` valid for one write; otherwise as for
103/// `openbim_ifc_v0_1_entity_attribute`.
104#[no_mangle]
105pub unsafe extern "C" fn openbim_ifc_v0_1_graphs_records(
106    graphs: OpenbimIfcGraphs,
107    out_count: *mut usize,
108    nodes: *mut OpenbimIfcValueNode,
109    node_capacity: usize,
110    out_nodes_required: *mut usize,
111    strings: *mut u8,
112    string_capacity: usize,
113    out_strings_required: *mut usize,
114) -> OpenbimIfcStatus {
115    let out = Out {
116        nodes,
117        node_capacity,
118        out_nodes_required,
119        strings,
120        string_capacity,
121        out_strings_required,
122    };
123    with_graphs(graphs, |set| {
124        // SAFETY: caller contract above.
125        if let Err(status) = unsafe { put(out_count, set.len()) } {
126            return status;
127        }
128        let tape = Tagged::List(
129            set.iter()
130                .map(|graph| graph.to_record().to_tagged())
131                .collect(),
132        );
133        // SAFETY: caller contract above.
134        unsafe { out.write(&tape) }.unwrap_or_else(|error| OpenbimIfcStatus::from(&error))
135    })
136}
137
138/// Copy the wire payload of graph `index` -- JSON text without a trailing
139/// NUL, or CBOR bytes -- into `buffer` (`capacity` bytes), after writing
140/// the size needed (its record's payload size) to `out_required`; 0 for a
141/// product with no graph. `OutOfRange` for an index past the set.
142///
143/// # Safety
144/// As for the other buffer calls: `buffer` valid for `capacity` writes
145/// when non-null, `out_required` for one.
146#[no_mangle]
147pub unsafe extern "C" fn openbim_ifc_v0_1_graphs_payload(
148    graphs: OpenbimIfcGraphs,
149    index: usize,
150    buffer: *mut u8,
151    capacity: usize,
152    out_required: *mut usize,
153) -> OpenbimIfcStatus {
154    with_graphs(graphs, |set| match set.get(index) {
155        // SAFETY: caller contract above.
156        Some(graph) => unsafe {
157            fill(
158                graph.payload.as_deref().unwrap_or_default(),
159                buffer,
160                capacity,
161                out_required,
162            )
163        },
164        None => OpenbimIfcStatus::OutOfRange,
165    })
166}
167
168/// Destroy a graph set. A stale or repeated handle is `InvalidHandle`.
169#[no_mangle]
170pub extern "C" fn openbim_ifc_v0_1_graphs_destroy(graphs: OpenbimIfcGraphs) -> OpenbimIfcStatus {
171    boundary(|| {
172        if registry::remove_graphs(graphs) {
173            OpenbimIfcStatus::Ok
174        } else {
175            OpenbimIfcStatus::InvalidHandle
176        }
177    })
178}