You are viewing the documentation for Deformable v0.3.1, an older version. Read the latest, v0.9.0
Rust SDK
Render surfaces
Embed a render mesh in an object's rest tetrahedral mesh, then skin it on the simulated object every frame, cracks and splinters included.
On this page
embed_surface prepares a render surface, the artist’s polygon mesh with its normals, UVs and colours, against the
object’s rest tetrahedral mesh once. Then, every frame, SurfaceEmbedding::deform moves it with the tetrahedrons. What
a render surface keeps, the clip modes, and how inner faces and splinters show where an object breaks are on
Render surfaces in the Engine guide; this page shows the calls.
embed_surface, SurfaceEmbedding, SkinningOptions and DeformedSurface are in deformable::scene, and
SurfaceMesh, PreparationParameters, ClipMode and CornerFlags are in deformable::tools. The
render surfaces reference lists them with every signature, except
SurfaceMesh, which is on the meshes reference.
The examples on this page use the cuboid and solid helpers from
Getting started. Save them as src/shapes.rs
next to each example.
The flow
- Build the object’s tetrahedral mesh with the tools.
- Call
embed_surface(&rest, &surface, ¶meters)with the rest mesh and the render surface. Keep the returnedSurfaceEmbeddingfor the life of the object. - Read the prepared surface once with
embedding.surface(). Its polygons and per-corner channels never change. - After each
Scene::step, read the object’stetrahedron_states, callembedding.deformwith them, and write the new positions, normals and hidden faces to your mesh.
This example drops a glass cube onto a floor and skins its surface every frame:
mod shapes;
use deformable::math::{AffineTransform, Vector2, Vector3};
use deformable::scene::{
DeformedSurface, DrivenVertex, MaterialParameters, ObjectOptions, Scene, SkinningOptions,
TetrahedronMaterials, embed_surface,
};
use deformable::tools::{ClipMode, PreparationParameters, SurfaceMesh};
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_polygons = cuboid(Vector3::new(-0.5, 2.0, -0.5), Vector3::new(0.5, 3.0, 0.5));
let cube_mesh = solid(&cube_polygons, 0.05, 0.3)?;
// One flat normal and one UV per corner, in the order of the box's six quads.
let face_normals = [-Vector3::Z, Vector3::Z, -Vector3::Y, Vector3::Y, -Vector3::X, Vector3::X];
let normals = face_normals.iter().flat_map(|&normal| [normal; 4]).collect();
let square = [Vector2::new(0.0, 0.0), Vector2::new(1.0, 0.0), Vector2::new(1.0, 1.0), Vector2::new(0.0, 1.0)];
let uvs = square.repeat(6);
let surface = SurfaceMesh { mesh: cube_polygons, normals, uv_sets: vec![uvs], ..SurfaceMesh::default() };
let parameters = PreparationParameters { clip_mode: ClipMode::ClipWithInnerFaces, uv_scale: 1.0, splinter_cage: None };
let embedding = embed_surface(&cube_mesh, &surface, ¶meters)?;
let prepared = &embedding.surface().mesh;
println!("prepared: {} vertices, {} faces", prepared.positions.len(), prepared.polygon_sizes.len());
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 deformed = DeformedSurface::default();
for frame in 0..49 {
scene.step(f64::from(frame) / 24.0, 10, None)?;
scene.tetrahedron_states(cube, &mut states)?;
embedding.deform(&states, &AffineTransform::IDENTITY, SkinningOptions::default(), &mut deformed)?;
if frame % 24 == 0 {
let hidden = deformed.hidden_faces.iter().filter(|&&hidden| hidden).count();
println!("frame {frame}: {hidden} hidden faces");
}
}
Ok(())
}prepared: 5556 vertices, 1852 faces
frame 0: 1638 hidden faces
frame 24: 1198 hidden faces
frame 48: 1194 hidden facesThe cube lands and breaks. Of its 1,638 inner faces, 440 show along the cracks by frame 24.
Describe the render surface
A SurfaceMesh is a polygon mesh with optional per-corner channels. Each channel is empty or holds one entry per
corner, in the order of mesh.polygon_vertices. SurfaceMesh::default() has every field empty.
mesh: the positions and the polygons, aPolygonMesh.normals: one normal per corner. The artist’s normals are kept: the library never invents one.uv_sets: UV sets, each with oneVector2per corner.colours: one red, green, blue and alpha colour per corner.
The surface does not have to match the cage you meshed. Points outside the rest mesh are extrapolated from a nearby tetrahedron.
Choose how to prepare it
embed_surface(&rest, &surface, ¶meters) prepares a render surface against a rest tetrahedral mesh, then embeds
each vertex in a tetrahedron by barycentric weights. rest is the mesh you pass to add_object, and surface is in
the same space. PreparationParameters has three fields:
clip_mode: how the surface is prepared. See the table below.uv_scale: the scale of the planar UVs made for inner faces and splinter caps. 1 is a good start.splinter_cage:None, orSome(&cage), a splinter cage in the surface’s space. WithClipWithInnerFaces, the surface breaks into these splinters. See Splinters.
Which clip mode suits which object is on Clip modes.
Clip |
What the call makes |
|---|---|
Assign |
Each vertex follows the tetrahedron it lies in. Nothing is cut and no inner face is made. |
Clip |
The surface is cut along the tetrahedron faces. The part of each interior face inside the solid becomes an inner face, hidden until a crack opens it. |
Tetrahedral |
The tetrahedral mesh is the surface: each polygon follows the tetrahedron its centre lies in, uncut, and every interior face becomes an inner face. |
The prepared surface keeps every channel the input has. Inner faces are opaque white when the surface has colours,
and get planar UVs at a random rotation and offset, scaled by uv_scale. The random
stream has a fixed seed, so the same input always gives the same UVs.
Malformed input gives an Error. For example, the kind LengthMismatch means the polygon sizes do not add up to
the corner count, or a channel has neither zero entries nor one per corner. NonFiniteValue means a position, a
channel value or the UV scale is NaN or infinite. Errors and threads shows how
to read the kind.
Read the prepared surface
embed_surface returns a SurfaceEmbedding: the prepared surface in rest space. It owns its data inside the
library and frees it when you drop it. It is Send and Sync, and skinning never changes it, so several threads can
skin one embedding at the same time. Keep it for the life of the object.
surface()returns the preparedSurfaceMesh: output vertices, polygons and per-corner channels. Build your render mesh’s topology from it once.source_faces()gives the input face each output face was cut from, or -1 for inner and cap faces. Use it to keep per-face materials, and give the -1 faces your inner material.corner_flags()gives oneCornerFlagsword per corner. Its methodstetrahedron(),face()andis_inner()read the corner’s tetrahedron, the tetrahedron face of an inner face, and whether the corner is on an inner face.
The other accessors expose the embedding itself, such as the barycentric weights of each vertex. They are on the render surfaces reference.
The prepared surface splits vertices where a crack can open, so it has more vertices than the input.
mod shapes;
use deformable::math::Vector3;
use deformable::scene::embed_surface;
use deformable::tools::{ClipMode, PreparationParameters, SurfaceMesh};
use shapes::{cuboid, solid};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cube_polygons = cuboid(Vector3::new(-0.5, 2.0, -0.5), Vector3::new(0.5, 3.0, 0.5));
let cube_mesh = solid(&cube_polygons, 0.05, 0.3)?;
let surface = SurfaceMesh { mesh: cube_polygons, ..SurfaceMesh::default() };
let parameters = PreparationParameters { clip_mode: ClipMode::ClipWithInnerFaces, uv_scale: 1.0, splinter_cage: None };
let embedding = embed_surface(&cube_mesh, &surface, ¶meters)?;
let inner = embedding.source_faces().iter().filter(|&&face| face == -1).count();
let inner_corners = embedding.corner_flags().iter().filter(|flags| flags.is_inner()).count();
println!("{inner} inner faces with {inner_corners} corners, of {} corners", embedding.surface().corner_count());
Ok(())
}1638 inner faces with 4914 corners, of 5556 cornersInner faces are triangles. The other 642 corners belong to the pieces of the cube’s six quads, cut along the tetrahedron faces.
Skin it every frame
embedding.deform(&states, &world_transform, options, &mut output) skins the surface on the current tetrahedrons
and writes the result into output.
states: the object’stetrahedron_states, one per rest tetrahedron. Another count givesLengthMismatch.world_transform: the world matrix of your render mesh. The result is mapped by its inverse into the mesh’s object space. PassAffineTransform::IDENTITYwhen the surface is in world space. A transform without an inverse givesSingularTransform, and a NaN or infinite one givesNonFiniteValue.options: aSkinningOptions.SkinningOptions::default()sets both of its fields tofalse.show_inner_facesshows every inner face and cap, cracked or not, which is useful to inspect the preparation.start_splinteredshows the splinter caps from the start, instead of once a fracture flags one of their tetrahedrons.output: aDeformedSurfaceyou reuse every frame.deformreplaces its contents.
A DeformedSurface holds flat arrays in single precision, ready to copy into a vertex buffer:
positions: the position of each output vertex, in the order ofsurface().mesh.positions.normals: the unit normal of each corner, in corner order. It is empty without normals, and a zero normal stays zero.hidden_faces:truefor each face to hide, in face order.
A face is hidden when it is an inner face or a splinter cap that no crack has opened yet. Once a fracture exposes the tetrahedron face under it, it shows for good.
Object space and the world transform
A host keeps the render mesh in its object space and places it with a world matrix. Do the same here:
- Embed the surface in object space, with a rest mesh in object space.
- Map the rest mesh to world space before
add_object: the simulation runs in world space. - Pass the world matrix to
deform. The result comes back in object space, ready for the mesh.
AffineTransform { linear, translation } maps row vectors: a point p goes to p · linear + translation, and
transform.apply(p) computes it. So row i of linear is where axis i goes. A matrix M that maps column vectors
(M · p, as in most engines) gives linear = M.transpose(), or build it with Matrix3::from_columns from M’s rows.
mod shapes;
use deformable::math::{AffineTransform, Matrix3, Vector3};
use deformable::mesh::TetrahedralMesh;
use deformable::scene::{
DeformedSurface, MaterialParameters, ObjectOptions, Scene, SkinningOptions, TetrahedronMaterials,
embed_surface,
};
use deformable::tools::{ClipMode, PreparationParameters, SurfaceMesh};
use shapes::{cuboid, solid};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let local_polygons = cuboid(Vector3::new(-0.5, -0.5, -0.5), Vector3::new(0.5, 0.5, 0.5));
let local_mesh = solid(&local_polygons, 0.05, 0.3)?;
let surface = SurfaceMesh { mesh: local_polygons, ..SurfaceMesh::default() };
let parameters = PreparationParameters { clip_mode: ClipMode::ClipWithInnerFaces, uv_scale: 1.0, splinter_cage: None };
let embedding = embed_surface(&local_mesh, &surface, ¶meters)?;
// The object's world matrix: lifted 2.5 units.
let world = AffineTransform { linear: Matrix3::IDENTITY, translation: Vector3::new(0.0, 2.5, 0.0) };
let world_mesh = TetrahedralMesh {
positions: local_mesh.positions.iter().map(|&position| world.apply(position)).collect(),
tetrahedrons: local_mesh.tetrahedrons.clone(),
};
let mut scene = Scene::new();
let rubber = scene.add_material(&MaterialParameters::preset("rubber").ok_or("no rubber preset")?)?;
let cube = scene.add_object(&world_mesh, TetrahedronMaterials::Uniform(rubber), ObjectOptions::default())?;
let mut states = Vec::new();
scene.tetrahedron_states(cube, &mut states)?;
let mut deformed = DeformedSurface::default();
embedding.deform(&states, &world, SkinningOptions::default(), &mut deformed)?;
let heights = deformed.positions.iter().map(|position| position[1]);
let lowest = heights.clone().fold(f32::INFINITY, f32::min);
let highest = heights.fold(f32::NEG_INFINITY, f32::max);
println!("{lowest} {highest}");
Ok(())
}-0.5 0.5The cube sits at y = 2.5 in the world, and its skinned surface comes back around the origin. A world matrix with a non-uniform scale keeps the artist’s normals too: they are mapped back into object space and made unit length.
Splinters
A splinter cage gives the cracks the shapes of its cells; see Splinters. The surface is cut into one piece per cage cell, and each piece is capped. A piece’s vertices follow their own tetrahedrons until a crack reaches them. Then they follow the piece’s one tetrahedron, so the piece moves as one rigid splinter.
Make the cage with splinters_from_image, or
load one of the splinter meshes in the plugin zips. It must be in the surface’s space. Pass it as splinter_cage with
ClipWithInnerFaces:
mod shapes;
use deformable::math::Vector3;
use deformable::scene::embed_surface;
use deformable::tools::{
ClipMode, PixelGrid, PreparationParameters, SplinterImageParameters, SurfaceMesh, splinters_from_image,
};
use shapes::{cuboid, solid};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let wall_polygons = cuboid(Vector3::new(-1.0, 0.0, -0.125), Vector3::new(1.0, 1.0, 0.125));
let wall_mesh = solid(&wall_polygons, 0.05, 0.25)?;
// A wall split in two cells by a vertical line, drawn as a 41 x 31 image.
let (width, height) = (41, 31);
let mut pixels = vec![[255, 255, 255]; width * height];
for column in 5..36 {
pixels[5 * width + column] = [0, 0, 0];
pixels[25 * width + column] = [0, 0, 0];
}
for row in 5..26 {
for column in [5, 20, 35] {
pixels[row * width + column] = [0, 0, 0];
}
}
for (column, row) in [(5, 5), (20, 5), (35, 5), (5, 25), (20, 25), (35, 25)] {
pixels[row * width + column] = [255, 0, 0];
}
let image = PixelGrid { width: width as u32, height: height as u32, pixels };
// The cells span x from -1 to 1 and y from 0 to 1, a little deeper than the wall.
let cage_parameters = SplinterImageParameters {
size: Vector3::new(2.8, 1.55, 0.5),
origin: Vector3::new(-1.4, -0.25, 0.25),
..SplinterImageParameters::default()
};
let splinter_cage = splinters_from_image(&image, &cage_parameters)?;
let parameters = PreparationParameters {
clip_mode: ClipMode::ClipWithInnerFaces,
uv_scale: 1.0,
splinter_cage: Some(&splinter_cage),
};
let surface = SurfaceMesh { mesh: wall_polygons, ..SurfaceMesh::default() };
let embedding = embed_surface(&wall_mesh, &surface, ¶meters)?;
println!("{} splinters", embedding.brick_tetrahedrons().len());
Ok(())
}2 splintersAt rest, the caps between splinters are hidden. A cap shows once a fracture flags one of its tetrahedrons, the brick’s
or the one under the cap’s first corner, in its tetrahedron state, or from the start with
SkinningOptions { start_splintered: true, ..SkinningOptions::default() }.
Next steps
- Scene: the scene the states come from.
- Errors and threads: handle errors and skin from several threads.
- Render surfaces reference:
embed_surface,SurfaceEmbedding,PreparationParameters,ClipMode,CornerFlagsand the skinning types, with every signature. - Meshes reference:
SurfaceMesh, the render surface.