﻿---
title: Scene
description: Create a scene, add materials and objects, drive vertices, add forces and glue, step it frame by frame, and read the outputs.
url: https://help.tangerina.io/deformable/v0.2.1/user-guides/rust/scene/
---

# Scene – Rust SDK – Deformable v0.2.1

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](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/simulation-settings/),
[Materials](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/materials/) and
[Kinematic objects and regions](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/kinematic-and-regions/). Every name on this page is in
`deformable::scene`, unless the page says otherwise. The full list of items, with every signature, is in the
[scene reference](https://help.tangerina.io/deformable/v0.2.1/api-references/rust/scene/).

The examples on this page use the `cuboid` and `solid` helpers from
[Getting started](https://help.tangerina.io/deformable/v0.2.1/user-guides/rust/getting-started/#helpers-for-the-other-pages). Save them as `src/shapes.rs`
next to each example.

## The frame loop

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

```rust
mod shapes;

use std::collections::BTreeSet;

use deformable::math::Vector3;
use deformable::scene::{DrivenVertex, MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let floor_mesh = solid(&cuboid(Vector3::new(-3.0, -0.5, -3.0), Vector3::new(3.0, 0.0, 3.0)), 1.0, 1.0)?;
    let cube_mesh = solid(&cuboid(Vector3::new(-0.5, 2.0, -0.5), Vector3::new(0.5, 3.0, 0.5)), 0.05, 0.3)?;

    let mut scene = Scene::new();
    let stone = scene.add_material(&MaterialParameters::preset("stone").ok_or("no stone preset")?)?;
    let glass = scene.add_material(&MaterialParameters::preset("glass").ok_or("no glass preset")?)?;

    // The floor is driven: each node is held at its rest position.
    let floor = scene.add_object(&floor_mesh, TetrahedronMaterials::Uniform(stone), ObjectOptions::default())?;
    let held: Vec<DrivenVertex> = (0..)
        .zip(&floor_mesh.positions)
        .map(|(vertex, &target)| DrivenVertex { vertex, target })
        .collect();
    scene.drive(floor, &held)?;
    let cube = scene.add_object(&cube_mesh, TetrahedronMaterials::Uniform(glass), ObjectOptions::default())?;

    let mut fractured = BTreeSet::new();
    for frame in 0..49 {
        scene.step(f64::from(frame) / 24.0, 10, None)?;
        fractured.extend(scene.face_events(cube)?.iter().map(|event| event.tetrahedron));
    }

    let mut positions = Vec::new();
    scene.node_positions(cube, &mut positions)?;
    println!("rest nodes: {}", cube_mesh.positions.len());
    println!("nodes now: {}", positions.len());
    println!("fractured tetrahedrons: {}", fractured.len());
    Ok(())
}
```

```text
rest nodes: 145
nodes now: 342
fractured tetrahedrons: 398
```

Fracture splits nodes, so the cube ends with more nodes than it started with. The tetrahedron count stays the same.

## Create a scene

```rust
let mut scene = Scene::new();
```

A new scene has 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. `Scene::default()` is the same.

Change them with these methods:

- `set_scale(scale)` sets the factor from your length unit to simulation units, from 0.001 to 1,000; see
  [Scale](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/simulation-settings/#scale). For a scene
  modelled in centimetres, call `set_scale(0.01)`. It applies to later calls; stored state is not rescaled.
- `set_gravity(gravity)` sets the gravity, in simulation units. The scale does not apply to it. For a z-up scene,
  pass `Vector3::new(0.0, 0.0, -9.81)`.
- `set_worker_count(count)` sets the number of threads, at least 1, the calling thread included. The results do not
  depend on it.

The scale multiplies positions, driven targets and glue plane offsets on the way in. It divides positions and
velocities on the way out. Time, forces, gravity, node masses and material values pass unscaled.

## Materials

### Material values

A `MaterialParameters` is a plain struct with the ten values of one material. All fields are `f64`, in simulation
units. What each value does, and how to make a material elastic, plastic or breakable, is on
[Materials](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/materials/#the-ten-values).

| Field | Default | Clamp | Meaning |
|---|---|---|---|
| `youngs_modulus` | 8e5 | [1e3, 1e10] | Young's modulus E, in pascals. Higher is stiffer. |
| `poissons_ratio` | 0 | [-0.90001, 0.490001] | Poisson's ratio, unitless. |
| `density` | 2500 | [0, 1e4] | Mass per unit volume. A tetrahedron weighs density times its volume. |
| `toughness` | 2e5 | [0, 1e8] | Fracture threshold. 0 or less means unbreakable. |
| `youngs_damping` | 0 | [0, 1e9] | Stiffness-proportional damping. The damping factor is youngs_damping / youngs_modulus. |
| `yield_strain` | 0 | [0, 1] | Plastic flow starts when the elastic strain norm exceeds this. |
| `maximum_yield` | 0 | [0, 1] | Upper bound on the plastic strain norm. 0 resets the plastic strain every solve. |
| `creep_fraction` | 0 | [0, 1] | Fraction of the elastic strain added to the plastic strain once per solve, while its norm exceeds `yield_strain`. 0 disables plasticity. |
| `wake_up_radius` | 1.2 | [1, 1000] | Radius around an impact that wakes sleeping tetrahedrons of an object that has glue; on an object without glue, an impact wakes the whole piece it hits. See [Sleep](https://help.tangerina.io/deformable/v0.2.1/user-guides/rust/scene/#sleep). |
| `friction` | 0.6 | [0, 1] | Coulomb friction coefficient. Two touching materials use the smaller value. |

`MaterialParameters::default()` gives the defaults above. `add_material` clamps each value to its range, and values
keep full double precision. To change a few fields, use struct update syntax:
`MaterialParameters { density: 7800.0, ..MaterialParameters::default() }`.

### Use a preset

The library ships the 43 presets of [Materials](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/materials/#the-presets), which lists them
with their values. `MaterialParameters::preset(name)` returns the preset with that name, or `None`. The name must match
exactly, case included. `MaterialParameters::presets()` lists every preset, in the library's order, each as a
`MaterialPreset` with a `name` and its `parameters`.

Every preset value lies inside its clamp range.

```rust
use deformable::scene::MaterialParameters;

fn main() {
    let presets = MaterialParameters::presets();
    println!("{} presets, from {} to {}", presets.len(), presets[0].name, presets[presets.len() - 1].name);

    let rubber = MaterialParameters::preset("rubber").expect("rubber is a preset");
    let heavy = MaterialParameters { density: 7800.0, toughness: 0.0, ..MaterialParameters::default() };
    println!("{} {} {:?}", rubber.youngs_modulus, heavy.density, MaterialParameters::preset("Steel"));
}
```

```text
43 presets, from sponge to iron
970000 7800 None
```

### Add and change a material

`add_material(&parameters)` creates a material and returns its `MaterialHandle`. Handles count up from 0. A NaN or
infinite value gives an error of kind `ErrorKind::NonFiniteValue`.

`set_material(material, &parameters)` rewrites a material later. The objects that use it take the new values before
the next step's substeps. A new density changes the lumped node masses then too, and the velocities stay as they were.

## Objects

### Add an object

`add_object(&mesh, materials, options)` creates an object from a tetrahedral mesh and returns its `ObjectHandle`.
Object handles count up from 0 in creation order.

- `mesh`: a `TetrahedralMesh`. Positions are in world space and your length unit. Tetrahedrons must be positively
  oriented, as the tools make them, though a thick `extrude` shell can invert some where the mesh curves sharply.
- `materials`: `TetrahedronMaterials::Uniform(handle)` gives every tetrahedron one material.
  `TetrahedronMaterials::PerTetrahedron(&handles)` gives one handle per tetrahedron, in mesh order.
- `options`: an `ObjectOptions`. `ObjectOptions::default()` turns `self_collision` on, so the object's faces collide
  with each other, and `disabled` off. For example, `ObjectOptions { self_collision: false,
  ..ObjectOptions::default() }` turns self-collision off.

The mesh is checked before anything is created. A mesh with no tetrahedron, a NaN position, an index past the
positions, a face shared by three tetrahedrons, or a tetrahedron that is too small, flat or inverted is refused. The
error's kind names the problem. For `DegenerateTetrahedron`, its first index names the first tetrahedron that fails.
[Errors and threads](https://help.tangerina.io/deformable/v0.2.1/user-guides/rust/errors/) shows how to handle it.

### Change an object

After you add an object, you can:

- give it new materials with `set_object_material(object, materials)`, before the next step's substeps. It rebuilds
  the object's islands and wakes nothing;
- turn it off and on with `set_object_disabled(object, disabled)`. A disabled object keeps its outputs and ignores
  forces; its driving waits until it is enabled. A re-enabled object keeps its stored node state;
- turn self-collision off or on with `set_self_collision(object, enabled)`;
- keep a node, and the part around it, from ever sleeping with `set_never_sleep(object, node, true)`. See
  [Sleep](#sleep);
- delete it with `remove_object(object)`. Its contacts and glue are freed.

Each method returns `Result<(), Error>`. An unknown or removed object gives `ErrorKind::UnknownObject` in every
method that takes one.

### Material regions

A [material region](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/kinematic-and-regions/#material-regions) gives the tetrahedrons
inside a convex polyhedron their own material.

`material_region_indices(&mesh, &regions)` returns one value per tetrahedron of `mesh`: 0 when no region holds the
tetrahedron's centroid, or k + 1 for the first region k that holds it. Regions are tried from the smallest volume up.
A region polygon with fewer than 3 corners or a zero normal gives `ErrorKind::DegenerateRegion`, with the region as
the error's first index and the polygon as its second.

A `MaterialRegion` has two fields:

- `mesh`: a `PolygonMesh` in the region's own space, normally a closed convex polyhedron with outward faces.
- `to_mesh_space`: 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.

```rust
mod shapes;

use deformable::math::{AffineTransform, Vector3};
use deformable::scene::{
    MaterialHandle, MaterialParameters, MaterialRegion, ObjectOptions, Scene, TetrahedronMaterials,
    material_region_indices,
};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cube_mesh = solid(&cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0)), 0.05, 0.3)?;
    let left_half = MaterialRegion {
        mesh: cuboid(Vector3::ZERO, Vector3::new(0.5, 1.0, 1.0)),
        to_mesh_space: AffineTransform::IDENTITY,
    };
    let indices = material_region_indices(&cube_mesh, &[left_half])?;

    let mut scene = Scene::new();
    let wood = scene.add_material(&MaterialParameters::preset("wood").ok_or("no wood preset")?)?;
    let steel = scene.add_material(&MaterialParameters::preset("steel").ok_or("no steel preset")?)?;
    let materials: Vec<MaterialHandle> = indices.iter().map(|&index| if index == 1 { steel } else { wood }).collect();
    scene.add_object(&cube_mesh, TetrahedronMaterials::PerTetrahedron(&materials), ObjectOptions::default())?;

    let in_region = indices.iter().filter(|&&index| index == 1).count();
    println!("{in_region} of {} tetrahedrons are steel", indices.len());
    Ok(())
}
```

```text
223 of 471 tetrahedrons are steel
```

## Drive vertices

A driven vertex follows a path you give instead of the simulation; see
[Driven vertices and forces](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/kinematic-and-regions/#driven-vertices-and-forces). A
`DrivenVertex` has a `vertex: u32`, an index into the object's nodes, and a `target: Vector3` in your length unit.

`drive(object, &vertices)` drives the listed vertices toward their targets from the next step on. The targets 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. `drive(object, &[])` releases them all.

- A floor or a wall that never moves is an object whose every node is driven to its rest position, once. The
  [frame loop](#the-frame-loop) does this.
- To animate an object, call `drive` before each `step` with the targets for the end of that step.
- To throw an object, drive it for a few frames, then release it. It keeps the speed it was driven at.

![A cube moves in equal steps while its nodes are driven to their targets, then keeps the same speed after it is released.](https://help.tangerina.io/deformable/v0.2.1/images/sdk-drive-then-release.svg)

This example drives a cube along x at 2.4 units per second for half a second, with no gravity, then releases it.
A driven node reports zero velocity, so the example prints the cube's centre while it is driven, and its velocity
once it is free:

```rust
mod shapes;

use deformable::math::Vector3;
use deformable::scene::{DrivenVertex, MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cube_mesh = solid(&cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0)), 0.05, 0.3)?;
    let mut scene = Scene::new();
    scene.set_gravity(Vector3::ZERO)?;
    let rubber = scene.add_material(&MaterialParameters::preset("rubber").ok_or("no rubber preset")?)?;
    let cube = scene.add_object(&cube_mesh, TetrahedronMaterials::Uniform(rubber), ObjectOptions::default())?;

    let mut positions = Vec::new();
    let mut velocities = Vec::new();
    for frame in 0..=24 {
        if frame <= 12 {
            // Driven: 0.1 units further along x each frame.
            let offset = Vector3::new(0.1 * f64::from(frame), 0.0, 0.0);
            let targets: Vec<DrivenVertex> = (0..)
                .zip(&cube_mesh.positions)
                .map(|(vertex, &position)| DrivenVertex { vertex, target: position + offset })
                .collect();
            scene.drive(cube, &targets)?;
        } else if frame == 13 {
            // Released: every vertex keeps its last driven velocity.
            scene.drive(cube, &[])?;
        }
        scene.step(f64::from(frame) / 24.0, 10, None)?;
        if frame % 6 == 0 {
            scene.node_positions(cube, &mut positions)?;
            scene.node_velocities(cube, &mut velocities)?;
            let count = positions.len() as f64;
            let centre = positions.iter().map(|position| position.x).sum::<f64>() / count;
            let speed = velocities.iter().map(|velocity| velocity.x).sum::<f64>() / count;
            println!("frame {frame}: centre x {centre:.2}, velocity x {speed:.2}");
        }
    }
    Ok(())
}
```

```text
frame 0: centre x 0.50, velocity x 0.00
frame 6: centre x 1.10, velocity x 0.00
frame 12: centre x 1.70, velocity x 0.00
frame 18: centre x 2.30, velocity x 2.40
frame 24: centre x 2.90, velocity x 2.40
```

While it is driven, the cube moves exactly 0.1 units per frame. Once released at frame 13, it keeps going at the 2.4
units per second it was driven at.

## Add forces

`add_force(object, 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.
Several calls on one node add up. A node index past the object's nodes gives
`ErrorKind::IndexOutOfRange`, and a NaN or infinite force gives `ErrorKind::NonFiniteValue`.

To apply a force field, read `node_positions`, `node_velocities` and `node_masses`, compute the forces, and queue
them before each step. This field lifts every node with its own weight, so the cube floats:

```rust
mod shapes;

use deformable::math::Vector3;
use deformable::scene::{MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cube_mesh = solid(&cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0)), 0.05, 0.3)?;

    for lifted in [false, true] {
        let mut scene = Scene::new();
        let material = scene.add_material(&MaterialParameters::default())?;
        let cube = scene.add_object(&cube_mesh, TetrahedronMaterials::Uniform(material), ObjectOptions::default())?;

        let mut masses = Vec::new();
        for frame in 0..=24 {
            if lifted {
                scene.node_masses(cube, &mut masses)?;
                for (node, mass) in (0..).zip(&masses) {
                    scene.add_force(cube, node, Vector3::new(0.0, 9.81 * mass, 0.0))?;
                }
            }
            scene.step(f64::from(frame) / 24.0, 10, None)?;
        }

        let mut positions = Vec::new();
        scene.node_positions(cube, &mut positions)?;
        let centre = positions.iter().map(|position| position.y).sum::<f64>() / positions.len() as f64;
        println!("lifted: {lifted}, centre y after 1 s: {centre:.2}");
    }
    Ok(())
}
```

```text
lifted: false, centre y after 1 s: -4.41
lifted: true, centre y after 1 s: 0.51
```

Without the field, the cube falls about 4.9 units in one second. With it, the cube floats near where it
started, with its centre at y = 0.5.

## Glue objects together

Glue holds objects together where their tetrahedrons overlap, with a spring and a damper; see
[Glue regions](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/kinematic-and-regions/#glue-regions). The damper resists only
motion relative to the other object, so an object glued to a driven one rides along with it.

`GlueParameters` has a `spring_constant` and a `damping_coefficient`, both `f64`. A value of 0 takes the library's
default: 4,905 for the spring constant, 2,452.5 for the damping coefficient.

- `set_glue_all(Some(parameters))` glues, from the next glue pass on, each new object to every other enabled object
  where they overlap. `None` turns it off, as in a new scene.
- `add_glue_region(region, &members, parameters)` glues each new member to every other enabled member, through their
  tetrahedrons with a vertex inside the `ConvexRegion`. Plane offsets are in your length unit. An unknown member gives
  `ErrorKind::UnknownObject`.

Glue applies to the objects added since the last step that advanced the time with at least one substep, and that step
makes it. Add the objects first, then call `set_glue_all` or `add_glue_region` before that step. The first `step` call
only records the time, and a call with no time elapsed or with 0 substeps runs no substep, so none of them makes
glue. A NaN or infinite glue value or plane gives `ErrorKind::NonFiniteValue`.

A `ConvexRegion` holds `planes: Vec<Plane>`. Its inside is the set of points inside every plane; with no plane it
holds every point. A `Plane` has a `normal: Vector3` and an `offset: f64`: the inside is `normal · p + offset <= 0`,
and the normal can have any length. `ConvexRegion::contains(point)` runs the same inside test the library runs.

This example hangs a block under a held one. The two overlap by 0.02 units. Without glue the lower block falls;
with glue it hangs:

```rust
mod shapes;

use deformable::math::Vector3;
use deformable::scene::{
    DrivenVertex, GlueParameters, MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials,
};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let upper_mesh = solid(&cuboid(Vector3::new(0.0, 1.0, 0.0), Vector3::new(1.0, 2.0, 1.0)), 0.05, 0.3)?;
    let lower_mesh = solid(&cuboid(Vector3::new(0.0, 0.02, 0.0), Vector3::new(1.0, 1.02, 1.0)), 0.05, 0.3)?;

    for glued in [false, true] {
        let mut scene = Scene::new();
        let wood = scene.add_material(&MaterialParameters::preset("wood").ok_or("no wood preset")?)?;
        let upper = scene.add_object(&upper_mesh, TetrahedronMaterials::Uniform(wood), ObjectOptions::default())?;
        let held: Vec<DrivenVertex> = (0..)
            .zip(&upper_mesh.positions)
            .map(|(vertex, &target)| DrivenVertex { vertex, target })
            .collect();
        scene.drive(upper, &held)?;
        let lower = scene.add_object(&lower_mesh, TetrahedronMaterials::Uniform(wood), ObjectOptions::default())?;
        if glued {
            scene.set_glue_all(Some(GlueParameters { spring_constant: 0.0, damping_coefficient: 0.0 }))?;
        }

        for frame in 0..=24 {
            scene.step(f64::from(frame) / 24.0, 10, None)?;
        }
        let mut positions = Vec::new();
        scene.node_positions(lower, &mut positions)?;
        let lowest = positions.iter().map(|position| position.y).fold(f64::INFINITY, f64::min);
        println!("glued: {glued}, lowest node of the lower block after 1 s: {lowest:.2}");
    }
    Ok(())
}
```

```text
glued: false, lowest node of the lower block after 1 s: -5.47
glued: true, lowest node of the lower block after 1 s: 0.02
```

Glue needs an overlap: two objects that only touch are not glued.

## Step the scene

`step(time, substeps, cancel)` advances the scene to `time`, in seconds, in `substeps` equal substeps. Call it once
per frame with the frame's time. `cancel` is `None`, or `Some(&flag)` with a `CancelFlag`.

- The first call only records the time. Start your loop at the start frame, so the first frame shows the rest pose.
- A time before the last step's time gives `ErrorKind::TimeWentBackwards`. 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. 10 is a good start. See [Substeps](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/simulation-settings/#substeps).
- A cancel flag set from another thread stops the step between two substeps. See
  [Cancel a step](#cancel-a-step).

![A time line of three frames: the first call at frame 0 only records the time, and each later step runs 10 equal substeps up to its frame.](https://help.tangerina.io/deformable/v0.2.1/images/sdk-frames-and-substeps.svg)

### Read the step's outcome

`step` returns a `StepReport`. It has `substeps_run: u32`, the number of substeps simulated, and `outcome: StepOutcome`.

| `StepOutcome` | Meaning |
|---|---|
| `Stepped` | The substeps ran. |
| `FirstCall` | The first call only recorded the time. |
| `NoTimeElapsed` | The time equals the last time. Nothing was stepped, and the queued forces are used up. |
| `NoSubsteps` | Zero substeps were asked for. The time advanced without a step. |
| `SubstepTooLarge` | The substep would exceed 0.04 seconds. The time advanced without a step. |
| `Cancelled` | The cancel flag stopped the step after `substeps_run` substeps. |

### Pause a scene

`skip_to(time)` records `time` as the last time without stepping, and drops the queued forces. Use it to pause a scene:
the next `step` goes on from `time` as if no time had passed. Before the first `step`, `skip_to` records nothing, so the
next `step` is still a first call.

This example shows each outcome, and a pause:

```rust
mod shapes;

use deformable::math::Vector3;
use deformable::scene::{MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cube_mesh = solid(&cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0)), 0.05, 0.3)?;
    let mut scene = Scene::new();
    let material = scene.add_material(&MaterialParameters::default())?;
    scene.add_object(&cube_mesh, TetrahedronMaterials::Uniform(material), ObjectOptions::default())?;

    let frame = |index: u32| f64::from(index) / 24.0;
    println!("{:?}", scene.step(frame(0), 10, None)?);
    println!("{:?}", scene.step(frame(0), 10, None)?);
    println!("{:?}", scene.step(frame(1), 0, None)?);
    println!("{:?}", scene.step(frame(2), 1, None)?);
    println!("{:?}", scene.step(frame(3), 10, None)?);

    // Pause for two frames: frame 6 goes on from frame 5.
    scene.skip_to(frame(5))?;
    println!("{:?}", scene.step(frame(6), 10, None)?);
    println!("{:?}", scene.step(frame(4), 10, None).map_err(|error| error.kind()));
    Ok(())
}
```

```text
StepReport { substeps_run: 0, outcome: FirstCall }
StepReport { substeps_run: 0, outcome: NoTimeElapsed }
StepReport { substeps_run: 0, outcome: NoSubsteps }
StepReport { substeps_run: 0, outcome: SubstepTooLarge }
StepReport { substeps_run: 10, outcome: Stepped }
StepReport { substeps_run: 10, outcome: Stepped }
Err(TimeWentBackwards)
```

The first call records the time. A call at the same time does nothing, and a call with 0 substeps or with a substep
over 0.04 seconds only moves the time on. After `skip_to`, the step from frame 5 to frame 6 runs its 10 substeps
over one frame, not three. A time before the last one is an error of kind `TimeWentBackwards`.

### Cancel a step

A step stops at the next substep once another thread sets the flag. It runs at least one substep, and the time then
stands at the last substep run, so the next `step` goes on from there. A `CancelFlag` is `Sync`, so the other thread
sets it through a shared reference.

```rust
mod shapes;

use std::thread;
use std::time::Duration;

use deformable::CancelFlag;
use deformable::math::Vector3;
use deformable::scene::{MaterialParameters, ObjectOptions, Scene, StepOutcome, TetrahedronMaterials};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cube_mesh = solid(&cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0)), 0.05, 0.3)?;
    let mut scene = Scene::new();
    let material = scene.add_material(&MaterialParameters::default())?;
    scene.add_object(&cube_mesh, TetrahedronMaterials::Uniform(material), ObjectOptions::default())?;

    let cancel = CancelFlag::new();
    scene.step(0.0, 10, None)?;
    let report = thread::scope(|scope| {
        scope.spawn(|| {
            thread::sleep(Duration::from_millis(10));
            cancel.set(true);
        });
        // Ten seconds in 1000 substeps: far longer than 10 milliseconds.
        scene.step(10.0, 1000, Some(&cancel))
    })?;
    println!("{:?} {}", report.outcome, report.substeps_run < 1000);
    assert_eq!(report.outcome, StepOutcome::Cancelled);
    Ok(())
}
```

```text
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](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/simulation-settings/#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, 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:

```rust
mod shapes;

use deformable::math::Vector3;
use deformable::scene::{DrivenVertex, MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let floor_mesh = solid(&cuboid(Vector3::new(-3.0, -0.5, -3.0), Vector3::new(3.0, 0.0, 3.0)), 1.0, 1.0)?;
    let cube_mesh = solid(&cuboid(Vector3::new(-0.5, 0.0, -0.5), Vector3::new(0.5, 1.0, 0.5)), 0.05, 0.3)?;

    for never_sleep in [false, true] {
        let mut scene = Scene::new();
        let stone = scene.add_material(&MaterialParameters::preset("stone").ok_or("no stone preset")?)?;
        let glass = scene.add_material(&MaterialParameters::preset("glass").ok_or("no glass preset")?)?;
        let floor = scene.add_object(&floor_mesh, TetrahedronMaterials::Uniform(stone), ObjectOptions::default())?;
        let held: Vec<DrivenVertex> = (0..)
            .zip(&floor_mesh.positions)
            .map(|(vertex, &target)| DrivenVertex { vertex, target })
            .collect();
        scene.drive(floor, &held)?;
        let cube = scene.add_object(&cube_mesh, TetrahedronMaterials::Uniform(glass), ObjectOptions::default())?;
        if never_sleep {
            scene.set_never_sleep(cube, 0, true)?;
        }

        let mut counts = Vec::new();
        for frame in 0..=120 {
            scene.step(f64::from(frame) / 24.0, 10, None)?;
            if frame % 24 == 0 {
                counts.push(scene.awake_tetrahedron_count());
            }
        }
        println!("never sleep: {never_sleep}, awake each second: {counts:?}");
    }
    Ok(())
}
```

```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.

## Determinism

The same inputs and the same calls give bitwise identical results, run to run, on any thread, and for any worker count,
as [Repeatable results](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/simulation-settings/#repeatable-results) says for every
interface. The worker count changes only the speed. So you can replay a simulation exactly, or compare two runs bit for
bit:

```rust
mod shapes;

use deformable::math::Vector3;
use deformable::scene::{DrivenVertex, MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let floor_mesh = solid(&cuboid(Vector3::new(-3.0, -0.5, -3.0), Vector3::new(3.0, 0.0, 3.0)), 1.0, 1.0)?;
    let cube_mesh = solid(&cuboid(Vector3::new(-0.5, 2.0, -0.5), Vector3::new(0.5, 3.0, 0.5)), 0.05, 0.3)?;

    let mut runs = Vec::new();
    for workers in [1, 4] {
        let mut scene = Scene::new();
        scene.set_worker_count(workers)?;
        let stone = scene.add_material(&MaterialParameters::preset("stone").ok_or("no stone preset")?)?;
        let glass = scene.add_material(&MaterialParameters::preset("glass").ok_or("no glass preset")?)?;
        let floor = scene.add_object(&floor_mesh, TetrahedronMaterials::Uniform(stone), ObjectOptions::default())?;
        let held: Vec<DrivenVertex> = (0..)
            .zip(&floor_mesh.positions)
            .map(|(vertex, &target)| DrivenVertex { vertex, target })
            .collect();
        scene.drive(floor, &held)?;
        let cube = scene.add_object(&cube_mesh, TetrahedronMaterials::Uniform(glass), ObjectOptions::default())?;
        for frame in 0..49 {
            scene.step(f64::from(frame) / 24.0, 10, None)?;
        }
        let mut positions = Vec::new();
        scene.node_positions(cube, &mut positions)?;
        runs.push(positions);
    }
    // Compare the bits, not only the values.
    let bits = |positions: &[Vector3]| positions.iter().flat_map(|position| position.to_array().map(f64::to_bits)).collect::<Vec<_>>();
    println!("identical: {}", bits(&runs[0]) == bits(&runs[1]));
    Ok(())
}
```

```text
identical: true
```

## Read the outputs

Most output methods fill a vector you pass in, after clearing it. Reuse the same vectors every frame.

- `node_positions(object, &mut positions)` and `node_velocities(object, &mut velocities)`: one `Vector3` per node,
  in your length unit and your length unit per second. Fracture adds nodes, so the lists can grow.
- `node_masses(object, &mut masses)`: the lumped mass of each node, in simulation units, driven nodes included.
- `tetrahedron_nodes(object, &mut nodes)`: the current four nodes of each tetrahedron, in mesh order.
- `tetrahedron_states(object, &mut states)`: one `TetrahedronState` per tetrahedron, in mesh order, with its corner
  positions, its island, a strain measure and flags.
- `face_events(object)`: a slice with one `FaceEvent` per tetrahedron that fracture changed in the last step. The
  slice is the library's own buffer, so it borrows the scene mutably until you drop it.
- `awake_tetrahedron_count()` and `statistics()`: counters for the whole scene.

The tetrahedron count of an object never changes; its node count grows as it breaks. To draw a broken object, read
`node_positions` and `tetrahedron_nodes` together, or skin a render surface with
[Render surfaces](https://help.tangerina.io/deformable/v0.2.1/user-guides/rust/render-surfaces/).

![Two tetrahedrons that share a face and 5 nodes break apart along that face; they are still 2 tetrahedrons, now with 8 nodes, and the opened face shows.](https://help.tangerina.io/deformable/v0.2.1/images/sdk-fracture-splits-nodes.svg)

### Find the faces a crack opened

A `FaceEvent` has `tetrahedron`, the index in the object's mesh, and `exposed_faces`, with bit k set when face k,
opposite corner k, is shared with no other tetrahedron. Faces on the rest boundary count as exposed;
`deformable::mesh::boundary_faces(&mesh)` gives that rest mask, so `exposed_faces & !boundary[tetrahedron]`
keeps only the faces a fracture opened.

`TetrahedronState::face_centroid(face)` and `face_normal(face)` place a point and an outward unit normal on face `face`,
0 to 3; they return `None` for a face above 3, and a face of zero area has a zero normal. Use them to place debris or
particles on new faces, as the plugins'
[fracture points](https://help.tangerina.io/deformable/v0.2.1/user-guides/engine/fracture-and-splinters/#fracture-points) do. The other fields and the
flag bits of `TetrahedronState` are on the [scene reference](https://help.tangerina.io/deformable/v0.2.1/api-references/rust/scene/#tetrahedronstate).

This example counts the faces the glass cube's fracture opens, and finds the lowest of them:

```rust
mod shapes;

use deformable::math::Vector3;
use deformable::mesh::boundary_faces;
use deformable::scene::{DrivenVertex, MaterialParameters, ObjectOptions, Scene, TetrahedronMaterials};
use shapes::{cuboid, solid};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let floor_mesh = solid(&cuboid(Vector3::new(-3.0, -0.5, -3.0), Vector3::new(3.0, 0.0, 3.0)), 1.0, 1.0)?;
    let cube_mesh = solid(&cuboid(Vector3::new(-0.5, 2.0, -0.5), Vector3::new(0.5, 3.0, 0.5)), 0.05, 0.3)?;
    let boundary = boundary_faces(&cube_mesh)?;

    let mut scene = Scene::new();
    let stone = scene.add_material(&MaterialParameters::preset("stone").ok_or("no stone preset")?)?;
    let glass = scene.add_material(&MaterialParameters::preset("glass").ok_or("no glass preset")?)?;
    let floor = scene.add_object(&floor_mesh, TetrahedronMaterials::Uniform(stone), ObjectOptions::default())?;
    let held: Vec<DrivenVertex> = (0..)
        .zip(&floor_mesh.positions)
        .map(|(vertex, &target)| DrivenVertex { vertex, target })
        .collect();
    scene.drive(floor, &held)?;
    let cube = scene.add_object(&cube_mesh, TetrahedronMaterials::Uniform(glass), ObjectOptions::default())?;

    let mut states = Vec::new();
    let mut opened = 0;
    let mut lowest = f64::INFINITY;
    for frame in 0..49 {
        scene.step(f64::from(frame) / 24.0, 10, None)?;
        scene.tetrahedron_states(cube, &mut states)?;
        for event in scene.face_events(cube)? {
            let tetrahedron = event.tetrahedron as usize;
            let new_faces = event.exposed_faces & !boundary[tetrahedron];
            for face in (0..4).filter(|face| new_faces >> face & 1 == 1) {
                opened += 1;
                let centroid = states[tetrahedron].face_centroid(face).ok_or("no such face")?;
                lowest = lowest.min(centroid.y);
            }
        }
    }
    println!("{opened} faces opened, the lowest at y = {lowest:.2}");
    println!("{:?}", scene.statistics());
    Ok(())
}
```

```text
530 faces opened, the lowest at y = 0.04
SceneStatistics { systems: 482, conjugate_gradient_updates: 24213, contacts: 3019, islands: 13 }
```

A face can open in one step and be reported again in a later one, when a later fracture changes its tetrahedron
again. Keep a set of the faces you have seen if you need each one once.

### Measure a scene

`statistics()` returns a `SceneStatistics`, the counters the example above prints:

- `systems`: linear systems solved so far: one per contact island, and one per awake island outside every contact
  island, per substep.
- `conjugate_gradient_updates`: conjugate gradient updates, summed over every solve so far.
- `contacts`: live contacts, glue contacts included.
- `islands`: islands, awake and asleep.

## Next steps

- [Tools](https://help.tangerina.io/deformable/v0.2.1/user-guides/rust/tools/): build tetrahedral meshes from your polygons.
- [Render surfaces](https://help.tangerina.io/deformable/v0.2.1/user-guides/rust/render-surfaces/): skin the artist's mesh on the simulated object.
- [Scene reference](https://help.tangerina.io/deformable/v0.2.1/api-references/rust/scene/): every item of the module, with its signature.
