openbim_ifc_capi/geometry.rs
1//! Geometry (#328, ADR 0021): placements as a record tape, meshes as a
2//! handle to a compiled set whose arrays the caller copies out.
3//!
4//! Compiling meshes is the expensive step, and the C protocol sizes every
5//! buffer with a first call, so meshes are compiled once into an opaque
6//! set ([`OpenbimIfcMeshes`], a non-zero `u64` like a model handle) that the
7//! host reads record by record and array by array, then destroys. The set
8//! owns its data: it stays valid after the model changes or is destroyed.
9
10use openbim_ifc_binding_core::record::to_records;
11use openbim_ifc_binding_core::value::Tagged;
12use openbim_ifc_binding_core::{ProductMesh, ToRecord};
13
14use crate::buffer::{fill, put, slice, text};
15use crate::domains::{list_export, Out};
16use crate::model::{with_model, OpenbimIfcModel};
17use crate::registry;
18use crate::status::{boundary, OpenbimIfcStatus};
19use crate::tape::OpenbimIfcValueNode;
20
21/// Opaque handle to a compiled mesh set. Zero is never a valid handle.
22pub type OpenbimIfcMeshes = u64;
23
24/// An id selection: null with `id_count` 0 is the call's default (every
25/// product with a shape, every object definition); otherwise `id_count`
26/// ids.
27///
28/// # Safety
29/// `ids`, if non-null, valid for `id_count` reads.
30pub(crate) unsafe fn selection<'a>(
31 ids: *const u64,
32 id_count: usize,
33) -> Result<Option<&'a [u64]>, OpenbimIfcStatus> {
34 if ids.is_null() {
35 return if id_count == 0 {
36 Ok(None)
37 } else {
38 Err(OpenbimIfcStatus::NullPointer)
39 };
40 }
41 // SAFETY: forwarded caller contract.
42 unsafe { slice(ids, id_count) }.map(Some)
43}
44
45/// Each product's world placement and selected Body representation, for
46/// `ids` (`id_count` of them) or, with `ids` null and `id_count` 0, every
47/// product with a shape, in id order. The tape is a `LIST` of
48/// `ProductPlacement` records; `out_count` gets their number.
49/// `ProductPlacement`: id (`REF`), global id, type name, transform (`LIST`
50/// of 16 `REAL`s, a column-major 4x4 in metres, or `NULL`), representation
51/// (`SelectedRepresentation` or `NULL`), refusal (`GeometryRefusal` or
52/// `NULL`). `SelectedRepresentation`: id, identifier, representation type,
53/// context (`REF` or `NULL`), context type, context identifier, target
54/// view. `GeometryRefusal`: code (`unsupported`, `invalid-model`,
55/// `missing-reference` or `budget-exceeded`), entity (`REF` or `NULL`),
56/// message.
57///
58/// A product that cannot be placed is a record with a refusal, not a
59/// failed call. `UnsupportedSchema`, `FeatureDisabled`.
60///
61/// # Safety
62/// `ids` valid for `id_count` reads when non-null; `out_count` valid for
63/// one write; otherwise as for `openbim_ifc_v0_1_entity_attribute`.
64#[no_mangle]
65pub unsafe extern "C" fn openbim_ifc_v0_1_model_product_placements(
66 model: OpenbimIfcModel,
67 ids: *const u64,
68 id_count: usize,
69 out_count: *mut usize,
70 nodes: *mut OpenbimIfcValueNode,
71 node_capacity: usize,
72 out_nodes_required: *mut usize,
73 strings: *mut u8,
74 string_capacity: usize,
75 out_strings_required: *mut usize,
76) -> OpenbimIfcStatus {
77 // SAFETY: caller contract above.
78 let ids = match unsafe { selection(ids, id_count) } {
79 Ok(ids) => ids,
80 Err(status) => return status,
81 };
82 let out = Out {
83 nodes,
84 node_capacity,
85 out_nodes_required,
86 strings,
87 string_capacity,
88 out_strings_required,
89 };
90 // SAFETY: caller contract above.
91 unsafe {
92 list_export(model, out_count, out, |m| {
93 Ok(to_records(&m.product_placements(ids)?))
94 })
95 }
96}
97
98/// Compile the Body mesh of each of `ids` (`id_count` of them) or, with
99/// `ids` null and `id_count` 0, of every product with a shape, and write
100/// the new set's handle to `out_meshes`. Read it with
101/// `openbim_ifc_v0_1_meshes_records`, `_meshes_positions` and
102/// `_meshes_indices`; destroy it with `openbim_ifc_v0_1_meshes_destroy`.
103///
104/// A product that cannot be meshed is a record with a refusal, not a
105/// failed call. `UnsupportedSchema`; `FeatureDisabled` in a library built
106/// without the `mesh` feature (the default build).
107///
108/// # Safety
109/// `ids` valid for `id_count` reads when non-null; `out_meshes` valid for
110/// one write.
111#[no_mangle]
112pub unsafe extern "C" fn openbim_ifc_v0_1_model_product_meshes(
113 model: OpenbimIfcModel,
114 ids: *const u64,
115 id_count: usize,
116 out_meshes: *mut OpenbimIfcMeshes,
117) -> OpenbimIfcStatus {
118 boundary(|| {
119 if out_meshes.is_null() {
120 return OpenbimIfcStatus::NullPointer;
121 }
122 // SAFETY: caller contract above.
123 let ids = match unsafe { selection(ids, id_count) } {
124 Ok(ids) => ids,
125 Err(status) => return status,
126 };
127 with_model(model, |m| {
128 let handle = registry::insert_meshes(m.product_meshes(ids)?);
129 // SAFETY: checked non-null; caller contract above.
130 Ok(unsafe { put(out_meshes, handle) }
131 .err()
132 .unwrap_or(OpenbimIfcStatus::Ok))
133 })
134 })
135}
136
137/// As [`openbim_ifc_v0_1_model_product_meshes`], meshing each product's
138/// `representation` (#458): `representation_len` bytes of UTF-8 at
139/// `representation`, one of `Body` (as the call above), `Plan`, `Axis`,
140/// `FootPrint`, `Annotation`, `Surface` or `Reference`. Its surfaces and solids are one
141/// mesh, whose record's closure says `solid` or `surface`; its curves are
142/// left to `openbim_ifc_v0_1_model_product_curves`. A product without the
143/// representation, or with curves only, has an empty mesh and no refusal.
144/// Only a Body mesh carries a colour.
145///
146/// `InvalidValue` for another name, `InvalidArgument` for text that is not
147/// UTF-8; otherwise as the call above.
148///
149/// # Safety
150/// `representation` valid for `representation_len` reads; otherwise as
151/// for `openbim_ifc_v0_1_model_product_meshes`.
152#[no_mangle]
153pub unsafe extern "C" fn openbim_ifc_v0_1_model_product_meshes_for(
154 model: OpenbimIfcModel,
155 ids: *const u64,
156 id_count: usize,
157 representation: *const u8,
158 representation_len: usize,
159 out_meshes: *mut OpenbimIfcMeshes,
160) -> OpenbimIfcStatus {
161 boundary(|| {
162 if out_meshes.is_null() {
163 return OpenbimIfcStatus::NullPointer;
164 }
165 // SAFETY: caller contract above.
166 let inputs = unsafe {
167 (
168 selection(ids, id_count),
169 text(representation, representation_len),
170 )
171 };
172 let (ids, representation) = match inputs {
173 (Ok(ids), Ok(representation)) => (ids, representation),
174 (Err(status), _) | (_, Err(status)) => return status,
175 };
176 with_model(model, |m| {
177 let handle = registry::insert_meshes(m.product_meshes_for(ids, representation)?);
178 // SAFETY: checked non-null; caller contract above.
179 Ok(unsafe { put(out_meshes, handle) }
180 .err()
181 .unwrap_or(OpenbimIfcStatus::Ok))
182 })
183 })
184}
185
186/// Run `read` on the live set behind `meshes`.
187fn with_meshes(
188 meshes: OpenbimIfcMeshes,
189 read: impl FnOnce(&[ProductMesh]) -> OpenbimIfcStatus,
190) -> OpenbimIfcStatus {
191 boundary(|| match registry::meshes(meshes) {
192 Some(set) => read(&set),
193 None => OpenbimIfcStatus::InvalidHandle,
194 })
195}
196
197/// The set's `ProductMesh` records as a tape, in the order compiled;
198/// `out_count` gets their number. `ProductMesh`: id (`REF`), global id,
199/// type name, transform (`LIST` of 16 `REAL`s, column-major, metres, or
200/// `NULL`), vertex count, triangle count (`INTEGER`s), refusal
201/// (`GeometryRefusal` or `NULL`), colour (`SurfaceColour` or `NULL`),
202/// colour refusal (`GeometryRefusal` or `NULL`), closure (`TEXT`, #458:
203/// `solid`, `surface` for an area with no volume, or `unknown` for an
204/// empty or refused mesh). Empty arrays and no refusal is a product with no
205/// Body representation.
206///
207/// `SurfaceColour` (#449): red, green, blue (`REAL`s in [0, 1]),
208/// transparency (`REAL`, 0 opaque, or `NULL` when the file states none),
209/// source (`item`, `layer`, `material` or `materialSet`, in that
210/// precedence), source entity (`REF`: the `IfcStyledItem`, the layer
211/// assignment, the `IfcMaterial` or, for `materialSet`, the material set,
212/// list or usage), surface style (`REF`), source materials (`LIST` of `REF`,
213/// last: for `materialSet` the materials of the set that colour the item,
214/// every one or the constituents its shape aspects name, ascending and
215/// distinct, else empty; #603). The colour is the one the Body's
216/// items agree on, `NULL` when nothing colours the product; the colour
217/// refusal's code is `ambiguous` (two styled items or colours at one
218/// level, a layer or profile set of several materials, a constituent set
219/// no shape aspect resolves, or Body items of different colours) or a
220/// shared geometry code, and never refuses the mesh.
221///
222/// # Safety
223/// `out_count` valid for one write; otherwise as for
224/// `openbim_ifc_v0_1_entity_attribute`.
225#[no_mangle]
226pub unsafe extern "C" fn openbim_ifc_v0_1_meshes_records(
227 meshes: OpenbimIfcMeshes,
228 out_count: *mut usize,
229 nodes: *mut OpenbimIfcValueNode,
230 node_capacity: usize,
231 out_nodes_required: *mut usize,
232 strings: *mut u8,
233 string_capacity: usize,
234 out_strings_required: *mut usize,
235) -> OpenbimIfcStatus {
236 let out = Out {
237 nodes,
238 node_capacity,
239 out_nodes_required,
240 strings,
241 string_capacity,
242 out_strings_required,
243 };
244 with_meshes(meshes, |set| {
245 // SAFETY: caller contract above.
246 if let Err(status) = unsafe { put(out_count, set.len()) } {
247 return status;
248 }
249 let tape = Tagged::List(
250 set.iter()
251 .map(|mesh| mesh.to_record().to_tagged())
252 .collect(),
253 );
254 // SAFETY: caller contract above.
255 unsafe { out.write(&tape) }.unwrap_or_else(|error| OpenbimIfcStatus::from(&error))
256 })
257}
258
259/// Copy the positions of mesh `index` -- `x, y, z` per vertex, metres,
260/// relative to its record's transform -- into `buffer` (`capacity`
261/// floats), after writing the count needed (3 x vertex count) to
262/// `out_required`. `OutOfRange` for an index past the set.
263///
264/// # Safety
265/// As for the other buffer calls: `buffer` valid for `capacity` writes
266/// when non-null, `out_required` for one.
267#[no_mangle]
268pub unsafe extern "C" fn openbim_ifc_v0_1_meshes_positions(
269 meshes: OpenbimIfcMeshes,
270 index: usize,
271 buffer: *mut f32,
272 capacity: usize,
273 out_required: *mut usize,
274) -> OpenbimIfcStatus {
275 with_meshes(meshes, |set| match set.get(index) {
276 // SAFETY: caller contract above.
277 Some(mesh) => unsafe { fill(&mesh.positions, buffer, capacity, out_required) },
278 None => OpenbimIfcStatus::OutOfRange,
279 })
280}
281
282/// Copy the triangle indices of mesh `index` -- three vertex indices per
283/// triangle -- into `buffer` (`capacity` values), after writing the count
284/// needed (3 x triangle count) to `out_required`. `OutOfRange` for an
285/// index past the set.
286///
287/// # Safety
288/// As for `openbim_ifc_v0_1_meshes_positions`.
289#[no_mangle]
290pub unsafe extern "C" fn openbim_ifc_v0_1_meshes_indices(
291 meshes: OpenbimIfcMeshes,
292 index: usize,
293 buffer: *mut u32,
294 capacity: usize,
295 out_required: *mut usize,
296) -> OpenbimIfcStatus {
297 with_meshes(meshes, |set| match set.get(index) {
298 // SAFETY: caller contract above.
299 Some(mesh) => unsafe { fill(&mesh.indices, buffer, capacity, out_required) },
300 None => OpenbimIfcStatus::OutOfRange,
301 })
302}
303
304/// Destroy a mesh set. A stale or repeated handle is `InvalidHandle`.
305#[no_mangle]
306pub extern "C" fn openbim_ifc_v0_1_meshes_destroy(meshes: OpenbimIfcMeshes) -> OpenbimIfcStatus {
307 boundary(|| {
308 if registry::remove_meshes(meshes) {
309 OpenbimIfcStatus::Ok
310 } else {
311 OpenbimIfcStatus::InvalidHandle
312 }
313 })
314}