You are viewing the documentation for Deformable v0.1.1, an older version. Read the latest, v0.9.0
Python SDK
Types and errors
The value types, array forms, handles, errors, threads and units that every part of the Python SDK shares.
On this page
This page explains the rules that every part of the package follows: how you pass points and meshes in, what comes
back, who frees what, and what happens when a call fails. Every name on this page is in the deformable module.
The examples on this page build on each other. Run them in order in one Python session, starting with the first. For every field and member of these types, see the Python API reference; the vectors and transforms are on the math reference.
Points, vectors and transforms
The package returns points as Vector3(x, y, z) and UVs as Vector2(x, y). Both are named tuples. The one exception
is the skinned surface SurfaceEmbedding.deform returns: a DeformedSurface holds flat arrays of 32-bit floats, three
per position or normal. Anywhere the package takes a point or a vector, a plain tuple or list of numbers works too.
AffineTransform(linear, translation) maps row vectors: a point p goes to p · linear + translation. So linear[i]
is where axis i goes. A matrix M that maps column vectors (M · p, as in Blender) gives linear[i][j] = M[j][i].
IDENTITY is the transform that leaves every point where it is.
import deformable
turn = deformable.AffineTransform(((0.0, 1.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 0.0, 1.0)), (0.0, 0.0, 5.0))
print(turn.linear[0], turn.translation)
print(deformable.IDENTITY.translation)(0.0, 1.0, 0.0) (0.0, 0.0, 5.0)
(0.0, 0.0, 0.0)This transform turns the x axis into the y axis, then moves points 5 units along z.
Mesh classes
The mesh classes are plain dataclasses. They hold whatever array form you give them. Any object with the same attribute names works in place of a mesh class, so you can pass your own mesh type.
| Class | Fields | Made by |
|---|---|---|
Tetrahedral |
positions, and tetrahedrons with four node indices each |
tetrahedralize, extrude, span_ |
Triangle |
positions, and triangles with three vertex indices each |
triangulate, autocage |
Polygon |
positions; polygon_, the corner count of each polygon; polygon_, the vertex of each corner, polygon after polygon |
splinters_ |
Surface |
mesh, a Polygon, plus the optional per-corner normals, uv_ and colours |
Surface |
FaceHole(face, first_corner, corner_count) marks a run of a polygon’s corners as a hole loop, for triangulate
and verify_surface. Every field of these classes is on the meshes reference.
Orientation
Every tetrahedral mesh the library takes must be positively oriented. For a tetrahedron (X0, X1, X2, X3), with
eᵢ = Xᵢ - X0, the value -e1 · (e2 × e3) is positive: the corners are left-handed. Face k is the face opposite
corner k, and face_corners(k) gives its three corners. The tools make positive tetrahedrons, though a thick
extrude shell can invert some where the mesh curves sharply. If you build a
mesh yourself and add_object raises DEGENERATE_TETRAHEDRON_INVERTED, your tetrahedrons are right-handed: swap two
corners of each one.
Triangle cages face outward: seen from outside, the corners of a triangle run counter-clockwise.
Array forms
Every array input takes any of these forms:
- A sequence of groups: a list of
(x, y, z)tuples, of lists, or ofVector3. - A flat sequence of numbers, group after group.
- Any buffer:
array.array,memoryview,bytes, or another object with the buffer protocol, flat or with one row per group. A buffer that already holds the C type,array("d")for positions orarray("I")for indices, is copied as one block. Any other buffer, such asarray("f")from Blender’sforeach_get, is read number by number.
import array
positions = [(x, y, z) for z in (0.0, 1.0) for y in (0.0, 1.0) for x in (0.0, 1.0)]
triangles = [
(0, 2, 3), (0, 3, 1), (4, 5, 7), (4, 7, 6), (0, 1, 5), (0, 5, 4),
(2, 6, 7), (2, 7, 3), (0, 4, 6), (0, 6, 2), (1, 3, 7), (1, 7, 5),
]
parameters = deformable.TetrahedralizeParameters(0.5)
from_tuples = deformable.tetrahedralize(deformable.TriangleMesh(positions, triangles), parameters).mesh
flat_positions = array.array("d", [coordinate for position in positions for coordinate in position])
flat_triangles = array.array("I", [vertex for triangle in triangles for vertex in triangle])
from_buffers = deformable.tetrahedralize(deformable.TriangleMesh(flat_positions, flat_triangles), parameters).mesh
print(from_tuples == from_buffers, from_buffers.positions[0], from_buffers.tetrahedrons[0])True Vector3(x=0.0, y=0.0, z=0.0) (8, 4, 5, 0)Results are copied out of the library at once. They are lists of Vector3, of int and of index tuples, and they
stay valid after later calls. The one exception is SurfaceEmbedding.deform, which returns flat array.array
copies for speed.
Enumerations
Every enumeration is an enum.IntEnum, so its members compare equal to their numbers, and a plain int works as an
argument. A number the library does not define raises INVALID_ARGUMENT.
| Enumeration | Used by |
|---|---|
Step |
Scene.step, see Scene |
Clip |
embed_, see Render surfaces |
Extrude |
extrude, see Tools |
Self, Mesh |
verify_, see Tools |
Status |
Deformable, below |
The members and their numbers are under each enumeration in the Python API reference:
StepOutcome,
ClipMode,
ExtrudeDirection,
SelfIntersectionCheck,
MeshIssueKind and
Status.
Errors
The package raises these exceptions.
| Exception | When |
|---|---|
Deformable |
The library refused a call. |
License |
The trial or license does not allow a call. A subclass of Deformable, see License errors. |
Value |
The package refused an argument before the call, or the handle is closed. |
Type |
An argument has the wrong type, such as a string where numbers belong. |
Library |
No shared library was found. It is a subclass of OSError. |
DeformableError
A DeformableError carries four attributes:
status: a member ofdeformable.Status, such asStatus.NON_CLOSED_BOUNDARY. A code newer than the package comes through as a plainint.message: the library’s message, in English.first_indexandsecond_index: the elements the failure concerns, such as the tetrahedron, the polygon or the two vertices of an edge. They are 0 when the status names none.
str(error) is the status name, a colon and the message. In these guides, a status name such as NON_CLOSED_BOUNDARY
means a DeformableError with that status. Nothing is created when a call fails.
cube = from_tuples
tetrahedrons = [list(tetrahedron) for tetrahedron in cube.tetrahedrons]
tetrahedrons[3][0], tetrahedrons[3][1] = tetrahedrons[3][1], tetrahedrons[3][0]
with deformable.Scene() as scene:
material = scene.add_material(deformable.MaterialParameters.default())
try:
scene.add_object(deformable.TetrahedralMesh(cube.positions, tetrahedrons), material)
except deformable.DeformableError as error:
print(error.status == deformable.Status.DEGENERATE_TETRAHEDRON_INVERTED, error.first_index)
print(error)True 3
DEGENERATE_TETRAHEDRON_INVERTED: tetrahedron 3 is invertedSwapping two corners turns tetrahedron 3 inside out, so add_object refuses the mesh and names the tetrahedron.
The status codes are the same as the C SDK’s. The full list, with what each index names, is on the errors reference.
License errors
Engine calls check the trial or license of this computer first. When it does not allow the call, the call raises
LicenseError, a subclass of DeformableError, with one of these statuses, and nothing is created. Its message is
written to show the user as it is, such as Trial ended — Buy license. Two statuses have their own subclass of
LicenseError: LicenseRequiredError and TrialLimitExceededError, whose tetrahedrons and limit name the count
that would take part in the simulation and the limit.
| Status | When |
|---|---|
LICENSE_ |
The trial ended, the computer has no trial, or the license was removed. |
TRIAL_ |
More than 2,500 tetrahedrons would take part in the simulation during the trial; a disabled object does not count. first_ is that count, second_ the limit. Scene.add_ adds nothing then, and the scene goes on with the objects it holds. |
LICENSE_ |
The trial has not started, the license needs its renewal, or the clock is behind. |
LICENSE_ |
activate, deactivate or refresh could not reach our licensing service, the service refused this copy of the library, its answer did not verify, or set_ turned contacts off. |
LICENSE_ |
Our licensing service refused the key: unknown, revoked or expired, of another product, or its seat is in use on another device; or the service takes no more devices. |
LICENSE_ |
The license state could not be saved in your user folder. |
The mesh tools, verify_surface, meshes_intersect, boundary_faces, material_region_indices, embed_surface,
SurfaceEmbedding.deform, Scene.add_object, Scene.step and Scene.skip_to check the license.
Creating a scene, setting its values, reading its outputs and closing handles never do, so your tool can always
clean up. deformable.license reads and changes the license state: see
License.
with deformable.Scene() as scene:
material = scene.add_material(deformable.MaterialParameters.default())
try:
scene.add_object(cube, material)
scene.step(1.0, substeps=10)
except deformable.TrialLimitExceededError as error:
print(f"{error.tetrahedrons} tetrahedrons, the trial allows {error.limit}")
except deformable.LicenseError as error:
print(error.message)While the trial or the license allows the calls, this prints nothing.
What the package refuses before the call
Some arguments cannot be checked by the library, so the package checks them first:
- A negative index, handle or count, or one too large for its C type, raises
ValueError. Indices and handles stop below 2^32. - Vertex or index data that is not a whole number of groups raises
ValueError, for example 2 numbers for a position. - A UV set without one pair per corner raises
ValueError. - A string where numbers belong raises
TypeError, and so does a preset name that is not astr. - Any call on a closed
Scene,SurfaceEmbeddingorCancelFlagraisesValueError.
try:
deformable.boundary_faces(deformable.TetrahedralMesh([0.0, 1.0], [(0, 1, 2, 3)]))
except ValueError as error:
print(error)positions holds 2 numbers, not a whole number of groups of 3Handles
Three classes own a library handle: Scene, SurfaceEmbedding and CancelFlag. Each one frees its handle in
one of three ways:
- at the end of a
withblock; - when you call
close(); - when the garbage collector collects it, at a time you do not control.
close() waits for the calls in flight on the object from other threads, then frees the handle. Closing twice does
nothing, and closed is True afterwards. Any later call raises ValueError.
scene = deformable.Scene()
scene.close()
try:
scene.step(0.0, 10)
except ValueError as error:
print(scene.closed, error)True the scene is closedObject and material handles are not classes. They are int values that count up from 0 in creation order, and they
belong to the scene that made them.
Cancel a long call
A CancelFlag stops a long call from another thread. Call set() to raise it, clear() to use it again, and
is_set() to read it. Scene.step, triangulate, tetrahedralize and autocage take one. See the
cancel flag reference.
A tool stops with CANCELLED. A step stops between two substeps and returns a StepReport whose outcome is
StepOutcome.CANCELLED; it does not raise.
with deformable.CancelFlag() as cancel:
cancel.set()
try:
deformable.tetrahedralize(deformable.TriangleMesh(positions, triangles), parameters, cancel)
except deformable.DeformableError as error:
print(error.status.name, cancel.is_set())CANCELLED TrueTools shows how to set the flag from another thread while a tool runs.
Threads
Library calls release the global interpreter lock, so other Python threads run while a call works.
- A
Scenecan move between threads. Calls on one scene from several threads run one at a time. - Tools,
SurfaceEmbeddingreads and skinning, and cancel flags work from several threads at once. - Results are bitwise identical run to run, whatever the worker count.
Units
Lengths cross in host units: positions, driven targets, glue plane offsets and every tool input. Time is in seconds.
Forces, gravity, node masses and material values are in simulation units. Scene.set_scale converts host
lengths to simulation lengths. The default scale of 1 makes them the same, and the default gravity of 9.81 makes a
unit read as a metre. The tools always work in their input’s unit. See
Units and axes.
Versions
deformable.__version__ is the package version, such as "0.1.0". deformable.library_version() loads the library
and returns its version, as major.minor.patch. The two match when the package and the library come from the same
release. See Getting started for how the package finds the library.
Next steps
- Scene: materials, objects, driving, glue, stepping and outputs.
- Errors reference: every status, with what its indices name.
- Support: report a bug in the SDK.