You are viewing the documentation for Deformable v0.2.0, an older version. Read the latest, v0.9.0

Python SDK

Scene

The Scene class, from materials and objects to driving, glue, stepping and reading the per-frame outputs.

On this page

A Scene holds materials and objects and steps them through time. You add them to it, then call step once per frame and read the outputs. What each setting, material value and output means, the same in the plugins and every SDK, is in the Engine guide: Simulation settings, Materials and Kinematic objects and regions. Every name on this page is in the deformable module. For every method and field, see the scene reference.

The examples on this page build on each other. Run them in order in one Python session, starting with the first.

The frame loop

This example drops a glass cube onto a floor that stays in place. The glass breaks on impact.

python
import deformable


def box(minimum, maximum):
    """A closed box as six outward quads."""
    (x0, y0, z0), (x1, y1, z1) = minimum, maximum
    positions = [(x, y, z) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)]
    corners = [0, 2, 3, 1, 4, 5, 7, 6, 0, 1, 5, 4, 2, 6, 7, 3, 0, 4, 6, 2, 1, 3, 7, 5]
    return deformable.PolygonMesh(positions, [4] * 6, corners)


def solid(polygons, maximum_area, maximum_edge_length):
    """Triangulate a closed polygon mesh, then fill it with tetrahedrons."""
    parameters = deformable.TriangulateParameters.default(maximum_area=maximum_area)
    cage = deformable.triangulate(polygons, parameters=parameters).mesh
    return deformable.tetrahedralize(cage, deformable.TetrahedralizeParameters(maximum_edge_length)).mesh


floor_mesh = solid(box((-3.0, -0.5, -3.0), (3.0, 0.0, 3.0)), 1.0, 1.0)
cube_mesh = solid(box((-0.5, 2.0, -0.5), (0.5, 3.0, 0.5)), 0.05, 0.3)
rest_boundary = deformable.boundary_faces(cube_mesh)

with deformable.Scene() as scene:
    stone = scene.add_material(deformable.MaterialParameters.preset("stone"))
    glass = scene.add_material(deformable.MaterialParameters.preset("glass"))

    # The floor is driven: each node is held at its rest position.
    floor = scene.add_object(floor_mesh, stone)
    scene.drive(floor, list(enumerate(floor_mesh.positions)))
    cube = scene.add_object(cube_mesh, glass)

    # Faces that fracture opened, per tetrahedron: exposed now, but not on the rest surface.
    new_faces = {}
    for frame in range(49):
        scene.step(frame / 24, substeps=10)
        for event in scene.face_events(cube):
            new_faces[event.tetrahedron] = event.exposed_faces & ~rest_boundary[event.tetrahedron]

    states = scene.tetrahedron_states(cube)
    print("rest nodes:", len(cube_mesh.positions))
    print("nodes now:", len(scene.node_positions(cube)))
    print("fractured tetrahedrons:", len(new_faces))
text
rest nodes: 145
nodes now: 342
fractured tetrahedrons: 398

Each frame, step advances the scene to the frame’s time, in 10 substeps. face_events lists the tetrahedrons that fracture changed in that step. Fracture splits nodes, so the cube ends with more nodes than it started with. The tetrahedron count stays the same.

Create a scene

Scene() creates an empty scene with gravity (0, -9.81, 0), scale 1, and min(available parallelism, 16) worker threads. So a simulation unit reads as a metre, and y points up. Change these before you add objects:

  • set_scale(scale) sets the factor from your length unit to simulation units, from 0.001 to 1,000; see Scale. For a scene modelled in centimetres, call set_scale(0.01). The scale multiplies positions, driven targets and glue plane offsets on the way in, and divides positions and velocities on the way out.
  • set_gravity(gravity) sets the gravity, three numbers in simulation units. For a z-up scene, pass (0.0, 0.0, -9.81).
  • set_worker_count(count) sets the number of threads, the calling thread included. The result does not depend on it: runs are bitwise identical whatever the count.

A scene owns a library handle. Use it in a with block, or call close(), to free it at a known point. It can move between threads, but it takes one call at a time. See Types and errors.

Materials

MaterialParameters is a frozen dataclass with the ten values of a material, all in simulation units. What each value does, and how to make a material elastic, plastic or breakable, is on Materials:

Value Default Range What it does
youngs_modulus 800000 [1000, 1e10] Stiffness, in pascals. Higher is stiffer.
poissons_ratio 0 [-0.90001, 0.490001] How much the material bulges sideways when you squeeze it.
density 2500 [0, 10000] Mass per unit volume.
toughness 200000 [0, 1e8] How hard it is to break. 0 or less means unbreakable.
youngs_damping 0 [0, 1e9] Damping that grows with stiffness. It calms vibration.
yield_strain 0 [0, 1] The strain above which the material starts to keep a dent.
maximum_yield 0 [0, 1] The largest dent the material keeps.
creep_fraction 0 [0, 1] How fast a dent forms, from 0 to 1. 0 turns denting off.
wake_up_radius 1.2 [1, 1000] How far an impact wakes a sleeping object that has glue, in simulation units. See Sleep.
friction 0.6 [0, 1] The friction coefficient. Two touching materials use the smaller value.

add_material raises NON_FINITE_VALUE for a NaN or infinite value, and clamps every other value to its range. print(deformable.MaterialParameters.default()) shows the defaults.

The library ships the 43 presets of Materials, which lists them with their values. MaterialParameters.preset(name) returns one, or None for an unknown name. MaterialParameters.default(**changes) returns the defaults with the named values changed. To change one value of an existing material, use dataclasses.replace.

python
import dataclasses

rubber = deformable.MaterialParameters.preset("rubber")
heavy = deformable.MaterialParameters.default(density=7800.0, toughness=0.0)
soft_rubber = dataclasses.replace(rubber, youngs_modulus=rubber.youngs_modulus / 2)
print(rubber.youngs_modulus, soft_rubber.youngs_modulus, heavy.density)
print(len(deformable.MaterialParameters.presets()), deformable.MaterialParameters.preset("Steel"))
text
970000.0 485000.0 7800.0
43 None

A name must match exactly, case included.

add_material returns a material handle, an int. set_material(material, parameters) rewrites a material later; the objects that use it take the new values before the next step. A new density changes the lumped node masses then too, and the velocities stay as they were.

Objects

add_object(mesh, materials, options=None) creates an object from a tetrahedral mesh and returns its handle, an int. The mesh is in world space and in your length unit. materials is one material handle for the whole object, or one handle per tetrahedron.

The mesh is checked before anything is created. A mesh with no tetrahedron, a NaN position, a face shared by three tetrahedrons, or a tetrahedron that is too small, flat or inverted is refused with a DeformableError that names the problem. The errors reference lists every status.

ObjectOptions holds two per-object settings: self_collision, on by default, lets the object’s faces collide with each other; disabled creates the object disabled. Build it with ObjectOptions.default(self_collision=False).

After you add an object, you can:

  • give it new materials with set_object_material;
  • turn it off and on with set_object_disabled; a disabled object keeps its outputs and ignores forces, and its driving waits until it is enabled;
  • turn self-collision off or on with set_self_collision;
  • keep a node, and the part around it, from ever sleeping with set_never_sleep;
  • delete it with remove_object. Later calls with its handle raise UNKNOWN_OBJECT.

Material regions

A material region gives the tetrahedrons inside a convex polyhedron their own material. material_region_indices(mesh, regions) returns one value per tetrahedron: 0 when no region holds the tetrahedron’s centroid, or k + 1 for the region k that holds it. Where regions overlap, the one with the smallest volume wins, whatever their order in the list. For every field, see the material regions reference.

MaterialRegion(mesh, to_mesh_space=IDENTITY) takes a closed convex PolygonMesh with outward faces, and an AffineTransform from the region’s space into the tetrahedral mesh’s space. You turn the indices into materials yourself: 0 is the object’s material, k + 1 is region k’s.

python
block_mesh = solid(box((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 0.05, 0.3)
left_half = box((0.0, 0.0, 0.0), (0.5, 1.0, 1.0))
indices = deformable.material_region_indices(block_mesh, [deformable.MaterialRegion(left_half)])

with deformable.Scene() as scene:
    materials = [
        scene.add_material(deformable.MaterialParameters.preset("wood")),
        scene.add_material(deformable.MaterialParameters.preset("steel")),
    ]
    block = scene.add_object(block_mesh, [materials[index] for index in indices])
    print(sorted(set(indices)), indices.count(1), "of", len(indices), "tetrahedrons are steel")
text
[0, 1] 223 of 471 tetrahedrons are steel

Drive vertices and add forces

A driven vertex follows a path you give instead of the simulation, and a force pushes a vertex; see Driven vertices and forces. drive(object_handle, vertices) moves vertices to targets you give. Each entry is a DrivenVertex(vertex, target), or a plain (vertex, target) pair: vertex is a node index, and target is a position in your length unit.

  • The targets act from the next step on, and they hold until the next drive call for the object.
  • A vertex driven before but not listed in the new call is released, with its last driven velocity. So you can throw an object: drive it along a path, then release it.
  • drive(object_handle, []) releases them all.
driven released keeps its last velocity each node moved to its target

A floor that never moves is an object whose every node is driven to its rest position, once:

python
with deformable.Scene() as scene:
    stone = scene.add_material(deformable.MaterialParameters.preset("stone"))
    floor = scene.add_object(floor_mesh, stone)
    scene.drive(floor, list(enumerate(floor_mesh.positions)))
    for frame in range(25):
        scene.step(frame / 24, substeps=10)
    print(scene.node_positions(floor) == floor_mesh.positions)
text
True

To animate an object, call drive before each step with the targets for the end of that step.

add_force(object_handle, node, force) queues a force, in simulation units, on one node. It acts in every substep of the next step, then it is dropped. Every step call that returns a report takes the queued forces, even one that runs no substep, such as the first call, and skip_to drops them: a force queued before the first step call never acts. To apply a force field, read node_positions, node_velocities and node_masses, compute the forces, and queue them before each step.

Glue

Glue holds objects together where they overlap, with a spring and a damper; see Glue regions. GlueParameters(spring_constant, damping_coefficient) sets its strength; a value of 0 takes the library’s default. The damper resists only motion relative to the other object, so an object glued to a driven one rides along with it.

  • set_glue_all(parameters) glues each new object to every other enabled object it overlaps. None turns it off, as in a new scene.
  • add_glue_region(region, members, parameters) glues the listed objects only where their tetrahedrons have a vertex inside a ConvexRegion.

Glue is made by the step after the objects are added, and the first step call only records the time. So add the objects, turn glue on, then step as usual.

This example hangs a rubber cube from a fixed block. The cube overlaps the block by 0.05. With glue it stays; without glue it falls.

python
anchor_mesh = solid(box((-1.0, 3.0, -1.0), (1.0, 3.5, 1.0)), 0.5, 0.5)
hanging_mesh = solid(box((-0.5, 2.05, -0.5), (0.5, 3.05, 0.5)), 0.05, 0.3)


def lowest_point_after_one_second(glue):
    with deformable.Scene() as scene:
        stone = scene.add_material(deformable.MaterialParameters.preset("stone"))
        rubber = scene.add_material(deformable.MaterialParameters.preset("rubber"))
        anchor = scene.add_object(anchor_mesh, stone)
        scene.drive(anchor, list(enumerate(anchor_mesh.positions)))
        hanging = scene.add_object(hanging_mesh, rubber)
        if glue:
            scene.set_glue_all(deformable.GlueParameters(0.0, 0.0))
        for frame in range(25):
            scene.step(frame / 24, substeps=10)
        return min(position.y for position in scene.node_positions(hanging))


print(f"glued: {lowest_point_after_one_second(True):.2f}, not glued: {lowest_point_after_one_second(False):.2f}")
text
glued: 2.04, not glued: -3.59

A ConvexRegion(planes) holds the points inside every one of its planes. Plane(normal, offset) puts a point p inside when normal · p + offset <= 0. ConvexRegion.contains(point) runs the same test the library runs:

python
region = deformable.ConvexRegion([deformable.Plane((1.0, 0.0, 0.0), -0.5)])
print(region.contains((0.25, 0.0, 0.0)), region.contains((0.75, 0.0, 0.0)))
text
True False

Stepping

step(time, substeps, cancel=None) advances the scene to time, in seconds, in substeps equal substeps. Call it once per frame with the frame’s time.

  • The first call only records the time. Start your loop at the start frame, so the first frame shows the rest pose.
  • Time only goes forward. A time before the last step’s time raises TIME_WENT_BACKWARDS. To restart, create a new scene.
  • A substep longer than 0.04 seconds is not simulated: the time advances without a step. At 24 frames per second, use at least 2 substeps. See Substeps.
  • skip_to(time) moves the time without stepping, to pause a scene. It makes no glue, applies no driven vertices and drops the queued forces. The next step goes on from there.
one step per frame 10 substeps frame 0 frame 1 frame 2 first call records the time

step returns a StepReport(substeps_run, outcome). The outcome is a StepOutcome: STEPPED when the substeps ran, FIRST_CALL for the first call, or the reason nothing ran (NO_TIME_ELAPSED, NO_SUBSTEPS, SUBSTEP_TOO_LARGE, CANCELLED).

A CancelFlag set from another thread stops the step between two substeps, after at least one. The step does not raise: it returns the outcome CANCELLED, and the next step goes on from there.

python
import threading

with deformable.Scene() as scene:
    material = scene.add_material(deformable.MaterialParameters.default())
    scene.add_object(cube_mesh, material)
    print(scene.step(0.0, 10).outcome.name)
    with deformable.CancelFlag() as cancel:
        threading.Timer(0.0, cancel.set).start()
        report = scene.step(10.0, 1000, cancel)
    print(report.outcome.name, report.substeps_run < 1000)
text
FIRST_CALL
CANCELLED True

Sleep

An object at rest on a support goes to sleep: the solver stops working on it until something wakes it. Why, and what a material’s Wake Up Radius does, is on Sleep. The rules:

  • An island of tetrahedrons can sleep only when it rests on support: a driven node, a sleeping neighbour, or a contact with a driven or sleeping object. A free object in the air never sleeps.
  • It sleeps once every node moves slower than 0.001 simulation units per second for two substeps.
  • An impact faster than 1 simulation unit per second wakes the object it hits. On an object with glue, it wakes only the tetrahedrons within the material’s wake_up_radius of the contact. Driving a sleeping node, or adding a force to it, wakes it too.
  • set_never_sleep(object_handle, node, True) keeps the island of that node awake for good.

awake_tetrahedron_count() returns the number of tetrahedrons in awake islands, over the whole scene. This example sets a glass cube on the floor and counts the awake tetrahedrons each second. The driven floor never counts as awake:

python
resting_mesh = solid(box((-0.5, 0.0, -0.5), (0.5, 1.0, 0.5)), 0.05, 0.3)

for never_sleep in (False, True):
    with deformable.Scene() as scene:
        stone = scene.add_material(deformable.MaterialParameters.preset("stone"))
        glass = scene.add_material(deformable.MaterialParameters.preset("glass"))
        floor = scene.add_object(floor_mesh, stone)
        scene.drive(floor, list(enumerate(floor_mesh.positions)))
        resting = scene.add_object(resting_mesh, glass)
        if never_sleep:
            scene.set_never_sleep(resting, 0, True)

        counts = []
        for frame in range(121):
            scene.step(frame / 24, substeps=10)
            if frame % 24 == 0:
                counts.append(scene.awake_tetrahedron_count())
        print(f"never sleep: {never_sleep}, awake each second: {counts}")
text
never sleep: False, awake each second: [0, 463, 463, 463, 0, 0]
never sleep: True, awake each second: [0, 463, 463, 463, 463, 463]

At frame 0 nothing is counted yet, because the first step only records the time. The cube settles, then sleeps after about 4 seconds. With one never-sleep node, it stays awake. How fast an object settles depends on its material: in this scene, a stone, rubber or wooden cube is still awake after 10 seconds.

Outputs

Each output method copies the data out of the library at once, so the lists stay valid after later calls.

  • node_positions(object_handle) and node_velocities(object_handle): one Vector3 per node, in your length unit and your length unit per second.
  • node_masses(object_handle): the mass of each node, in simulation units.
  • tetrahedron_nodes(object_handle): the current four nodes of each tetrahedron, in mesh order.
  • tetrahedron_states(object_handle): one TetrahedronState per tetrahedron, with its corner positions, its island, a strain measure and flags.
  • face_events(object_handle): one FaceEvent(tetrahedron, exposed_faces) per tetrahedron that fracture changed in the last step.
  • awake_tetrahedron_count() and statistics(): counters for the whole scene.

The tetrahedron count of an object never changes, but its node count grows as it breaks. To draw a broken object, read node_positions and tetrahedron_nodes together, or skin a render surface as Render surfaces shows.

fracture 2 tetrahedrons, 5 nodes 2 tetrahedrons, 8 nodes

Find the faces a crack opened

In a FaceEvent, bit k of exposed_faces is set when face k of the tetrahedron, the face opposite corner k, is shared with no other tetrahedron. Faces on the rest surface count too. boundary_faces(mesh) gives that rest mask, so exposed_faces & ~boundary_faces(mesh)[tetrahedron] keeps only the faces a crack opened. The frame loop above collected them in new_faces.

TetrahedronState.face_centroid(face) and face_normal(face) place a point and an outward direction on a face. Use them to emit dust or debris where the cube broke, as the plugins’ fracture points do:

python
debris = [
    (states[tetrahedron].face_centroid(face), states[tetrahedron].face_normal(face))
    for tetrahedron, mask in sorted(new_faces.items())
    for face in range(4)
    if mask & (1 << face)
]
print(len(debris), "new faces")
text
444 new faces

Next steps

  • Tools: build the tetrahedral meshes you add as objects.
  • Render surfaces: skin the artist’s mesh on the simulated object.
  • Scene reference: every class and method of the scene, with its signature.