You are viewing the documentation for Deformable v0.7.0, an older version. Read the latest, v0.9.0
Rust SDK
Errors and threads
The error type of the Rust SDK, the kinds of failure each call returns, how to handle them, and how to use the library from several threads and cancel long calls.
On this page
Every call that can fail returns a Result whose error is deformable::Error. The library checks your input and
returns an error instead of panicking. This page explains the error type, lists the kinds of failure each call
returns, shows how to handle them, and explains the thread rules. Every item, with its documentation, is in the
errors reference.
The error type
One type, Error, serves every call. It carries:
kind(): anErrorKind, what went wrong. Match on it to react to one case.message(): the library’s description of the failure, in English.Displayprints it too.first_index()andsecond_index(): the elements the failure names, such as a tetrahedron, a polygon, a vertex or the two vertices of an edge. They are 0 when the kind names no element. EachErrorKindvariant says what its indices mean.
Error implements std::error::Error, so the ? operator turns it into a Box<dyn std::error::Error>. It is also
Clone, Eq and Debug.
ErrorKind is a small Copy enum with one variant per failure. DegenerateTetrahedron carries a
mesh::DegenerateKind: an Inverted tetrahedron has its corners in the wrong order, so swap two of them; a Flat or
TooSmall one must be remeshed. A tetrahedron is degenerate when its orientation determinant is not above 1e-9, in
simulation units.
ErrorKind is #[non_exhaustive]: a newer library can add kinds, so a match on it needs a _ arm. A status this
crate does not know comes as ErrorKind::Unrecognized(code).
On this guide’s pages, “gives NonFiniteValue” is short for “returns an Error whose kind is
ErrorKind::NonFiniteValue”.
Error kinds
Each call returns only some kinds. This table lists them, with the meaning of the indices where a kind has them.
| Call | Kinds |
|---|---|
Scene methods |
Unknown, Unknown, Index, Length, Non, Scale, Invalid, Time. add_ also checks the mesh: Empty, Non and Degenerate, whose first index is the tetrahedron; and on Free, Tetrahedron. |
material_ |
The mesh kinds, and Degenerate: the first index is the region, the second the polygon. |
verify_, Polygon, Surface |
Index, Length, Non. |
meshes_, Tetrahedral |
Empty, Index, Non. |
boundary_ |
Empty, Index, Non, Non. |
triangulate |
Empty, Index and Degenerate (first index: the polygon), Non and Non (first and second index: the edge’s vertices), Non, Could, Cancelled, Output. |
tetrahedralize |
Bad, Meshing, No, Invalid, Cancelled, Output. |
autocage |
Empty, Index (first index: the polygon), Non, Step, Cancelled, Output. |
extrude, span_ |
Non, Not, Unknown, Duplicate and Degenerate (first index: the face), Multiple and Null (first index: the vertex). |
splinters_ |
Empty, Length, Non, No, No, Endless, Face. |
embed_, Surface |
Index, Length, Non, Empty, Non, Invalid, Singular. |
deformable functions |
Invalid (not a license key, another key is active, a key while signed in or a sign-in while a key is active, or no sign-in started), License, License, License, License. |
Three kinds can come from any call. InvalidArgument means the library could not read an argument, and Panicked
means it failed inside: drop the objects the call used. NullPointer never comes from this crate’s safe API; if you
see it, report a bug.
The ErrorKind reference gives the cause of every kind.
License errors
Nothing ever refuses to run. Without a subscription or a license, Deformable runs as Free, and a scene simulates up to 2,500 tetrahedrons. The license is the Application license key the program activated, or else Free, the Standalone subscription or the Standalone license of this device. A license error’s message is written to show the user as it is, such as Free: this would simulate 3,120 tetrahedrons; the limit is 2,500 per scene.
| Kind | When |
|---|---|
Tetrahedron |
On Free, Scene would take the scene past 2,500 tetrahedrons; a disabled object does not count. The first index is the count the scene would simulate with the object, the second the limit. add_ adds nothing then, and the scene goes on with the objects it holds. |
License |
A deformable function that goes online could not reach our licensing service or it did not answer, its answer did not verify, the device’s clock contradicts it, or set_ turned contacts off. Or deactivate or sign_ could not free the seat: the license or sign-in is forgotten all the same. |
License |
Our licensing service refused the Standalone key: it does not exist, was revoked or refunded, is not for Deformable, every seat of the license is in use, or this device was removed. Or the Application key was refused: it was revoked, its trial ended, its updates ended before this version was released, or the program is Blender or Maya, where Application licenses do not work. |
License |
The license state could not be saved in your user folder. |
License |
wait_ ended the sign-in: it was denied, or its code is no longer valid. Or this version of Deformable cannot sign in, or our licensing service could not read its request. Start a new sign-in, or update Deformable. |
Scene::add_object is the only engine call the license can refuse. The mesh tools and render surfaces have no limit.
When a scene holds more than fits, such as after a subscription or a Standalone license went too long offline,
Scene::step simulates the objects that fit, in the order they were added, and holds the rest still until a
subscription or a license applies again. Creating a scene, setting its values, reading its outputs and dropping it never
check the license, so your program can always clean up. deformable::license reads and changes the license state: see
License.
Handle an error
Match on the kind to react to one case, and pass the rest on:
use deformable::ErrorKind;
use deformable::math::Vector3;
use deformable::mesh::{DegenerateKind, TetrahedralMesh};
use deformable::scene::{MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let positions = vec![Vector3::ZERO, Vector3::X, Vector3::Y, Vector3::Z];
let mut mesh = TetrahedralMesh { positions, tetrahedrons: vec![[0, 1, 2, 3]] };
let mut scene = Scene::new();
let material = scene.add_material(&MaterialParameters::default())?;
let materials = TetrahedronMaterials::Uniform(material);
let object = match scene.add_object(&mesh, materials, ObjectOptions::default()) {
Err(error) if error.kind() == ErrorKind::DegenerateTetrahedron(DegenerateKind::Inverted) => {
let tetrahedron = error.first_index();
println!("tetrahedron {tetrahedron} is inverted: swapping two corners");
mesh.tetrahedrons[tetrahedron as usize].swap(1, 2);
scene.add_object(&mesh, materials, ObjectOptions::default())?
}
result => result?,
};
println!("added {object:?}");
scene.remove_object(object)?;
let error = scene.node_positions(object, &mut Vec::new()).unwrap_err();
println!("{:?}: {error}", error.kind());
println!("{}", scene.set_scale(5000.0).unwrap_err());
Ok(())
}tetrahedron 0 is inverted: swapping two corners
added ObjectHandle(0)
UnknownObject: unknown object
scale outside [0.001, 1000]A tool error is handled the same way. Here a size that is far too fine for the cage is refused before any work, and the program tries a coarser one:
mod shapes;
use deformable::ErrorKind;
use deformable::math::Vector3;
use deformable::tools::{Anisotropy, TetrahedralizeParameters, TriangulateParameters, tetrahedralize, triangulate};
use shapes::cuboid;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cube = cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0));
let refined = TriangulateParameters { maximum_area: Some(0.05), ..TriangulateParameters::default() };
let cage = triangulate(&cube, &[], &refined, None)?.mesh;
for maximum_edge_length in [0.0001, 0.3] {
let parameters = TetrahedralizeParameters {
maximum_edge_length,
anisotropy: [Anisotropy::default(); 2],
density_regions: Vec::new(),
};
match tetrahedralize(&cage, ¶meters, None) {
Ok(result) => println!("{maximum_edge_length}: {} tetrahedrons", result.mesh.tetrahedrons.len()),
Err(error) if error.kind() == ErrorKind::OutputTooLarge => {
println!("{maximum_edge_length}: too fine for this cage")
}
Err(error) => return Err(error.into()),
}
}
Ok(())
}0.0001: too fine for this cage
0.3: 471 tetrahedronsWhat the library checks
Every public call checks its input. add_object checks the whole mesh before it creates anything, so a refused
mesh leaves no half-built object behind.
- Positions and parameters must be finite. NaN and infinity give
NonFiniteValue, or the tool’s matching kind.tetrahedralizehas two exceptions: it treats a NaN or infinitemaximum_edge_lengthas no size limit, and it clamps an infinite anisotropy scale or direction instead of refusing it. - Indices must be in range, and list lengths must match.
add_objectalso runs the quality check on every tetrahedron.- Tools whose output grows with a size parameter estimate the output first, and return
OutputTooLargeinstead of running out of memory.
To check a mesh early, before a call that would refuse it, use the validate methods of TetrahedralMesh,
PolygonMesh and SurfaceMesh. They check that every index is in range and that every position is finite.
TetrahedralMesh::validate also refuses a mesh with no tetrahedron; the other two accept a mesh with no polygon, and
check that the polygon sizes add up to the corner count. They run in the crate, without calling the library, and do not run the tetrahedron
quality check.
Numerical trouble inside a step is not an error. When the positions of a part of an object become NaN, that part stops moving, and the NaN never reaches another object through a contact.
Threads
The library is thread-safe in the Rust way: the types say what you can share.
SceneisSendbut notSync. You can move it to another thread, and you call it from one thread at a time. Wrap it in aMutexto reach it from several threads.stepruns its own worker threads.set_worker_countsets how many, and the results do not depend on it.- The tools keep no global state. Call them from as many threads as you like.
- The mesh types, the parameter types,
SurfaceEmbeddingandCancelFlagareSendandSync. Several threads can skin one embedding at once. - The error of a failed call is read on the thread that made the call, so errors never mix between threads.
This example fills one cage at three sizes on three threads, then steps a scene on another thread and takes it back:
mod shapes;
use std::thread;
use deformable::math::Vector3;
use deformable::scene::{MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use deformable::tools::{Anisotropy, TetrahedralizeParameters, TriangulateParameters, tetrahedralize, triangulate};
use shapes::cuboid;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cube = cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0));
let refined = TriangulateParameters { maximum_area: Some(0.05), ..TriangulateParameters::default() };
let cage = triangulate(&cube, &[], &refined, None)?.mesh;
// One tool call per thread, all reading the same cage.
let results = thread::scope(|scope| {
let workers: Vec<_> = [0.3, 0.2, 0.1]
.map(|maximum_edge_length| {
let cage = &cage;
scope.spawn(move || {
let parameters = TetrahedralizeParameters {
maximum_edge_length,
anisotropy: [Anisotropy::default(); 2],
density_regions: Vec::new(),
};
tetrahedralize(cage, ¶meters, None)
})
})
.into_iter()
.collect();
workers.into_iter().map(|worker| worker.join().expect("the tool does not panic")).collect::<Vec<_>>()
});
let mut meshes = Vec::new();
for result in results {
meshes.push(result?.mesh);
}
println!("{:?}", meshes.iter().map(|mesh| mesh.tetrahedrons.len()).collect::<Vec<_>>());
// Move the scene to a worker thread, step it there, and take it back.
let mut scene = Scene::new();
let material = scene.add_material(&MaterialParameters::default())?;
let object = scene.add_object(&meshes[0], TetrahedronMaterials::Uniform(material), ObjectOptions::default())?;
let worker = thread::spawn(move || {
for frame in 0..=24 {
scene.step(f64::from(frame) / 24.0, 10, None).expect("a valid step");
}
scene
});
let scene = worker.join().expect("the step does not panic");
let mut positions = Vec::new();
scene.node_positions(object, &mut positions)?;
println!("{} nodes after one second on another thread", positions.len());
Ok(())
}[471, 727, 2602]
146 nodes after one second on another threadAt 0.3 the size follows the cage triangles, so a coarser size would give the same 471 tetrahedrons.
Cancel a long call
The calls that can run long take a cancel: Option<&CancelFlag>: Scene::step, triangulate,
tetrahedralize and autocage. Pass None for no flag. They read the flag often while they run.
CancelFlag::new()creates a flag that is not set.set(true)sets it from any thread, andis_set()reads it.- A tool returns an error of kind
Cancelledonce the flag is set. - A step stops between two substeps, after at least one, and returns
OkwithStepOutcome::Cancelled. The time stands at the last substep run, so the next step goes on from there. - A flag that is already set stops a tool at once, and a step after its first substep. Clear it with
set(false)before you reuse it. - One flag can serve several calls at once, for example every tool of one job.
Scene and Tools each show a flag set from another thread.
Next steps
- Getting started: the crate and its conventions.
- Errors reference:
Error,ErrorKindandCancelFlag, with their documentation. - Support: report a bug in the SDK.