Skip to main content

cadlib/
cad.rs

1// Code generated for the SimScale cadlib Rust bindings. DO NOT EDIT.
2//! Safe Rust wrapper over the cadlib native library.
3
4use std::{
5    ffi::{CStr, CString},
6    os::raw::{c_char, c_int},
7};
8
9use serde::{de::DeserializeOwned, Serialize};
10
11use crate::{
12    error::{parse_cad_error, CadLibError},
13    ffi,
14    models::{
15        BoundingBoxParameters, BoundingBoxResponse, CenterOfGravityParameters,
16        CenterOfGravityResponse, ColorsParameters, ColorsResponse, DetectCommonRotationParameters,
17        DetectCommonRotationResponse, DetectEnclosureParameters, DetectEnclosureResponse,
18        EntitiesResponse, GenerateComfortMapDiscParameters, GenerateComfortMapDiscResponse,
19        MaterialPointsParameters, MaterialPointsResponse, ModelMetricsParameters,
20        ModelMetricsResponse, PlanarPatchPrimitivesParameters, PlanarPatchPrimitivesResponse,
21        TessellateFacesParameters, TessellateFacesResponse, TessellateParameters,
22        TessellateResponse, VolumeParameters, VolumeResponse,
23    },
24    version_check::check_lib_version,
25};
26
27/// Take ownership of a C string returned by the library: copy it into an owned
28/// `String`, then free the original with `cad_free_string`. `ptr` may be null.
29fn take_c_string(ptr: *mut c_char) -> String {
30    if ptr.is_null() {
31        return String::new();
32    }
33    // SAFETY: `ptr` is a non-null, NUL-terminated string produced by the FFI,
34    // valid until we free it on the next line.
35    let owned = unsafe { CStr::from_ptr(ptr) }
36        .to_string_lossy()
37        .into_owned();
38    // SAFETY: `ptr` was allocated by the library; hand it back to be freed.
39    unsafe { ffi::cad_free_string(ptr) };
40    owned
41}
42
43/// Run an FFI call that signals failure via a non-zero return code and an
44/// out-error string. Returns the decoded error on failure.
45fn with_error_handling(call: impl FnOnce(*mut *mut c_char) -> c_int) -> Result<(), CadLibError> {
46    let mut err: *mut c_char = std::ptr::null_mut();
47    if call(&mut err) != 0 {
48        return Err(parse_cad_error(&take_c_string(err)));
49    }
50    Ok(())
51}
52
53/// Serialize optional parameters to a JSON `CString` (null pointer when `None`).
54fn marshal_params<P: Serialize>(params: Option<&P>) -> Result<Option<CString>, CadLibError> {
55    match params {
56        None => Ok(None),
57        Some(p) => {
58            let json = serde_json::to_string(p).map_err(|e| CadLibError::Unexpected {
59                message: format!("failed to marshal parameters: {e}"),
60            })?;
61            CString::new(json)
62                .map(Some)
63                .map_err(|e| CadLibError::Unexpected {
64                    message: format!("parameters contain an interior NUL byte: {e}"),
65                })
66        }
67    }
68}
69
70/// Run an FFI call producing a JSON result string, then deserialize it.
71fn deserialize_result<R: DeserializeOwned>(
72    call: impl FnOnce(*mut *mut c_char, *mut *mut c_char) -> c_int,
73) -> Result<R, CadLibError> {
74    let mut result: *mut c_char = std::ptr::null_mut();
75    with_error_handling(|e| call(&mut result, e))?;
76    let json = take_c_string(result);
77    serde_json::from_str(&json).map_err(|e| CadLibError::Unexpected {
78        message: format!("failed to unmarshal result: {e}"),
79    })
80}
81
82/// A handle to a loaded CAD model.
83///
84/// Dropping a `Cad` releases the underlying native resources; there is no
85/// explicit close (unlike the Go bindings, which need one). All query methods
86/// are blocking — wrap them in `tokio::task::spawn_blocking` from async code.
87#[derive(Debug)]
88pub struct Cad {
89    handle: *mut ffi::CadHandle,
90}
91
92impl Cad {
93    /// Load a CAD model from the CAD data map entry of a workflow method's run
94    /// request, or anything else serializing to the same shape (a
95    /// `serde_json::Value`, a map, a struct of your own).
96    ///
97    /// Only the entry's `externalReference` is required; `dataType` and
98    /// `source.type` are validated when present and other keys are ignored.
99    ///
100    /// ```ignore
101    /// let cad = Cad::load(&request.data_map.cad)?;
102    /// ```
103    ///
104    /// Raw JSON text has to be parsed first (`serde_json::from_str::<Value>`):
105    /// a `&str` serializes to a JSON string rather than an object, which is
106    /// rejected with `invalid-cad-model-json`.
107    ///
108    /// # Errors
109    ///
110    /// Returns [`CadLibError::Expected`] when the entry is rejected (no or
111    /// malformed reference, an unsupported data type or source) and
112    /// [`CadLibError::Unexpected`] when the entry cannot be serialized, contains
113    /// an interior NUL byte, or the native library is incompatible with these
114    /// bindings. The error codes it can return are listed in
115    /// <https://github.com/SimScaleGmbH/simscale-rust-cadlib/blob/main/ERRORS.md>.
116    pub fn load<T: Serialize + ?Sized>(entry: &T) -> Result<Self, CadLibError> {
117        check_lib_version().map_err(|message| CadLibError::Unexpected { message })?;
118
119        let cad_model = serde_json::to_string(entry).map_err(|e| CadLibError::Unexpected {
120            message: format!("failed to marshal the cad data map entry: {e}"),
121        })?;
122
123        let c_model = CString::new(cad_model).map_err(|e| CadLibError::Unexpected {
124            message: format!("cad data map entry contains an interior NUL byte: {e}"),
125        })?;
126
127        let mut handle: *mut ffi::CadHandle = std::ptr::null_mut();
128        with_error_handling(|e|
129            // SAFETY: `c_model` is a valid NUL-terminated string; `handle` is a
130            // valid out-pointer the FFI writes on success.
131            unsafe { ffi::cad_load(c_model.as_ptr(), &mut handle, e) })?;
132
133        Ok(Self { handle })
134    }
135}
136
137impl Drop for Cad {
138    fn drop(&mut self) {
139        if !self.handle.is_null() {
140            // SAFETY: `handle` came from `cad_load` and has not been freed yet.
141            unsafe { ffi::cad_destroy(self.handle) };
142            self.handle = std::ptr::null_mut();
143        }
144    }
145}
146
147// `Cad` is `Send` but deliberately not `Sync`: a handle may be *moved* between
148// threads (e.g. into `tokio::task::spawn_blocking`), which the native library
149// tolerates. It is not `Sync` because the query methods take `&self` and the
150// native state is not safe to call concurrently through a shared reference.
151// SAFETY: the library keeps no thread-affine state tied to a handle.
152unsafe impl Send for Cad {}
153
154// ============================================================================
155// Generated query methods
156// ============================================================================
157
158impl Cad {
159    /// Tessellates the model and writes the STL files into a directory.
160    ///
161    /// One STL file is written per region by default, or one per face when
162    /// ``write_one_file_per_face`` is set. The directory is created if it does not
163    /// exist, and files in it with the same names are overwritten.
164    ///
165    /// ``tessellation_type``, ``max_facet_width`` and ``allowed_facet_faults_level``
166    /// apply to Parasolid models, and ``tessellation_type`` has to be set explicitly;
167    /// ``feature_size``, ``adaptivity`` and ``max_edge_length`` apply to nTop models
168    /// and all default when omitted. ``tess_surface_area`` is set in the response
169    /// only when ``calculate_area`` is requested.
170    ///
171    /// Supported for Parasolid, STL and nTop models.
172    ///
173    /// # Errors
174    ///
175    /// Returns [`CadLibError::Expected`] for a known domain error and
176    /// [`CadLibError::Unexpected`] if `dest_dir` contains an interior NUL byte,
177    /// the parameters cannot be serialized, or the library fails internally.
178    ///
179    /// # Query errors
180    ///
181    /// * `tessellation-has-error[-with-entity]` - The kernel could not tessellate one or more entities.
182    /// * `tessellation-ntop-negative-adaptivity` - `adaptivity` is negative.
183    /// * `tessellation-ntop-zero-edge-length` - `max_edge_length` is zero.
184    /// * `tessellation-ntop-zero-feature-size` - `feature_size` is zero.
185    /// * `tessellation-too-large` - The result could not be written; the kernel ran out of disk space.
186    pub fn tessellate(
187        &self,
188        dest_dir: &str,
189        params: Option<&TessellateParameters>,
190    ) -> Result<TessellateResponse, CadLibError> {
191        let c_dest = CString::new(dest_dir).map_err(|e| CadLibError::Unexpected {
192            message: format!("dest_dir contains an interior NUL byte: {e}"),
193        })?;
194        let params_json = marshal_params(params)?;
195        let params_ptr = params_json
196            .as_ref()
197            .map_or(std::ptr::null(), |c| c.as_ptr());
198        deserialize_result(|r, e|
199            // SAFETY: `self.handle` is a live handle; `c_dest`/`params_ptr` are
200            // valid (or null) NUL-terminated strings; `r`/`e` are out-pointers.
201            unsafe { ffi::cad_tessellate(self.handle, c_dest.as_ptr(), params_ptr, r, e) })
202    }
203
204    /// Tessellates the requested faces, writing one STL file per face into a directory.
205    ///
206    /// Each requested face is tessellated into its own STL file, named after the
207    /// face id; a face requested more than once is tessellated only once. The
208    /// response additionally carries the normal of each face, evaluated at the
209    /// mid point of the face.
210    ///
211    /// The faces to tessellate are required, so a query without parameters is
212    /// rejected. The directory is created if it does not exist, and files in it with
213    /// the same names are overwritten.
214    ///
215    /// Supported only for Parasolid models. Other formats fail with
216    /// ``query-type-unsupported-for-cad-format``.
217    ///
218    /// # Errors
219    ///
220    /// Returns [`CadLibError::Expected`] for a known domain error and
221    /// [`CadLibError::Unexpected`] if `dest_dir` contains an interior NUL byte,
222    /// the parameters cannot be serialized, or the library fails internally.
223    ///
224    /// # Query errors
225    ///
226    /// * `tessellation-has-error` - The kernel could not tessellate one of the faces.
227    pub fn tessellate_faces(
228        &self,
229        dest_dir: &str,
230        params: Option<&TessellateFacesParameters>,
231    ) -> Result<TessellateFacesResponse, CadLibError> {
232        let c_dest = CString::new(dest_dir).map_err(|e| CadLibError::Unexpected {
233            message: format!("dest_dir contains an interior NUL byte: {e}"),
234        })?;
235        let params_json = marshal_params(params)?;
236        let params_ptr = params_json
237            .as_ref()
238            .map_or(std::ptr::null(), |c| c.as_ptr());
239        deserialize_result(|r, e|
240            // SAFETY: `self.handle` is a live handle; `c_dest`/`params_ptr` are
241            // valid (or null) NUL-terminated strings; `r`/`e` are out-pointers.
242            unsafe { ffi::cad_tessellate_faces(self.handle, c_dest.as_ptr(), params_ptr, r, e) })
243    }
244
245    /// Generates the comfort-map disc and writes the STL result into a directory.
246    ///
247    /// The disc is a tessellated surface covering a region of interest: a circle of
248    /// radius ``floor_radius`` around ``center``, placed ``height`` above the ground.
249    /// ``fineness`` controls how finely it is tessellated.
250    ///
251    /// By default the disc is written as a single file. Asking for one of the zipped
252    /// encodings in ``result_encoding`` unpacks the result into the directory instead.
253    /// The directory is created if it does not exist, and files in it with
254    /// the same names are overwritten.
255    ///
256    /// A disc with no geometry is reported as ``empty-comfort-map-disc``.
257    ///
258    /// Supported for Parasolid and STL models. Other formats fail with
259    /// ``query-type-unsupported-for-cad-format``.
260    ///
261    /// # Errors
262    ///
263    /// Returns [`CadLibError::Expected`] for a known domain error and
264    /// [`CadLibError::Unexpected`] if `dest_dir` contains an interior NUL byte,
265    /// the parameters cannot be serialized, or the library fails internally.
266    ///
267    /// # Query errors
268    ///
269    /// * `empty-comfort-map-disc` - The query returned no geometry.
270    /// * `lawson-cylinder-exceeds-size-box` - `floor_radius` is too large for the model's size box.
271    /// * `lawson-negative-height-above-ground` - `height` is negative.
272    /// * `lawson-roi-radius-must-be-positive` - `floor_radius` is zero or negative.
273    /// * `lawson-tessellation-max-width-must-be-positive` - `fineness` is zero or negative.
274    /// * `lawson-tessellation-too-fine` - `fineness` produces more than 100 million triangles, which the query does not allow.
275    /// * `tessellation-has-error[-with-entity]` - The kernel could not tessellate one or more entities.
276    /// * `tessellation-too-large` - The result could not be written; the kernel ran out of disk space.
277    pub fn generate_comfort_map_disc(
278        &self,
279        dest_dir: &str,
280        params: Option<&GenerateComfortMapDiscParameters>,
281    ) -> Result<GenerateComfortMapDiscResponse, CadLibError> {
282        let c_dest = CString::new(dest_dir).map_err(|e| CadLibError::Unexpected {
283            message: format!("dest_dir contains an interior NUL byte: {e}"),
284        })?;
285        let params_json = marshal_params(params)?;
286        let params_ptr = params_json
287            .as_ref()
288            .map_or(std::ptr::null(), |c| c.as_ptr());
289        deserialize_result(|r, e|
290            // SAFETY: `self.handle` is a live handle; `c_dest`/`params_ptr` are
291            // valid (or null) NUL-terminated strings; `r`/`e` are out-pointers.
292            unsafe { ffi::cad_generate_comfort_map_disc(self.handle, c_dest.as_ptr(), params_ptr, r, e) })
293    }
294
295    /// Computes the volume of each selected solid, and their total.
296    ///
297    /// The solids and sheets to measure are given by their entity ids, as
298    /// ``entities`` returns them.
299    ///
300    /// ``volumes`` holds one entry per measured entity, keyed by its entity id,
301    /// and ``total`` is their sum.
302    ///
303    /// Supported for Parasolid and nTop models. Other formats fail with
304    /// ``query-type-unsupported-for-cad-format``.
305    ///
306    /// # Errors
307    ///
308    /// Returns [`CadLibError::Expected`] for a known domain error and
309    /// [`CadLibError::Unexpected`] if the parameters cannot be serialized or the
310    /// library fails internally.
311    pub fn volume(&self, params: Option<&VolumeParameters>) -> Result<VolumeResponse, CadLibError> {
312        let params_json = marshal_params(params)?;
313        let params_ptr = params_json
314            .as_ref()
315            .map_or(std::ptr::null(), |c| c.as_ptr());
316        deserialize_result(|r, e|
317            // SAFETY: `self.handle` is a live handle; `params_ptr` is null or a
318            // valid NUL-terminated JSON string; `r`/`e` are valid out-pointers.
319            unsafe { ffi::cad_volume(self.handle, params_ptr, r, e) })
320    }
321
322    /// Computes the bounding box of the model, of each body, and of any faces given.
323    ///
324    /// The box of the whole model and one box per solid and sheet are always
325    /// returned. Naming faces additionally returns one box per face, keyed by
326    /// face id, and a single box enclosing all of them.
327    ///
328    /// Supported for Parasolid and nTop models. Other formats fail with
329    /// ``query-type-unsupported-for-cad-format``.
330    ///
331    /// # Errors
332    ///
333    /// Returns [`CadLibError::Expected`] for a known domain error and
334    /// [`CadLibError::Unexpected`] if the parameters cannot be serialized or the
335    /// library fails internally.
336    pub fn bounding_box(
337        &self,
338        params: Option<&BoundingBoxParameters>,
339    ) -> Result<BoundingBoxResponse, CadLibError> {
340        let params_json = marshal_params(params)?;
341        let params_ptr = params_json
342            .as_ref()
343            .map_or(std::ptr::null(), |c| c.as_ptr());
344        deserialize_result(|r, e|
345            // SAFETY: `self.handle` is a live handle; `params_ptr` is null or a
346            // valid NUL-terminated JSON string; `r`/`e` are valid out-pointers.
347            unsafe { ffi::cad_bounding_box(self.handle, params_ptr, r, e) })
348    }
349
350    /// Computes the center of gravity of the given faces and edges.
351    ///
352    /// The selection accepts faces and edges only; any other entity type fails
353    /// the query. One center of gravity is computed for the selection as a
354    /// whole, not one per selected entity.
355    ///
356    /// Supported only for Parasolid models. Other formats fail with
357    /// ``query-type-unsupported-for-cad-format``.
358    ///
359    /// # Errors
360    ///
361    /// Returns [`CadLibError::Expected`] for a known domain error and
362    /// [`CadLibError::Unexpected`] if the parameters cannot be serialized or the
363    /// library fails internally.
364    ///
365    /// # Query errors
366    ///
367    /// * `compute-cog-entity-not-supported` - A selected entity has unsupported type, it is neither a face nor an edge.
368    pub fn center_of_gravity(
369        &self,
370        params: Option<&CenterOfGravityParameters>,
371    ) -> Result<CenterOfGravityResponse, CadLibError> {
372        let params_json = marshal_params(params)?;
373        let params_ptr = params_json
374            .as_ref()
375            .map_or(std::ptr::null(), |c| c.as_ptr());
376        deserialize_result(|r, e|
377            // SAFETY: `self.handle` is a live handle; `params_ptr` is null or a
378            // valid NUL-terminated JSON string; `r`/`e` are valid out-pointers.
379            unsafe { ffi::cad_center_of_gravity(self.handle, params_ptr, r, e) })
380    }
381
382    /// Finds the solids that enclose a given point.
383    ///
384    /// The response holds the id of every solid that contains it.
385    ///
386    /// Supported only for Parasolid models. Other model formats fail with
387    /// ``query-type-unsupported-for-cad-format``.
388    ///
389    /// # Errors
390    ///
391    /// Returns [`CadLibError::Expected`] for a known domain error and
392    /// [`CadLibError::Unexpected`] if the parameters cannot be serialized or the
393    /// library fails internally.
394    pub fn detect_enclosure(
395        &self,
396        params: Option<&DetectEnclosureParameters>,
397    ) -> Result<DetectEnclosureResponse, CadLibError> {
398        let params_json = marshal_params(params)?;
399        let params_ptr = params_json
400            .as_ref()
401            .map_or(std::ptr::null(), |c| c.as_ptr());
402        deserialize_result(|r, e|
403            // SAFETY: `self.handle` is a live handle; `params_ptr` is null or a
404            // valid NUL-terminated JSON string; `r`/`e` are valid out-pointers.
405            unsafe { ffi::cad_detect_enclosure(self.handle, params_ptr, r, e) })
406    }
407
408    /// Detects the rotation axis and center shared by the given faces.
409    ///
410    /// All the given faces must be rotationally aligned about a single axis; the
411    /// query fails if they are not, or if no axis can be determined. The response
412    /// gives the direction of that axis and a point on it.
413    ///
414    /// Supported only for Parasolid models. Other formats fail with
415    /// ``query-type-unsupported-for-cad-format``.
416    ///
417    /// # Errors
418    ///
419    /// Returns [`CadLibError::Expected`] for a known domain error and
420    /// [`CadLibError::Unexpected`] if the parameters cannot be serialized or the
421    /// library fails internally.
422    ///
423    /// # Query errors
424    ///
425    /// * `detect-rotation-axis-not-consistent-for-all-faces` - The selected faces do not share the same rotation axis.
426    /// * `detect-rotation-could-not-detect-axis` - No rotation axis could be detected for the selected faces.
427    /// * `detect-rotation-flat-faces-selected[-with-entity]` - The selection contains flat faces, which have no rotation axis.
428    /// * `detect-rotation-multiple-possible-directions` - More than one rotation direction fits the selected faces.
429    pub fn detect_common_rotation(
430        &self,
431        params: Option<&DetectCommonRotationParameters>,
432    ) -> Result<DetectCommonRotationResponse, CadLibError> {
433        let params_json = marshal_params(params)?;
434        let params_ptr = params_json
435            .as_ref()
436            .map_or(std::ptr::null(), |c| c.as_ptr());
437        deserialize_result(|r, e|
438            // SAFETY: `self.handle` is a live handle; `params_ptr` is null or a
439            // valid NUL-terminated JSON string; `r`/`e` are valid out-pointers.
440            unsafe { ffi::cad_detect_common_rotation(self.handle, params_ptr, r, e) })
441    }
442
443    /// Returns the colors defined on the model's solids and sheets.
444    ///
445    /// The query takes no parameters and covers the whole model. Each entry names
446    /// the entity the color is defined on and the color itself, as a hex string
447    /// such as ``#ff0000``.
448    ///
449    /// Supported for Parasolid and nTop models. Other formats fail with
450    /// ``query-type-unsupported-for-cad-format``.
451    ///
452    /// # Errors
453    ///
454    /// Returns [`CadLibError::Expected`] for a known domain error and
455    /// [`CadLibError::Unexpected`] if the parameters cannot be serialized or the
456    /// library fails internally.
457    pub fn colors(&self, params: Option<&ColorsParameters>) -> Result<ColorsResponse, CadLibError> {
458        let params_json = marshal_params(params)?;
459        let params_ptr = params_json
460            .as_ref()
461            .map_or(std::ptr::null(), |c| c.as_ptr());
462        deserialize_result(|r, e|
463            // SAFETY: `self.handle` is a live handle; `params_ptr` is null or a
464            // valid NUL-terminated JSON string; `r`/`e` are valid out-pointers.
465            unsafe { ffi::cad_colors(self.handle, params_ptr, r, e) })
466    }
467
468    /// Computes a point inside the material, for the whole model or for each solid.
469    ///
470    /// ``query_type`` chooses between the two. The response sets the field that
471    /// matches it and leaves the other unset; the per-body field is keyed by
472    /// entity id.
473    ///
474    /// A material point is only guaranteed to lie inside the material. Which
475    /// interior point is returned is unspecified, and can differ between runs.
476    ///
477    /// Supported only for Parasolid models. Other formats fail with
478    /// ``query-type-unsupported-for-cad-format``.
479    ///
480    /// # Errors
481    ///
482    /// Returns [`CadLibError::Expected`] for a known domain error and
483    /// [`CadLibError::Unexpected`] if the parameters cannot be serialized or the
484    /// library fails internally.
485    pub fn material_points(
486        &self,
487        params: Option<&MaterialPointsParameters>,
488    ) -> Result<MaterialPointsResponse, CadLibError> {
489        let params_json = marshal_params(params)?;
490        let params_ptr = params_json
491            .as_ref()
492            .map_or(std::ptr::null(), |c| c.as_ptr());
493        deserialize_result(|r, e|
494            // SAFETY: `self.handle` is a live handle; `params_ptr` is null or a
495            // valid NUL-terminated JSON string; `r`/`e` are valid out-pointers.
496            unsafe { ffi::cad_material_points(self.handle, params_ptr, r, e) })
497    }
498
499    /// Approximates groups of coplanar faces with a circle or rectangle primitive.
500    ///
501    /// Groups the requested faces into patches of adjacent, coplanar faces and
502    /// approximates each patch with the primitive — a circle or a rectangle — whose
503    /// area is closest to the area of the patch. All faces of a patch belong to the
504    /// same occurrence. The query fails if any of the requested faces is not planar.
505    ///
506    /// Supported only for Parasolid models. Other formats fail with
507    /// ``query-type-unsupported-for-cad-format``.
508    ///
509    /// # Errors
510    ///
511    /// Returns [`CadLibError::Expected`] for a known domain error and
512    /// [`CadLibError::Unexpected`] if the parameters cannot be serialized or the
513    /// library fails internally.
514    ///
515    /// # Query errors
516    ///
517    /// * `planar-patch-primitives-degenerate-patch[-with-entity]` - A face has no interior point, or a patch is not two-dimensional, so no primitive fits it.
518    /// * `planar-patch-primitives-non-coplanar-faces[-with-entity]` - Faces that are adjacent, and so belong to the same patch, lie on different planes.
519    /// * `planar-patch-primitives-non-planar-faces[-with-entity]` - One or more of the requested faces is not planar.
520    pub fn planar_patch_primitives(
521        &self,
522        params: Option<&PlanarPatchPrimitivesParameters>,
523    ) -> Result<PlanarPatchPrimitivesResponse, CadLibError> {
524        let params_json = marshal_params(params)?;
525        let params_ptr = params_json
526            .as_ref()
527            .map_or(std::ptr::null(), |c| c.as_ptr());
528        deserialize_result(|r, e|
529            // SAFETY: `self.handle` is a live handle; `params_ptr` is null or a
530            // valid NUL-terminated JSON string; `r`/`e` are valid out-pointers.
531            unsafe { ffi::cad_planar_patch_primitives(self.handle, params_ptr, r, e) })
532    }
533
534    /// Computes volume and surface-area metrics for the model and its entities.
535    ///
536    /// Computes aggregated volume and surface area for the model, along with
537    /// per-solid, per-sheet, per-face and per-edge metrics.
538    ///
539    /// The query takes no parameters: the metrics always cover the whole model.
540    ///
541    /// Supported for Parasolid and nTop models. Other formats fail with
542    /// ``query-type-unsupported-for-cad-format``.
543    ///
544    /// # Errors
545    ///
546    /// Returns [`CadLibError::Expected`] for a known domain error and
547    /// [`CadLibError::Unexpected`] if the parameters cannot be serialized or the
548    /// library fails internally.
549    pub fn model_metrics(
550        &self,
551        params: Option<&ModelMetricsParameters>,
552    ) -> Result<ModelMetricsResponse, CadLibError> {
553        let params_json = marshal_params(params)?;
554        let params_ptr = params_json
555            .as_ref()
556            .map_or(std::ptr::null(), |c| c.as_ptr());
557        deserialize_result(|r, e|
558            // SAFETY: `self.handle` is a live handle; `params_ptr` is null or a
559            // valid NUL-terminated JSON string; `r`/`e` are valid out-pointers.
560            unsafe { ffi::cad_model_metrics(self.handle, params_ptr, r, e) })
561    }
562
563    /// Returns the model's entities: solids, sheets, faces, edges and vertices.
564    ///
565    /// The list is flat: each entity references its parents and children by their
566    /// 0-based index in it. Solids and sheets are the top-level entities.
567    ///
568    /// Each entity carries the entity id that the other queries take as input.
569    ///
570    /// Supported for Parasolid, STL and nTop models.
571    ///
572    /// # Errors
573    ///
574    /// Returns [`CadLibError::Expected`] for a known domain error and
575    /// [`CadLibError::Unexpected`] if the library fails internally.
576    pub fn entities(&self) -> Result<EntitiesResponse, CadLibError> {
577        deserialize_result(|r, e|
578            // SAFETY: `self.handle` is a live handle; `r`/`e` are valid out-pointers.
579            unsafe { ffi::cad_entities(self.handle, r, e) })
580    }
581}