Deterministic Tetrahedral XPBD Soft-Body Elasticity in Godot 4
Simulate real-time volume-preserving 3D elastic soft-bodies (rubber, jelly, slime) at 60 FPS in Godot 4 Compatibility WebGL 2 using a 3x3x3 tetrahedral lattice and sub-stepped Extended Position-Based Dynamics (XPBD).
- physics
- softbody
- xpbd
- elasticity
- tetrahedral
- squash-and-stretch
- webgl
- siggraph
- siggraph-2026
No demo.
Problem
Built-in 3D rigid bodies cannot squash, bulge laterally on impact, or drape over ledges, while full finite-element solvers explode or stall when exported to Compatibility WebGL 2. Naive spring-mass cubes collapse flat under gravity because distance springs alone have no notion of signed 3D volume and invert when compressed.
Approach
Implement Extended Position-Based Dynamics (XPBD) over a compact 3×3×3 tetrahedral lattice (27 nodes, 8 sub-cubes decomposed into 40 parity-alternating tetrahedra):
- Parity-alternating 5-tet tessellation: split each sub-cube into 5 tetrahedra and mirror the X diagonal on odd
(ix + iy + iz)sub-cubes so adjacent faces share matching diagonals and zero directional shear bias. - Sub-stepped symplectic prediction: divide each fixed
1/60 sphysics tick into6substeps (h = dt / 6). High-frequency sub-stepping makes compliance (alpha_tilde = compliance / h^2) physically consistent and eliminates explosive overshoots without implicit matrix solves. - Stretch/shear distance constraints: project every unique tetrahedral edge using its compliance
edge_complianceand accumulated Lagrange multiplieredge_lambda. - Exact signed tetrahedral volume preservation: for each tetrahedron
(p0, p1, p2, p3), evaluateC_V = ((p1 - p0) x (p2 - p0)) . (p3 - p0) / 6 - V0and apply the four exact analytical volume gradients. Vertical impact automatically drives outward lateral Poisson bulging and prevents tetrahedron inversion. - Analytic floor & pedestal AABB projection + smooth
ArrayMeshskinning: project penetrating nodes onto static colliders with tangential friction and elastic normal rebound, then update a singleArrayMeshsurface with smooth area-weighted vertex normals and UV deformation grid shading.
Implementation
Save xpbd_softbody.gd to Assets/Game/Scripts/gameplay/xpbd_softbody.gd:
class_name XpbdSoftBody3D
extends MeshInstance3D
## Deterministic Extended Position-Based Dynamics (XPBD) volumetric soft-body solver.
## Uses a 3x3x3 particle lattice (27 nodes, 40 parity-alternating tetrahedra) with
## distance stretch/shear constraints and exact tetrahedral volume preservation.
@export var grid_dim: int = 3
@export var body_size: float = 1.45
@export var edge_compliance: float = 0.12
@export var volume_compliance: float = 0.000003
@export var damping: float = 0.994
@export var gravity: Vector3 = Vector3(0.0, -14.0, 0.0)
@export var substeps: int = 8
@export var floor_y: float = 0.0
@export var floor_friction: float = 0.24
@export var floor_restitution: float = 0.38
var positions: PackedVector3Array = PackedVector3Array()
var prev_positions: PackedVector3Array = PackedVector3Array()
var velocities: PackedVector3Array = PackedVector3Array()
var inv_masses: PackedFloat32Array = PackedFloat32Array()
var edge_a: PackedInt32Array = PackedInt32Array()
var edge_b: PackedInt32Array = PackedInt32Array()
var edge_rest: PackedFloat32Array = PackedFloat32Array()
var edge_lambda: PackedFloat32Array = PackedFloat32Array()
var tet_indices: PackedInt32Array = PackedInt32Array()
var tet_rest_vol: PackedFloat32Array = PackedFloat32Array()
var tet_lambda: PackedFloat32Array = PackedFloat32Array()
var surface_quads: PackedInt32Array = PackedInt32Array()
var surface_uvs: PackedVector2Array = PackedVector2Array()
var colliders: Array[AABB] = []
var total_rest_volume: float = 0.0
var _mesh: ArrayMesh
func build_lattice(center: Vector3, tilt_rad: Vector3 = Vector3.ZERO) -> void:
var n: int = maxi(2, grid_dim)
var count: int = n * n * n
positions.resize(count)
prev_positions.resize(count)
velocities.resize(count)
inv_masses.resize(count)
var basis := Basis.from_euler(tilt_rad)
var spacing: float = body_size / float(n - 1)
var half: float = body_size * 0.5
var node_mass: float = 1.0 / float(count)
var inv_m: float = 1.0 / node_mass
for iz in range(n):
for iy in range(n):
for ix in range(n):
var idx: int = _node_idx(ix, iy, iz, n)
var local_p := Vector3(
ix * spacing - half,
iy * spacing - half,
iz * spacing - half
)
var world_p := center + basis * local_p
positions[idx] = world_p
prev_positions[idx] = world_p
velocities[idx] = Vector3.ZERO
inv_masses[idx] = inv_m
_build_tetrahedra_and_edges(n)
_build_surface_topology(n)
_mesh = ArrayMesh.new()
mesh = _mesh
rebuild_mesh()
func _node_idx(ix: int, iy: int, iz: int, n: int) -> int:
return (iz * n + iy) * n + ix
func _build_tetrahedra_and_edges(n: int) -> void:
var tets: Array[int] = []
var rest_vols: Array[float] = []
var edge_set: Dictionary = {}
var ea: Array[int] = []
var eb: Array[int] = []
var er: Array[float] = []
total_rest_volume = 0.0
var even_patterns := [
[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]],
[[1, 1, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]],
[[1, 0, 1], [0, 0, 1], [1, 1, 1], [1, 0, 0]],
[[0, 1, 1], [1, 1, 1], [0, 0, 1], [0, 1, 0]],
[[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 1]],
]
for iz in range(n - 1):
for iy in range(n - 1):
for ix in range(n - 1):
var mirror_x: bool = ((ix + iy + iz) & 1) == 1
for pat in even_patterns:
var ids: Array[int] = []
for c in pat:
var dx: int = (1 - int(c[0])) if mirror_x else int(c[0])
ids.append(_node_idx(ix + dx, iy + int(c[1]), iz + int(c[2]), n))
var v0: float = _signed_tet_volume(ids[0], ids[1], ids[2], ids[3])
if v0 < 0.0:
var tmp: int = ids[2]
ids[2] = ids[3]
ids[3] = tmp
v0 = -v0
tets.append(ids[0])
tets.append(ids[1])
tets.append(ids[2])
tets.append(ids[3])
rest_vols.append(v0)
total_rest_volume += v0
var pairs := [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]
for pr in pairs:
var u: int = mini(ids[pr[0]], ids[pr[1]])
var v: int = maxi(ids[pr[0]], ids[pr[1]])
var key: int = (u << 12) | v
if not edge_set.has(key):
edge_set[key] = true
ea.append(u)
eb.append(v)
er.append(positions[u].distance_to(positions[v]))
tet_indices = PackedInt32Array(tets)
tet_rest_vol = PackedFloat32Array(rest_vols)
tet_lambda.resize(rest_vols.size())
tet_lambda.fill(0.0)
edge_a = PackedInt32Array(ea)
edge_b = PackedInt32Array(eb)
edge_rest = PackedFloat32Array(er)
edge_lambda.resize(ea.size())
edge_lambda.fill(0.0)
func _signed_tet_volume(i0: int, i1: int, i2: int, i3: int) -> float:
var p0: Vector3 = positions[i0]
return (positions[i1] - p0).cross(positions[i2] - p0).dot(positions[i3] - p0) / 6.0
func step_simulation(dt: float) -> void:
if positions.is_empty():
return
var clamped_dt: float = clampf(dt, 0.001, 0.033)
var steps: int = maxi(1, substeps)
var h: float = clamped_dt / float(steps)
var inv_h2: float = 1.0 / (h * h)
var alpha_edge: float = edge_compliance * inv_h2
var alpha_vol: float = volume_compliance * inv_h2
var p_count: int = positions.size()
var e_count: int = edge_a.size()
var t_count: int = tet_rest_vol.size()
for _s in range(steps):
for i in range(p_count):
prev_positions[i] = positions[i]
var v: Vector3 = (velocities[i] + gravity * h) * damping
velocities[i] = v
positions[i] = positions[i] + v * h
edge_lambda.fill(0.0)
tet_lambda.fill(0.0)
for e in range(e_count):
var ia: int = edge_a[e]
var ib: int = edge_b[e]
var wa: float = inv_masses[ia]
var wb: float = inv_masses[ib]
var w_sum: float = wa + wb
if w_sum <= 0.0:
continue
var delta: Vector3 = positions[ib] - positions[ia]
var dist: float = delta.length()
if dist < 1e-6:
continue
var c: float = dist - edge_rest[e]
var d_lambda: float = (-c - alpha_edge * edge_lambda[e]) / (w_sum + alpha_edge)
edge_lambda[e] += d_lambda
var corr: Vector3 = (delta / dist) * d_lambda
positions[ia] -= corr * wa
positions[ib] += corr * wb
for t in range(t_count):
var base: int = t * 4
var i0: int = tet_indices[base]
var i1: int = tet_indices[base + 1]
var i2: int = tet_indices[base + 2]
var i3: int = tet_indices[base + 3]
var p0: Vector3 = positions[i0]
var p1: Vector3 = positions[i1]
var p2: Vector3 = positions[i2]
var p3: Vector3 = positions[i3]
var g0: Vector3 = (p3 - p1).cross(p2 - p1) / 6.0
var g1: Vector3 = (p2 - p0).cross(p3 - p0) / 6.0
var g2: Vector3 = (p3 - p0).cross(p1 - p0) / 6.0
var g3: Vector3 = (p1 - p0).cross(p2 - p0) / 6.0
var w0: float = inv_masses[i0]
var w1: float = inv_masses[i1]
var w2: float = inv_masses[i2]
var w3: float = inv_masses[i3]
var denom: float = (
w0 * g0.length_squared()
+ w1 * g1.length_squared()
+ w2 * g2.length_squared()
+ w3 * g3.length_squared()
+ alpha_vol
)
if denom < 1e-9:
continue
var vol: float = (p1 - p0).cross(p2 - p0).dot(p3 - p0) / 6.0
var c_vol: float = vol - tet_rest_vol[t]
var d_lambda_v: float = (-c_vol - alpha_vol * tet_lambda[t]) / denom
tet_lambda[t] += d_lambda_v
positions[i0] = p0 + g0 * (w0 * d_lambda_v)
positions[i1] = p1 + g1 * (w1 * d_lambda_v)
positions[i2] = p2 + g2 * (w2 * d_lambda_v)
positions[i3] = p3 + g3 * (w3 * d_lambda_v)
for i in range(p_count):
var p: Vector3 = positions[i]
var prev_p: Vector3 = prev_positions[i]
var hit_normal := Vector3.ZERO
if p.y < floor_y:
p.y = floor_y
hit_normal = Vector3.UP
for box in colliders:
if box.has_point(p):
var min_b: Vector3 = box.position
var max_b: Vector3 = box.end
var best: float = max_b.y - p.y
var nrm := Vector3.UP
var resolved := Vector3(p.x, max_b.y, p.z)
if p.x - min_b.x < best:
best = p.x - min_b.x; nrm = Vector3.LEFT; resolved = Vector3(min_b.x, p.y, p.z)
if max_b.x - p.x < best:
best = max_b.x - p.x; nrm = Vector3.RIGHT; resolved = Vector3(max_b.x, p.y, p.z)
if p.z - min_b.z < best:
best = p.z - min_b.z; nrm = Vector3.FORWARD; resolved = Vector3(p.x, p.y, min_b.z)
if max_b.z - p.z < best:
best = max_b.z - p.z; nrm = Vector3.BACK; resolved = Vector3(p.x, p.y, max_b.z)
if p.y - min_b.y < best:
nrm = Vector3.DOWN; resolved = Vector3(p.x, min_b.y, p.z)
p = resolved
hit_normal = nrm
positions[i] = p
var new_v: Vector3 = (p - prev_p) / h
if hit_normal != Vector3.ZERO:
var vn: float = velocities[i].dot(hit_normal)
var tang: Vector3 = new_v - hit_normal * new_v.dot(hit_normal)
new_v = tang * (1.0 - floor_friction) + hit_normal * maxf(0.0, -vn * floor_restitution)
velocities[i] = new_v
rebuild_mesh()
Deformation-Readable Jelly Shader (softbody_jelly.gdshader)
shader_type spatial;
render_mode cull_back, diffuse_burley, specular_schlick_ggx;
uniform vec3 base_color : source_color = vec3(0.22, 0.82, 0.68);
uniform vec3 grid_color : source_color = vec3(0.95, 0.99, 1.0);
uniform vec3 rim_color : source_color = vec3(0.85, 0.98, 1.0);
uniform float roughness_val : hint_range(0.05, 1.0) = 0.18;
uniform float grid_density = 4.0;
void fragment() {
vec2 g = abs(fract(UV * grid_density - 0.5) - 0.5) / max(fwidth(UV * grid_density), vec2(0.002));
float line = 1.0 - clamp(min(g.x, g.y), 0.0, 1.0);
float edge_border = 1.0 - smoothstep(0.02, 0.06, min(min(UV.x, 1.0 - UV.x), min(UV.y, 1.0 - UV.y)));
float pattern = max(line * 0.45, edge_border * 0.72);
float fresnel = pow(1.0 - clamp(dot(normalize(NORMAL), normalize(VIEW)), 0.0, 1.0), 2.6);
ALBEDO = mix(base_color, grid_color, pattern * 0.55);
ROUGHNESS = mix(roughness_val, 0.08, fresnel * 0.5);
METALLIC = 0.04;
EMISSION = rim_color * fresnel * 0.28 + base_color * 0.08;
}
Tuning & Budget
- Compliance presets:
- Firm rubber:
edge_compliance = 0.028,volume_compliance = 0.000002,floor_restitution = 0.58. - Medium jelly:
edge_compliance = 0.14,volume_compliance = 0.0000025,floor_restitution = 0.42. - Soft slime:
edge_compliance = 0.42,volume_compliance = 0.000003,floor_restitution = 0.24. - WebGL 2 CPU cost: a 3×3×3 lattice (
27nodes,40tets,~90edges,48exterior triangles) solved with6substeps takes< 0.4 msper body in GDScript, allowing 4–6 simultaneous deformable props at 60 FPS in browser builds.
Common Pitfalls
- Inside-out faces in
ArrayMesh: Godot front faces use clockwise winding when viewed from outside. Verify outward face normals(pc - pa).cross(pb - pa)match your triangle order(ia, ib, ic)and(ia, ic, id). - Collapsed/inverted tetrahedra: keep
volume_compliancean order of magnitude stiffer thanedge_compliance(<= 0.0002) so compressed tets rebound outward instead of flipping negative volume. - Unclamped
delta: always clampdt <= 0.033before sub-stepping so tab switches never feed a huge timestep into1 / (h * h).
Official references
- SIGGRAPH 2026 Courses — Physics Is Easier Than You Think: Classical to Neural Elastic Simulation
- SIGGRAPH 2026 Real-Time Live! (Audience Choice — Dissectible Anatomy: Real-Time Volumetric Soft-Tissue Simulation)
- Miles Macklin, Matthias Müller & Nuttapong Chentanez (MIG 2016 — XPBD: Position-Based Simulation of Compliant Constrained Dynamics)
- Matthias Müller et al. (SCA 2020 — Detailed Rigid Body Simulation with Extended Position Based Dynamics)
More Godot 4 games
Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Godot 4 games here look like.

Fernlight
Raise a carved whistle to your lips in a fog-drowned forest, coax a glowing bird onto your open hand, and point to send it off to light the dark.
More Godot 4 techniques
Cel-Shading, Shadow Ramps & Width-Compensated Outlines in Godot 4 Compatibility →
Godot 4.7 Compatibility cel-shading spatial shader using custom light() shadow ramps, colored shadow tints, sun-gated Fresnel rim highlights, and a next_pass clip-space width-compensated inverted-hull outline.
CharacterBody3D Slopes, Snap & Coyote Jump in Godot 4 →
Crisp Godot 4 CharacterBody3D locomotion combining floor_snap_length, apex hang gravity, jump-cut, coyote time, and zero-arg move_and_slide.
Frame-Rate-Independent Springs, Squash-Stretch & Ribbon Trails in Godot 4 →
Typed GDScript 4 second-order damped springs, volume-preserving visual squash-stretch, Eiserloh T^2 FastNoiseLite camera trauma, and ImmediateMesh sword/dash ribbon trails.
Stylized Water, Gerstner Waves & Depth Shoreline Foam in Godot 4 Compatibility →
Godot 4.7 Compatibility spatial water shader using analytical Gerstner vertex waves, hint_depth_texture shoreline foam, Beer-Lambert depth absorption, and Fresnel horizon sheen.
Read via free MCP — or sign in to add techniques & beta test
Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.