You are viewing the documentation for Deformable v0.5.0, an older version. Read the latest, v0.9.0
Rust SDK
Tools
The mesh tools that turn polygon meshes, layers and line images into simulation input, and the checks that find bad meshes.
On this page
The tools prepare what a scene needs: a closed triangle cage, then a tetrahedral mesh. They also make splinter
cages and check meshes. The tools are in deformable::tools, and boundary_faces and FACES are in
deformable::mesh. For every parameter and field of each tool, see the
tools reference; the mesh checks are on the
mesh checks reference, and the mesh types and face helpers on the
meshes reference.
All tools are pure functions with no global state. They work in the unit of their input, so you can call them before
you create a scene. You can call them from several threads at the same time. The tools that can run long take
an Option<&CancelFlag>: pass None for no flag.
| Function | Takes | Returns |
|---|---|---|
triangulate |
A Polygon, with optional holes |
A Triangulation: a triangle cage and the source polygon of each triangle |
tetrahedralize |
A closed, outward Triangle |
A Tetrahedralization: a Tetrahedral and the skipped density regions |
autocage |
Any Polygon |
A closed, outward Triangle around it |
extrude |
A Triangle and a thickness |
A Tetrahedral shell |
span_ |
Two Triangle layers with the same topology |
A Tetrahedral between them |
splinters_ |
A Pixel line image |
A Polygon splinter cage |
verify_ |
A Surface, with optional holes |
A Vec<Mesh |
meshes_ |
Two Tetrahedral values |
bool |
boundary_ |
A Tetrahedral |
One face mask per tetrahedron |
embed_surface is on Render surfaces, and material_region_indices is on
Scene. Every tool returns Result<_, Error>, and the
error’s kind says what went wrong. Errors and threads
lists the kinds each tool returns and shows how to handle them.
Some examples on this page use the cuboid and solid helpers from
Getting started. Save them as src/shapes.rs
next to the example.
From polygons to tetrahedrons
The usual path has two steps. triangulate turns the artist’s polygons into a fine triangle cage, and
tetrahedralize fills the cage with tetrahedrons. What each tool is for, and how many tetrahedrons to aim for, is on
Preparing meshes in the Engine guide.
mod shapes;
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;
let parameters = TetrahedralizeParameters {
maximum_edge_length: 0.3,
anisotropy: [Anisotropy::default(); 2],
density_regions: Vec::new(),
};
let result = tetrahedralize(&cage, ¶meters, None)?;
println!("{} triangles, {} tetrahedrons", cage.triangles.len(), result.mesh.tetrahedrons.len());
Ok(())
}214 triangles, 471 tetrahedronsThe cage triangles stay the boundary of the tetrahedral mesh, except where a density region reaches the cage and
meshes the cage faces there again at its size, so a finer cage gives a finer boundary. When the
input is not closed, or is too detailed to use as a cage, wrap it with autocage instead.
Triangulate a polygon mesh
triangulate(&cage, &holes, ¶meters, cancel) triangulates each polygon of a PolygonMesh in its own plane
(Triangulate).
Where two polygons share an edge, the points added on that edge are shared too, so the result stays closed. Triangles
follow the winding of their polygon. A polygon can be non-planar: its inner points get a height interpolated from its
boundary.
TriangulateParameters::default() gives the defaults. Change a field with struct update syntax. The fields you
change most:
maximum_area: the largest triangle area,Some(1.0)by default. Smaller gives a finer cage.None, 0 or less sets no limit.quality: the minimum angle, in degrees, up to 20, the default.closed_boundary:trueby default. Every edge must border two polygons, or the call returns an error of kindNonClosedBoundary. Set it tofalseto triangulate a non-closed mesh.
The result is a Triangulation. Its mesh is the cage, and source_polygons gives the input polygon of each
triangle, so you can carry per-polygon data, such as materials, to the triangles.
A polygon with a hole
holes is a list of FaceHole runs, or &[] for none. A FaceHole { face, first_corner, corner_count } marks a
run of a polygon’s corners as a hole loop. The corners before the polygon’s first hole form its outer loop.
use std::collections::BTreeSet;
use deformable::math::Vector3;
use deformable::mesh::PolygonMesh;
use deformable::tools::{FaceHole, TriangulateParameters, triangulate};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let outline = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (0.0, 1.0)];
let hole = [(0.75, 0.25), (0.75, 0.75), (1.25, 0.75), (1.25, 0.25)];
let plate = PolygonMesh {
positions: outline.iter().chain(&hole).map(|&(x, y)| Vector3::new(x, y, 0.0)).collect(),
polygon_sizes: vec![8],
polygon_vertices: (0..8).collect(),
};
let holes = [FaceHole { face: 0, first_corner: 4, corner_count: 4 }];
let flat_parameters = TriangulateParameters { maximum_area: Some(0.05), closed_boundary: false, ..TriangulateParameters::default() };
let triangulation = triangulate(&plate, &holes, &flat_parameters, None)?;
let sources: BTreeSet<u32> = triangulation.source_polygons.iter().copied().collect();
println!("{} {:?}", triangulation.mesh.triangles.len(), sources);
// The plate is open, so the default closed boundary check refuses it.
let error = triangulate(&plate, &holes, &TriangulateParameters::default(), None).unwrap_err();
println!("{:?} ({}, {}): {}", error.kind(), error.first_index(), error.second_index(), error.message());
Ok(())
}59 {0}
NonClosedBoundary (0, 3): edge (0, 3) borders only one polygonThe plate is a single open polygon, so closed_boundary must be false. With the default true, the call returns
an error of kind NonClosedBoundary, whose first and second index are the edge’s two vertices. The other kinds
triangulate returns are in Error kinds.
Fill a cage with tetrahedrons
tetrahedralize(&cage, ¶meters, cancel) fills a closed triangle cage with tetrahedrons
(Tetrahedralize). It runs on one thread.
The cage must be closed, face outward and not cross itself; otherwise the call returns
an error of kind InvalidCage. Cage points never move, and cage vertices that no triangle uses are dropped. Every
tetrahedron of the result is positively oriented, as Scene::add_object requires.
TetrahedralizeParameters has no default: you always choose the size.
maximum_edge_lengthcaps the tetrahedron size inside the volume, in the cage’s unit. Near the surface, the size follows the cage triangles. A size of 0 or less givesMeshingFailed. A NaN or infinite size is not refused: it meshes the cage with no size limit.anisotropyholds two stretches of the mesher space.[Anisotropy::default(); 2]means no stretch. See Stretch the tetrahedrons.density_regionslists regions meshed finer or coarser than the rest. See Mesh some parts finer.
The result is a Tetrahedralization: the mesh, and skipped_density_regions, the indices of the density regions
the call skipped. The other kinds tetrahedralize returns are in
Error kinds.
Stretch the tetrahedrons
An Anisotropy { scale, direction } stretches the mesher space: with a scale s along a direction n, the tetrahedrons
come out about s times longer along n. Use it for long objects, such as planks and beams, to spend fewer tetrahedrons
along their length (Anisotropy). Both triangulate and
tetrahedralize take two of them; pass the same pair to both. Anisotropy::default() is scale 1 along (1, 1, 1), which
is no stretch.
mod shapes;
use deformable::math::Vector3;
use deformable::mesh::TetrahedralMesh;
use deformable::tools::{Anisotropy, TetrahedralizeParameters, TriangulateParameters, tetrahedralize, triangulate};
use shapes::cuboid;
/// The mean size of the tetrahedrons along one axis.
fn mean_extent(mesh: &TetrahedralMesh, axis: fn(&Vector3) -> f64) -> f64 {
let extents = mesh.tetrahedrons.iter().map(|tetrahedron| {
let values = tetrahedron.map(|node| axis(&mesh.positions[node as usize]));
values.iter().copied().fold(f64::NEG_INFINITY, f64::max) - values.iter().copied().fold(f64::INFINITY, f64::min)
});
extents.sum::<f64>() / mesh.tetrahedrons.len() as f64
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let beam = cuboid(Vector3::ZERO, Vector3::new(4.0, 1.0, 1.0));
for stretch in [1.0, 4.0] {
let anisotropy = [Anisotropy { scale: stretch, direction: Vector3::X }, Anisotropy::default()];
let refined = TriangulateParameters { maximum_area: Some(0.05), anisotropy, ..TriangulateParameters::default() };
let cage = triangulate(&beam, &[], &refined, None)?.mesh;
let parameters = TetrahedralizeParameters { maximum_edge_length: 0.3, anisotropy, density_regions: Vec::new() };
let mesh = tetrahedralize(&cage, ¶meters, None)?.mesh;
let ratio = mean_extent(&mesh, |position| position.x) / mean_extent(&mesh, |position| position.y);
println!("stretch {stretch:.1}: {} tetrahedrons, {ratio:.1} times longer along x", mesh.tetrahedrons.len());
}
Ok(())
}stretch 1.0: 1329 tetrahedrons, 1.0 times longer along x
stretch 4.0: 471 tetrahedrons, 3.9 times longer along xThe beam is 4 units long. Stretched by 4 along its length, it takes as many tetrahedrons as the unit cube.
The scale is clamped to [0.02, 50]. The direction can have any length, and each of its components is clamped to
[-100, 100]. A NaN scale or direction gives BadScales in tetrahedralize and NonFiniteValue in triangulate.
An infinite one differs between the two tools: triangulate refuses it with NonFiniteValue, while tetrahedralize
clamps it and goes on.
Mesh some parts finer
A DensityRegion { points, scale } meshes the convex hull of points, in the cage’s space, finer or coarser than the
rest (Density regions). Its tetrahedron size is
maximum_edge_length divided by the cube root of scale, so a scale above 1 is finer and a scale below 1 is coarser. A
scale of 0 or less counts as 1. A region with fewer than 4 points, a NaN or infinite point, or a NaN scale is skipped,
not refused, and listed in skipped_density_regions.
mod shapes;
use deformable::math::Vector3;
use deformable::tools::{
Anisotropy, DensityRegion, 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;
// A finer corner, and a region with only three points.
let corner = (0..8)
.map(|index| 0.5 * Vector3::new(f64::from(index >> 2 & 1), f64::from(index >> 1 & 1), f64::from(index & 1)))
.collect();
let flat = vec![Vector3::ZERO, Vector3::X, Vector3::Y];
let parameters = TetrahedralizeParameters {
maximum_edge_length: 0.3,
anisotropy: [Anisotropy::default(); 2],
density_regions: vec![
DensityRegion { points: corner, scale: 8.0 },
DensityRegion { points: flat, scale: 8.0 },
],
};
let result = tetrahedralize(&cage, ¶meters, None)?;
println!("{} {:?}", result.mesh.tetrahedrons.len(), result.skipped_density_regions);
Ok(())
}693 [1]The finer corner region adds tetrahedrons, from 471 to 693. The second region has only three points, so it is skipped.
Cancel a tool
triangulate, tetrahedralize and autocage can run long on a fine size. Set the cancel flag from another thread
while the tool runs. The tool checks it often and returns an error of kind Cancelled. A CancelFlag is Sync, so
the other thread sets it through a shared reference.
mod shapes;
use std::thread;
use std::time::Duration;
use deformable::CancelFlag;
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 fine = TriangulateParameters { maximum_area: Some(0.002), ..TriangulateParameters::default() };
let cage = triangulate(&cube, &[], &fine, None)?.mesh;
let parameters = TetrahedralizeParameters {
maximum_edge_length: 0.05,
anisotropy: [Anisotropy::default(); 2],
density_regions: Vec::new(),
};
let cancel = CancelFlag::new();
let result = thread::scope(|scope| {
scope.spawn(|| {
thread::sleep(Duration::from_millis(20));
cancel.set(true);
});
tetrahedralize(&cage, ¶meters, Some(&cancel))
});
let outcome = result.map(|tetrahedralization| tetrahedralization.mesh.tetrahedrons.len());
println!("{:?}", outcome.map_err(|error| error.kind()));
Ok(())
}Err(Cancelled)A flag that is already set when the call starts stops it at once. Clear it with cancel.set(false) before you reuse
it.
A size so small that the result could not be indexed gives OutputTooLarge at once, before any work. The estimate
assumes the mesh reaches maximum_edge_length everywhere. The density regions have bounds of their own, checked
during the run before each group of regions is meshed again, so a region can give it after the first mesh.
Wrap any mesh in a cage
autocage(&mesh, ¶meters, cancel) wraps any polygon mesh, open or closed, in a closed, outward cage of
near-equilateral triangles, at a small gap outside it
(Autocage). Fill the cage with tetrahedralize, then skin
the input mesh on the object as Render surfaces shows.
AutocageParameters::default() aims for 300 triangles. target_face_count sets how many triangles the cage aims
for, and scale_gap multiplies the gap. With a target_face_count of 0 or less, target_tetrahedron_count sets the
size instead. The counts are targets, not exact results.
mod shapes;
use deformable::math::Vector3;
use deformable::tools::{Anisotropy, AutocageParameters, TetrahedralizeParameters, autocage, tetrahedralize};
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 wrapped = autocage(&cube, &AutocageParameters { target_face_count: 100, ..AutocageParameters::default() }, None)?;
let parameters = TetrahedralizeParameters {
maximum_edge_length: 0.5,
anisotropy: [Anisotropy::default(); 2],
density_regions: Vec::new(),
};
let mesh = tetrahedralize(&wrapped, ¶meters, None)?.mesh;
println!("{} cage triangles, {} tetrahedrons", wrapped.triangles.len(), mesh.tetrahedrons.len());
Ok(())
}154 cage triangles, 301 tetrahedronsA target finer than the tool resolves gives an error of kind OutputTooLarge, and a cage that has not closed within the
step limit (1,000 steps per expected triangle and at least 100,000, restarts included) gives StepLimitReached. The
other kinds are in Error kinds.
Make thin objects
Extrude a triangle mesh into a shell
extrude(&mesh, thickness, direction) turns a triangle mesh into a shell thickness thick: 2 nodes per vertex and 3
tetrahedrons per triangle, with no added points. Each vertex moves along its angle-weighted unit normal. Use it for
sheets, plates and other thin objects (Extrude). The mesh
can be non-closed. The direction says where the second layer goes:
Extrude |
Layers |
|---|---|
Up |
The mesh, and a copy thickness along the normal. |
Down |
The mesh, and a copy thickness against the normal. |
Both |
Two copies, thickness / 2 on each side. The default. |
use deformable::math::Vector3;
use deformable::tools::{ExtrudeDirection, TriangleMesh, extrude};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let sheet = TriangleMesh {
positions: vec![
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(1.0, 0.0, 0.0),
Vector3::new(1.0, 0.0, 1.0),
Vector3::new(0.0, 0.0, 1.0),
],
triangles: vec![[0, 2, 1], [0, 3, 2]],
};
let shell = extrude(&sheet, 0.1, ExtrudeDirection::Up)?;
let mut heights: Vec<f64> = shell.positions.iter().map(|position| position.y).collect();
heights.sort_by(f64::total_cmp);
heights.dedup();
println!("{} {} {:?}", shell.positions.len(), shell.tetrahedrons.len(), heights);
Ok(())
}8 6 [0.0, 0.1]The sheet’s triangles face +y, so Up puts the second layer at y = 0.1. The tetrahedrons come out positive, but on
sharp curvature some can invert; Scene::add_object then refuses the mesh. Use a smaller thickness or a
smoother mesh. An empty triangle mesh gives an empty tetrahedral mesh.
A thickness of 0, less or NaN gives an error of kind NonPositiveThickness. The other kinds extrude and
span_layers return name the face or vertex at fault in the error’s first index. They are in
Error kinds.
Fill the space between two layers
span_layers(&first_layer, &second_layer) fills the space between two triangle meshes with the same vertices and faces,
such as a mesh and a moved copy of it (Span Layers).
Each triangle and its partner make a prism of 3 tetrahedrons. Each face of the first layer must match exactly one face
of the second, with the same vertices and winding, or the call returns NotIsomorphic. The tetrahedrons come out
positive whichever layer is on top. Layers that touch give flat tetrahedrons, which add_object refuses.
use deformable::math::Vector3;
use deformable::tools::{TriangleMesh, span_layers};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)];
let layer = |height: f64| TriangleMesh {
positions: corners.iter().map(|&(x, z)| Vector3::new(x, height, z)).collect(),
triangles: vec![[0, 2, 1], [0, 3, 2]],
};
let slab = span_layers(&layer(0.0), &layer(0.5))?;
println!("{} {}", slab.positions.len(), slab.tetrahedrons.len());
Ok(())
}8 6The output holds the first layer’s points, then the second layer’s.
Make a splinter cage from a drawing
splinters_from_image(&image, ¶meters) turns a line drawing into a splinter cage: one closed prism per cell. You
pass the cage to embed_surface, and the render surface breaks into those splinters. See
Render surfaces, and for how to draw one,
Draw your own pattern.
A pixel counts as black when red < 128 and green + blue <= 15, and as a red corner mark when red >= 128 and
red >= 8 x (green + blue). The plugin zips carry a library of drawings and ready cages as OBJ files: the
Blender plugin zip in splinters/images and splinters/meshes, the Maya plugin zip in
deformable/assets/splinters/images and deformable/assets/splinters/meshes. Unzip a copy of one of the zips to use
them from your own program.
The call never reads files: you decode the image into a PixelGrid { width, height, pixels }. The pixels are
[red, green, blue] triples, row after row, bottom row first. SplinterImageParameters::default() makes a cage 1
unit wide, high and deep at the origin. Change it to place the cage:
size: the cage’s width and height in x and y, and its depth.origin: the image’s lower-left corner in x and y, and the z of the top face. The bottom sits one depth lower.allow_nonconvex:truekeeps the traced cell outlines.falsestraightens each wall between two junctions.
The result holds the top points, then the bottom points. Its polygons are the tops, then the bottoms, then the side quads.
Read a BMP
The bundled drawings are 24-bit BMP files, stored bottom row first with blue, green, red bytes. This reader is enough for them. The program takes the image’s path on the command line:
use std::env;
use std::fs;
use deformable::math::Vector3;
use deformable::tools::{PixelGrid, SplinterImageParameters, splinters_from_image};
/// A 24-bit, bottom-up BMP file as a pixel grid.
fn read_bmp(path: &str) -> Result<PixelGrid, Box<dyn std::error::Error>> {
let data = fs::read(path)?;
let read_u32 = |at: usize| u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]);
let offset = read_u32(10) as usize;
let (width, height) = (read_u32(18) as i32, read_u32(22) as i32);
let bits = u16::from_le_bytes([data[28], data[29]]);
if &data[..2] != b"BM" || bits != 24 || width <= 0 || height <= 0 {
return Err(format!("{path} is not a bottom-up 24-bit BMP").into());
}
let (width, height) = (width as usize, height as usize);
let stride = (3 * width).div_ceil(4) * 4;
let mut pixels = Vec::with_capacity(width * height);
for row in 0..height {
for column in 0..width {
let at = offset + row * stride + 3 * column;
let (blue, green, red) = (data[at], data[at + 1], data[at + 2]);
pixels.push([red, green, blue]);
}
}
Ok(PixelGrid { width: width as u32, height: height as u32, pixels })
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = env::args().nth(1).ok_or("pass the path of a BMP file")?;
let image = read_bmp(&path)?;
let parameters = SplinterImageParameters {
size: Vector3::new(2.0, 1.0, 0.25),
origin: Vector3::new(-1.0, 0.0, 0.125),
..SplinterImageParameters::default()
};
let splinter_cage = splinters_from_image(&image, ¶meters)?;
println!("{} {} {} {}", image.width, image.height, splinter_cage.positions.len(), splinter_cage.polygon_sizes.len());
Ok(())
}Run it with the path of bricks.bmp from either unzipped plugin, here the Blender plugin, with the loader path set as
in Getting started:
cargo run --release -- /path/to/deformable-blender/splinters/images/bricks.bmp656 450 268 502A drawing that the tool cannot trace gives an error. Its kind is NoVertices for a blank image, or one that holds only
an open line, a closed line without a red mark or a T without red marks; NoCells when no line closes a cell; and
FaceAlreadySet for loose line ends with red marks, such as a T on its own with red marks at its three ends. The other
kinds
are in Error kinds.
Check a mesh before you use it
verify_surface(&mesh, &holes, &checks) checks the polygon mesh of a surface mesh and returns what it finds, in check
order. An empty list means the mesh passes; what each problem means, and how to fix it, is on
Verify Mesh. Run it before triangulate to find the
problems that would make the cage fail: a non-closed boundary, inverted normals, tiny angles, faces that cross each
other, and more. The check reads the positions, the polygons, the holes and the first two UV sets of the SurfaceMesh,
which Render surfaces describes.
MeshChecks::default() sets which checks run and their thresholds. Two fields matter most:
closed_boundary: off by default. Turn it on for a simulation cage: it reports a non-closed boundary, and checks for inward normals and nested parts.self_intersection: how far the self-intersection check goes.SelfIntersectionCheck::Skipruns no self-intersection, island, inward-normal or nesting check.PerIsland, the default, does not report a face crossed by an edge of another island.Fullreports every face crossed by an edge.
The other fields set the angle, gap and planarity thresholds and turn on the UV and convexity checks. They are on the mesh checks reference.
mod shapes;
use deformable::math::Vector3;
use deformable::mesh::PolygonMesh;
use deformable::tools::{MeshChecks, SurfaceMesh, verify_surface};
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 checks = MeshChecks { closed_boundary: true, ..MeshChecks::default() };
let surface = SurfaceMesh { mesh: cube.clone(), ..SurfaceMesh::default() };
println!("{:?}", verify_surface(&surface, &[], &checks)?);
// The cube without its last face.
let open_box = PolygonMesh {
positions: cube.positions.clone(),
polygon_sizes: vec![4; 5],
polygon_vertices: cube.polygon_vertices[..20].to_vec(),
};
let surface = SurfaceMesh { mesh: open_box, ..SurfaceMesh::default() };
for issue in verify_surface(&surface, &[], &checks)?.iter().take(4) {
println!("{issue:?}");
}
Ok(())
}[]
NonClosedBoundary { edge: [1, 3] }
NonClosedBoundary { edge: [5, 7] }
NonClosedBoundary { edge: [1, 5] }
NonClosedBoundary { edge: [3, 7] }Each MeshIssue is an enum variant whose fields locate the problem: a vertex, an edge, a face, an island, a distance.
Some issues are reported twice, once per way the check walks the edges, so remove duplicates before you show them.
The 22 variants and their fields are on the
mesh checks reference.
Malformed input is an error, not an issue: an index past the positions or a hole run outside its face gives an error
of kind IndexOutOfRange, polygon sizes that do not add up to the corner count or a UV set of the wrong length give
LengthMismatch, and a NaN or infinite position or threshold gives NonFiniteValue.
Find objects that start inside each other
meshes_intersect(&first, &second) returns true when a tetrahedron of first overlaps a tetrahedron of second by a
volume above 1e-10 with a nonzero normal: a pair where one tetrahedron lies wholly inside the other, or the two
coincide, does not count (Overlapping objects).
Both meshes are in world space. Use it to find objects that start inside each other before you simulate the scene. An
empty mesh, an index past the positions or a NaN or infinite position gives an Error.
mod shapes;
use deformable::math::Vector3;
use deformable::mesh::TetrahedralMesh;
use deformable::tools::meshes_intersect;
use shapes::{cuboid, solid};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mesh = solid(&cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0)), 0.05, 0.3)?;
let moved = |offset: Vector3| TetrahedralMesh {
positions: mesh.positions.iter().map(|&position| position + offset).collect(),
tetrahedrons: mesh.tetrahedrons.clone(),
};
let overlapping = meshes_intersect(&mesh, &moved(Vector3::new(0.5, 0.0, 0.0)))?;
let apart = meshes_intersect(&mesh, &moved(Vector3::new(3.0, 0.0, 0.0)))?;
println!("{overlapping} {apart}");
Ok(())
}true falseTwo identical meshes give false, because their overlaps have no direction.
Tetrahedron faces
boundary_faces(&mesh) returns one mask per tetrahedron: bit k is set when face k has no neighbour, so it lies on the
outer surface. Subtract it from a FaceEvent’s exposed_faces to keep only the faces a fracture opened.
FACES[k] holds the three corners of face k of a tetrahedron. Face k is the face opposite corner k.
mod shapes;
use deformable::math::Vector3;
use deformable::mesh::{FACES, boundary_faces};
use shapes::{cuboid, solid};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mesh = solid(&cuboid(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0)), 0.05, 0.3)?;
let masks = boundary_faces(&mesh)?;
println!("{} boundary faces", masks.iter().map(|mask| mask.count_ones()).sum::<u32>());
println!("{FACES:?}");
Ok(())
}214 boundary faces
[[1, 2, 3], [0, 3, 2], [0, 1, 3], [0, 2, 1]]The cube’s cage had 214 triangles, and each one is a boundary face. Seen from outside a positive tetrahedron, the corners of each face run clockwise, so (b - a) x (c - a) points into the tetrahedron.
Next steps
- Scene: turn the meshes into objects.
- Render surfaces: skin the artist’s mesh on the result.
- Tools reference: every item of the module, with its signature.