Constraints are conditions imposed on particles, that largely determine their behavior. Obi spends most of the time in a physics step enforcing constraints. In order to efficiently process all constraints in the shortest amount of time possible, Obi can process multiple constraints at the same time thanks to multithreading.
However, multithreading requires that no constraints affecting the same particle are processed at exactly the same time. Otherwise multiple threads would attempt to modify the same particle at once, leading to incorrect results and/or bad performance. To ensure correctness, constraints need to be processed in a very specific order.
Obi groups constraints of the same type into work items, and then organizes work items into batches. A work item is a small set of constraints (usually 1 - 8 constraints) that share as many particles as possible. A batch cannot contain work items that affect the same particle, so all work items in a batch can be safely processed in parallel.
All batches for a given constraint type are processed sequentially, then all batches for the next constraint type, until all constraints have been processed.
Organizing constraints into work items and batches can be a very time consuming process (known as graph-coloring) so when possible, Obi avoids doing it at runtime: it often happens as part of blueprint generation, blueprints store constraints pre-organized. Some constraint types (such as particle-particle collision constraints) are created and destroyed very often while the simulation is running, in these cases Obi performs incremental graph coloring at runtime.
At runtime, you can enable/disable/modify all constraints of a given type in an actor. Actor expose these parameters as public properties.
Here's a small example: a component that sets cloth distance constraint stretching compliance to 2 m/N upon pressing any key:
using UnityEngine;
using Obi;
[RequireComponent(typeof(ObiCloth))]
public class ElasticCloth : MonoBehaviour
{
void Update ()
{
if (Input.anyKeyDown)
GetComponent<ObiCloth>().stretchCompliance = 2;
}
}
Another small example that deactivates bend constraints in a rope:
using UnityEngine;
using Obi;
[RequireComponent(typeof(ObiRope))]
public class BendableRope : MonoBehaviour
{
void Update ()
{
if (Input.anyKeyDown)
GetComponent<ObiRope>().bendConstraintsEnabled = false;
}
}
For a detailed list of all constraint parameters exposed in an actor, check the API documentation.
In addition to modifying per-actor parameters that affect all of its constraints, you can also modify individual constraints.
ObiSolvers keep an instance of ObiConstraintsContainer for each type of constraint (once for distance constraints, one for bend constraints, and so on) where individual constraint data is stored in SoA fashion - that is, one list per constraint attribute. The amount of lists and the data they contain depends on the constraint type, check the API documentation for details.
Very much like they do for particle data, actors reserve a range in the solver's constraint containers to store their constraint data contiguously. When an actor gets added to a solver, all the constraints stored in its blueprint are copied to the range of solver entries reserved by the actor. You can retrieve the range of solver indices using actor.GetConstraintIndices<T>() or its non-generic variant actor.GetConstraintIndices(Type constraintType). The following snippet iterates trough all distance constraints for an actor and calculates the force exerted by each one:
// get the range of indices (start and count) where our distance constraints are stored in the solver:
Range indexRange = cloth.GetConstraintIndices<ObiDistanceConstraintsContainer>();
// get the solver's distance constraint container:
ObiDistanceConstraintsContainer container = actor.solver.GetConstraintsByType<ObiDistanceConstraintsContainer>();
// iterate the range of constraints, skipping inactive ones:
for (int j = 0; j < indexRange.count; ++j)
{
int idx = indexRange[j];
if (!sc.IsConstraintActive(idx))
continue;
// divide lambda by time squared to get force applied by constraint expressed in newtons:
float force = container.lambdas[ctrIdx] / (substepTime * substepTime);
// write to console:
Debug.Log("Constraint " + j + " exerts " + force + " Newtons");
}
Another example that modifies skin constraint radius and backstop:
using UnityEngine;
using Obi;
[RequireComponent(typeof(ObiSkinnedCloth))]
public class SkinAdjustments : MonoBehaviour
{
void Update ()
{
if (Input.anyKey)
{
var cloth = GetComponent<ObiSkinnedCloth>();
// get the range of indices (start and count) where our distance constraints are stored in the solver:
Range indexRange = cloth.GetConstraintIndices<ObiSkinConstraintsContainer>();
// retrieve the solver's skin constraints container:
var skinConstraints = cloth.solver.GetConstraintsByType<ObiSkinConstraintsContainer>
// iterate the range of constraints, skipping inactive ones:
for (int i = 0; i < indexRange.count; ++i)
{
int idx = indexRange[i];
if (!sc.IsConstraintActive(idx))
continue;
// set skin radius, backstop radius and backstop distance:
skinConstraints.skinRadiiBackstop[index] = new Vector3(0.05f, 0.1f, 0);
}
}
}
}
When using the Compute backend, the GPU is used to perform the simulation. Typically CPU and GPU memory are physically separate, and data must be uploaded from the CPU to the GPU or readback from the GPU to the CPU. Writing data to the constraint arrays as in the above example will only modify the CPU copy. You need to upload any changes made to constraint data arrays to the GPU by calling their Upload() method. In the above example, this means adding the following line right after the for loop:
// upload changes to the GPU: skinConstraints.skinRadiiBackstop.Upload();
Sometimes you want to add new constraints or remove existing ones. Most common case is adding pin constraints manually, instead of using attachments. To add a new constraint to a container you use AddConstraint(int minOverlap, ...), which returns the index of the constraint you just added. To remove it, call RemoveConstraint(int index) passing the index of the constraint that you got from AddConstraint().
AddConstraint takes different parameters depending on the specific type of constraint container you're dealing with. The first parameter is typically a minimum percentage of shared particles for this constraint to share work item with other constraints, 0.3f (30%) is a good default (some constraints that have a work item size of 1 don't have this parameter). The following parameters are those of the specific constraint (rest lengths, compliances, max bending, etc).
Here's an example of how to add a couple pin constraints to a rope:
// get a hold of the constraint type we want, in this case, pin constraints: var pins = solver.GetConstraintsByType<ObiPinConstraintsContainer>(); // Add a couple constraints to it, pinning the first and last particles in the rope. // Use 0 compliance for position and infinite compliance for rotation: int pin1 = pins.AddConstraint(rope.solverIndices[0], colliderA, Vector3.zero, Quaternion.identity, 0, float.PositiveInfinity); int pin2 = pins.AddConstraint(rope.solverIndices[blueprint.activeParticleCount - 1], colliderB, Vector3.zero, Quaternion.identity, 0, float.PositiveInfinity);
Obi allows you to write entirely custom constraints, and register them on a per-solver basis. Adding a new constraint type to a solver also creates a new UI panel in that solver's inspector that allows you to expose custom properties/controls.
Constraints are split into 4 classes you must derive yours from:
Now let's learn by doing: we'll create our own simple constraint type, dihedral constraints, as described in PBD's foundational paper.
We'll create a new class derived from ObiConstraintsContainer, adding the [Serializable] attribute so Unity can store its data in blueprints. We also set its priority relative to other constraint types (higher priority constraints get evaluated last):
using System;
using UnityEngine;
namespace Obi.Samples
{
[Serializable]
public class ObiDihedralConstraintsContainer : ObiConstraintsContainer
{
public override int priority => 400;
}
}
Each dihedral angle constraint affects 4 particles that define two triangles sharing an edge, and constrains the angle between the two triangles to be as close as possible to a reference (rest) angle. Other than the indices of the particles involved (that the container allocates and handles automatically for us), we'll need to store the rest angle and a compliance value per constraint, so we declare two lists:
using System;
using UnityEngine;
namespace Obi.Samples
{
[Serializable]
public class ObiDihedralConstraintsContainer : ObiConstraintsContainer
{
// one float per constraint: the rest angle between both triangle normals, in radians.
[ObiConstraintData][HideInInspector] public ObiNativeFloatList restAngles = new ObiNativeFloatList();
// one float per constraint: the compliance of the constraint.
[ObiConstraintData][HideInInspector] public ObiNativeFloatList compliances = new ObiNativeFloatList();
}
}
The ObiConstraintData attribute tells the container that it must resize the list when you add new constraints to the container. It has an optional argument that lets you flag the list as read/write (they're read-only by default).
We then write an AddConstraint method that allocates and initializes data for one constraint. We can use the base class' AddConstraint(minOverlap, params int[] particleIndices) method to allocate the constraint and get an index for it, then initialize the data at that index and return it.
using System;
using UnityEngine;
namespace Obi.Samples
{
[Serializable]
public class ObiDihedralConstraintsContainer : ObiConstraintsContainer
{
// one float per constraint: the rest angle between both triangle normals, in radians.
[ObiConstraintData][HideInInspector] public ObiNativeFloatList restAngles = new ObiNativeFloatList();
// one float per constraint: the compliance of the constraint.
[ObiConstraintData][HideInInspector] public ObiNativeFloatList compliances = new ObiNativeFloatList();
public override int priority => 400;
// Adds a new dihedral constraint and returns its index.
// minOverlap: minimum percentage of overlap we require between the constraint and candidate work item (between 0 and 1)
// p1: First particle of the shared edge.
// p2: Second particle of the shared edge.
// p3: Particle opposite to the shared edge in the first triangle.
// p4: Particle opposite to the shared edge in the second triangle
// restAngle: Rest angle between both triangle normals, in radians.
// compliance: Compliance of the constraint. 0 means fully rigid.
public int AddConstraint(float minOverlap, int p1, int p2, int p3, int p4, float restAngle, float compliance)
{
int constraintIndex = AddConstraint(minOverlap, p1, p2, p3, p4);
restAngles[constraintIndex] = restAngle;
compliances[constraintIndex] = compliance;
return constraintIndex;
}
}
}
This is all we need for our dihedral constraints. The ObiConstraintsContainer class declares more virtual methods that you may override in specific situations, see the API docs for reference. We also recommend taking a look at Obi's built-in constraint containers (ObiDistanceConstraintsContainer, ObiVolumeConstraintsContainer, etc) to see examples of more complex constraints where there's read/write data, per-actor parameters, or a variable amount of particles per constraint.
There's two methods in BurstConstraintsImpl we need to override:
using Unity.Jobs;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
using Unity.Burst;
namespace Obi.Samples
{
public class BurstDihedralConstraintsImpl : BurstConstraintsImpl
{
DihedralConstraintsBatchJob projectConstraints;
public override void SetConstraintData()
{
base.SetConstraintData();
var d = container as ObiDihedralConstraintsContainer;
projectConstraints.restAngles = d.restAngles.AsNativeArray<float>();
projectConstraints.compliances = d.compliances.AsNativeArray<float>();
projectConstraints.lambdas = this.lambdas;
}
public override JobHandle SolvePositions(JobHandle inputDeps, ObiSolver.SimulationTime time)
{
return ProcessConstraints(ref projectConstraints, time, inputDeps);
}
}
}
We're done with the boilerplate: all we need to do is write the actual job that implements the constraints. We won't get into details for the math behind the constraint (as it's explained in the PBD paper) but instead focus on Obi specifics.
Our job should implement the IConstraintsBatchJob interface, with its IConstraintsBatchJob.Mediator property setter. The ConstraintMediator struct contains references to basic particle data arrays (positions, orientations, inverse masses, etc) as well as helper methods to access all constraints in a work item.
Each Execute() call receives a work item index by argument. It should iterate trough all constraints in the work item (skipping inactive ones) calculating and applying corrections due to each of them. Here's the template that most constraints' implementation of Execute() should follow:
public void Execute(int w)
{
// get the work item at index w, and the index of the first constraint "i":
var wi = mediator.GetWorkItem(w, out int i);
// iterate from 0 to work item size:
for (int j = 0; j < mediator.workItemSize; ++j, ++i)
{
if (!wi.IsConstraintActive(j))
continue;
// Evaluate and apply constraint here.
// Use index "i" to access per-constraint data.
}
}
To calculate and apply XPBD corrections, there's a few helper methods and classes that take care of commonly used calculations:
Most XPBD constraints only deal with linear quantities (positions), such is the case of dihedral constraints: they simply move particles around, regardless of their orientation. More advanced constraints may also deal with particle orientation / angular quantities. The GeneralizedInvMass and Correction classes can be used for linear, angular and combined linear/angular constraints.
Among the built-in constraints, the most complex one that deals with both linear and angular quantities is BurstParticleCollisionConstraintsImpl by far, as it deals with frictional contact between simplices composed of multiple particles each. It's a good reference in case you want to delve deeper into complex XPBD constraints.
With this in mind, the job that implements dihedral constraints would look like this:
[BurstCompile]
public struct DihedralConstraintsBatchJob : IConstraintsBatchJob
{
[ReadOnly] public ConstraintMediator mediator;
[ReadOnly] public NativeArray<float> restAngles;
[ReadOnly] public NativeArray<float> compliances;
[NativeDisableContainerSafetyRestriction] [NativeDisableParallelForRestriction] public NativeArray<float> lambdas;
ConstraintMediator IConstraintsBatchJob.Mediator { set => mediator = value; }
public void Execute(int w)
{
var wi = mediator.GetWorkItem(w, out int i);
for (int j = 0; j < mediator.workItemSize; ++j, ++i)
{
if (!wi.IsConstraintActive(j))
continue;
// p1, p2: shared edge. p3, p4: vertices opposite to the edge in each triangle.
int p1 = mediator.GetParticleIndex(i, 0);
int p2 = mediator.GetParticleIndex(i, 1);
int p3 = mediator.GetParticleIndex(i, 2);
int p4 = mediator.GetParticleIndex(i, 3);
// positions relative to p1:
float3 e = mediator.GetPositionDifference(p2, p1).xyz;
float3 a = mediator.GetPositionDifference(p3, p1).xyz;
float3 b = mediator.GetPositionDifference(p4, p1).xyz;
float3 c3 = math.cross(e, a);
float3 c4 = math.cross(e, b);
float l3 = math.length(c3);
float l4 = math.length(c4);
// degenerate triangles have no normal:
if (l3 < BurstMath.epsilon || l4 < BurstMath.epsilon)
continue;
float3 n1 = c3 / l3;
float3 n2 = c4 / l4;
float d = math.clamp(math.dot(n1, n2), -1, 1);
// the gradient of acos(d) is singular when both triangles are coplanar (d = +-1).
float s = math.sqrt(1 - d * d);
if (s < BurstMath.epsilon)
continue;
// acos returns an unsigned angle, so the constraint can't tell towards which side
// the triangles are folded: rest angles are always in the [0, pi] range.
float constraint = math.acos(d) - restAngles[i];
// q_i (as given in the paper) are the gradients of -d with respect to each particle's position:
float3 q3 = (math.cross(e, n2) + math.cross(n1, e) * d) / l3;
float3 q4 = (math.cross(e, n1) + math.cross(n2, e) * d) / l4;
float3 q2 = -(math.cross(a, n2) + math.cross(n1, a) * d) / l3
- (math.cross(b, n1) + math.cross(n2, b) * d) / l4;
float3 q1 = -q2 - q3 - q4;
var w1 = new GeneralizedInvMass(mediator.SplitInvMass(p1));
var w2 = new GeneralizedInvMass(mediator.SplitInvMass(p2));
var w3 = new GeneralizedInvMass(mediator.SplitInvMass(p3));
var w4 = new GeneralizedInvMass(mediator.SplitInvMass(p4));
// since the derivative of acos(d) is -1 / s, the gradient of the constraint is q / s:
float weightedGradient = (w1.weight * math.lengthsq(q1) +
w2.weight * math.lengthsq(q2) +
w3.weight * math.lengthsq(q3) +
w4.weight * math.lengthsq(q4)) / (s * s);
float dlambda = BurstMath.XPBDLambdaDelta(constraint, compliances[i], lambdas[i], weightedGradient, mediator.substepTime);
lambdas[i] += dlambda;
float scale = dlambda / s;
new Correction(w1, q1, scale).AddPositionalCorrection(p1, mediator);
new Correction(w2, q2, scale).AddPositionalCorrection(p2, mediator);
new Correction(w3, q3, scale).AddPositionalCorrection(p3, mediator);
new Correction(w4, q4, scale).AddPositionalCorrection(p4, mediator);
}
}
}
This is very similar to writing a Burst implementation, with the difference that instead of a job we'll use a compute kernel which lives in a separate, .compute file in your project. Instead of passing data as NativeArrays, we'll use GraphicsBuffers in the C# side and (RW)StructuredBuffers in the HLSL side.
Boilerplate is an almost direct equivalent of Burst's. ComputeConstraintsImpl declares constraintsShader, smoothKeyword, atomicKeyword and projectKernel. These should be populated with the ComputeShader, LocalKeyword and kernel index from your implementation. SetConstraintsData binds resources to the kernel (same as it did for the Burst job), and SolvePositions dispatches the kernel just like it scheduled the job in Burst.
using UnityEngine;
using UnityEngine.Rendering;
namespace Obi.Samples
{
public class ComputeDihedralConstraintsImpl : ComputeConstraintsImpl
{
ObiDihedralConstraintsContainer d => container as ObiDihedralConstraintsContainer;
public ComputeDihedralConstraintsImpl()
{
constraintsShader = GameObject.Instantiate(Resources.Load<ComputeShader>("DihedralConstraints"));
smoothKeyword = new LocalKeyword(constraintsShader, "SMOOTH");
atomicKeyword = new LocalKeyword(constraintsShader, "ATOMIC");
projectKernel = constraintsShader.FindKernel("Project");
}
public override void SetConstraintData()
{
base.SetConstraintData();
constraintsShader.SetBuffer(projectKernel, "restAngles", d.restAngles.AsComputeBuffer<float>());
constraintsShader.SetBuffer(projectKernel, "compliances", d.compliances.AsComputeBuffer<float>());
}
public override void SolvePositions(ObiSolver.SimulationTime time)
{
ProcessConstraints(projectKernel, time.substepTime);
}
}
}
Here's the .compute file that implements the kernel:
#pragma multi_compile_local __ SMOOTH
#pragma multi_compile_local __ ATOMIC
#pragma kernel Project
// project-relative paths: they must point to wherever Obi is installed.
#include "Assets/Obi/Resources/Compute/MathUtils.cginc"
#include "Assets/Obi/Resources/Compute/Corrections.cginc"
#include "Assets/Obi/Resources/Compute/WorkItems.cginc"
StructuredBuffer<float> restAngles;
StructuredBuffer<float> compliances;
RWStructuredBuffer<float> lambdas;
float substepTime;
[numthreads(64, 1, 1)]
void Project (uint3 id : SV_DispatchThreadID)
{
unsigned int w = id.x;
if (w >= batches[batchIndex].activeWorkItemCount) return;
int i;
workItem wi = GetWorkItem(w,i);
for (uint j = 0; j < workItemSize; ++j, ++i)
{
if (!wi.IsConstraintActive(j))
continue;
// p1, p2: shared edge. p3, p4: vertices opposite to the edge in each triangle.
int p1 = GetParticleIndex(i, 0);
int p2 = GetParticleIndex(i, 1);
int p3 = GetParticleIndex(i, 2);
int p4 = GetParticleIndex(i, 3);
// positions relative to p1:
float3 e = GetPositionDifference(p2, p1).xyz;
float3 a = GetPositionDifference(p3, p1).xyz;
float3 b = GetPositionDifference(p4, p1).xyz;
float3 c3 = cross(e, a);
float3 c4 = cross(e, b);
float l3 = length(c3);
float l4 = length(c4);
// degenerate triangles have no normal:
if (l3 < EPSILON || l4 < EPSILON)
continue;
float3 n1 = c3 / l3;
float3 n2 = c4 / l4;
float d = clamp(dot(n1, n2), -1, 1);
// the gradient of acos(d) is singular when both triangles are coplanar (d = +-1).
float s = sqrt(1 - d * d);
if (s < EPSILON)
continue;
// acos returns an unsigned angle, so the constraint can't tell towards which side
// the triangles are folded: rest angles are always in the [0, pi] range.
float constraint = acos(d) - restAngles[i];
// q_i (as given in the paper) are the gradients of -d with respect to each particle's position:
float3 q3 = (cross(e, n2) + cross(n1, e) * d) / l3;
float3 q4 = (cross(e, n1) + cross(n2, e) * d) / l4;
float3 q2 = -(cross(a, n2) + cross(n1, a) * d) / l3
-(cross(b, n1) + cross(n2, b) * d) / l4;
float3 q1 = -q2 - q3 - q4;
GeneralizedInvMass w1 = GenInvMass(SplitInvMass(p1));
GeneralizedInvMass w2 = GenInvMass(SplitInvMass(p2));
GeneralizedInvMass w3 = GenInvMass(SplitInvMass(p3));
GeneralizedInvMass w4 = GenInvMass(SplitInvMass(p4));
// since the derivative of acos(d) is -1 / s, the gradient of the constraint is q / s:
float weightedGradient = (w1.weight() * dot(q1, q1) +
w2.weight() * dot(q2, q2) +
w3.weight() * dot(q3, q3) +
w4.weight() * dot(q4, q4)) / (s * s);
float dlambda = XPBDLambdaDelta(constraint, compliances[i], lambdas[i], weightedGradient, substepTime);
lambdas[i] += dlambda;
float scale = dlambda / s;
CreateCorrection(w1, q1, scale).AddPositionalCorrection(p1);
CreateCorrection(w2, q2, scale).AddPositionalCorrection(p2);
CreateCorrection(w3, q3, scale).AddPositionalCorrection(p3);
CreateCorrection(w4, q4, scale).AddPositionalCorrection(p4);
}
}
To register a new constraint type, solvers have a generic RegisterConstraintType<T,U>(string name) method. It takes two generic arguments: T is the ObiConstraintsContainer that holds data for your constraints, and U is the ConstraintParameters that holds inspector parameters. The string argument is the name used when displaying your constraints in the solver's inspector.
Once a new type is registered, you may provide implementations for each backend. You do this using RegisterBurstConstraintsImplementation<T,U> and RegisterComputeConstraintsImplementation<T,U>. T is the ObiConstraintsContainer subclass for our constraints and U is the BurstConstraintsImpl / ComputeConstraintsImpl subclass that implements these constraints for the corresponding backend.
Here's how we register our dihedral constraints and both its implementations. You'd typically do this in the solver's OnBeforeInitialize event:
solver.RegisterConstraintType<ObiDihedralConstraintsContainer, Oni.SmoothIterativeConstraintParameters>("Dihedral");
solver.RegisterBurstConstraintsImplementation<ObiDihedralConstraintsContainer, BurstDihedralConstraintsImpl>();
solver.RegisterComputeConstraintsImplementation<ObiDihedralConstraintsContainer, ComputeDihedralConstraintsImpl>();
The SmoothIterativeConstraintParameters class declares basic solver parameters: an on/off checkbox, an iterations counter and a smooth iterations counter. Most constraints use it. A few more complex ones (for instance collisions and density constraints) use their own subclass to expose a different parameter set.