BorrowedTorch.FabricSimulator
1.5.1
Prefix Reserved
dotnet add package BorrowedTorch.FabricSimulator --version 1.5.1
NuGet\Install-Package BorrowedTorch.FabricSimulator -Version 1.5.1
<PackageReference Include="BorrowedTorch.FabricSimulator" Version="1.5.1" />
<PackageVersion Include="BorrowedTorch.FabricSimulator" Version="1.5.1" />
<PackageReference Include="BorrowedTorch.FabricSimulator" />
paket add BorrowedTorch.FabricSimulator --version 1.5.1
#r "nuget: BorrowedTorch.FabricSimulator, 1.5.1"
#:package BorrowedTorch.FabricSimulator@1.5.1
#addin nuget:?package=BorrowedTorch.FabricSimulator&version=1.5.1
#tool nuget:?package=BorrowedTorch.FabricSimulator&version=1.5.1
BorrowedTorch.FabricSimulator
GPU cloth solver for MonoGame. Positions live in a structured buffer and never come back to the CPU unless you ask: a compute shader integrates them, relaxes the constraints and computes the normals, and stops there. You draw them.
- Verlet integration on a fixed step, with Jacobi relaxation
- Structural, shearing and bending constraints; bending yields plastically, so creases stay
- Long-range attachments, so a wide pinned sheet does not stretch like rubber
- Sphere and ground colliders with friction, and your own scene's surfaces through a function of position
- Self-collision through a spatial hash rebuilt every step, each particle's partners gathered once a step
- Pins set and released on the live sheet, with no kick
- Rips and tears cut into the live sheet: threads, folds, normals, triangles, contacts and pin distances all follow
- Clean-lipped cuts at any angle:
CreateCutMeshclips the damaged triangles along the strokes that cut them - Cuts driven by world rays, so crumpled cloth is cut where the knife passed rather than where the sheet was built
- Rips along a stroke with ragged lips, as torn cloth has, beside the clean cuts
- Tearing under strain: threads give way where the sheet is stretched past a strength, found on the GPU each step
- Wind as an air velocity, with drag evaluated against it: one vector a frame, gusted by any formula you like
- A rest deadband and a hold, so cloth settles instead of twitching on solver noise, and a settled pile stays exactly still
- Physically-scaled: areal density, not particle mass, so the sheet behaves the same at any tessellation
No rendering. No lights, no materials, no draw calls. The package ships the compute shader and the particle layout; you shade the sheet yourself. See Drawing it below.
Demo
The repository — not the package — carries a small demo of all of it: a hanging sheet you can cut.
dotnet run --project Demo
Drag the left mouse button across the sheet to cut along the stroke, picked against the billowing cloth itself rather
than a flat plane; the lips follow it cleanly at any angle. Space tears a random wandering rip, X a short straight one,
C mends, R rebuilds the sheet, P lets go of the top edge between its corners and pins it again, W cycles the wind
(--calm starts without any), Escape exits. The demo compiles the solver's HLSL with the same content builder a host
uses, so it doubles as a working reference for everything below.
Requirements
Windows, net10.0-windows, and the compute-capable MonoGame fork — this package depends on BorrowedTorch's
BorrowedTorch.MonoGame.Framework.Compute.WindowsDX 3.8.6.101 (1.3.1 and earlier on the old fork,
MonoGame.Framework.Compute.WindowsDX.NoMemoryLeak). Stock MonoGame has no compute shaders or structured buffers, so it
will not work. Your GraphicsDeviceManager must use GraphicsProfile.HiDef.
You also need the fork's content builder, because the solver ships as HLSL and something has to compile it:
dotnet add package BorrowedTorch.MonoGame.Content.Builder.Task.Compute
dotnet new tool-manifest
dotnet tool install BorrowedTorch.MonoGame.Content.Builder.Compute
Not the old fork's builder. BorrowedTorch's fork loads effects of its own format (MGFX 100) only. The old fork's builder -
MonoGame.Content.Builder.Task.Computewith thedotnet-mgcb-computetool, 3.8.3 - writes MGFX 12, whose effects fail atContent.Load: take it out of the project and the tool manifest - from 1.4.1 the build stops withBTFS0003while it is there. 1.4.0 came out before the fork's builder; on it, compileFabricCompute.fxwith the fork'smgfxcand setBorrowedTorchFabricProvideShaderSourcetofalse, or move to 1.4.1 and the builder above.
You almost certainly need the builder anyway: your own cloth shader reads a StructuredBuffer, which stock MGCB cannot
compile and stock MonoGame cannot bind. Building one more .fx costs about a second. Without it the build stops with
BTFS0001 rather than failing later at Content.Load.
Install
dotnet add package BorrowedTorch.FabricSimulator
On every build the package copies its shader sources into your content folder and builds them alongside your own content:
Content/BorrowedTorch.FabricSimulator.mgcb its own response file, beside whatever .mgcb you already have
Content/Effects/Fabric/FabricCompute.fx the solver
Content/Effects/Fabric/*.fxh the solver's body, and the layout your shader includes — see Drawing it
They land in your tree rather than the package cache because the builder writes its output next to the .mgcb that
named it, and a package folder is shared by every project on the machine. Worth a .gitignore line; Content/bin/ and
Content/obj/ want one anyway. The copy stays the package's: every build refreshes it, so an edit made to it in place
is lost at the next one. To change the solver, turn the copying off first, as below.
The result is Content/Effects/Fabric/FabricCompute.xnb in your output, which is FabricEffect.DefaultEffectPath for a
ContentManager rooted at Content. Two response files in one content folder do not collide: the builder keys its
output folder on the .mgcb's name and its link folder on the containing folder.
Set BorrowedTorchFabricContentDir if your content root is not Content\ (with or without the trailing separator) — in
the project file or Directory.Build.props, so the package's targets see it when they are imported. The
copying is on by default for an executable and off for a library, and the targets flow transitively, so a game that gets
the package through a library of its own still gets the shaders, while the library in between compiles none. Set
BorrowedTorchFabricProvideShaderSource=false to keep the package out of your content build and compile
FabricCompute.fx
yourself — BorrowedTorchFabricShaderSourceDir names where the package keeps its own copy, for a Copy target of your
own.
That switch takes the package out of your content build — no copy, no BTFS0001 or BTFS0003 check — but deletes
nothing. The builder finds .mgcb files by scanning your content folder, so whatever an earlier build left there keeps
being compiled, and once you compile FabricCompute.fx from a .mgcb of your own, two content builds race for one
output path. So while the copied response file is still there with the switch off, every build warns with BTFS0002
rather than leaving you to find out later.
Deleting the copies is a separate, deliberate step. By the time you turn the switch off, the copy in your tree may be one you have edited, and a build that removed it as a side effect would discard that silently:
dotnet build -t:BorrowedTorchFabricRemoveShaderSource
That deletes the files the package copied, by name, and removes the Effects/Fabric folder only once nothing else is
left in it, so anything of your own in that tree is untouched. It is safe to run repeatedly and does nothing when there
is nothing to remove.
Why source rather than a compiled shader. A compiled effect carries an MGFX version the runtime checks and rejects outright, so a blob would be tied to one build of one fork, and the failure message would not mention this package.
A working sheet
Four files, on top of the packages above. Everything after this section is detail on how they work.
Program.cs:
using var game = new ClothGame();
game.Run();
ClothGame.cs:
using BorrowedTorch.FabricSimulator.Simulation;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
public class ClothGame : Game
{
private FabricSettings _settings;
private FabricEffect _solver;
private Fabric _fabric;
private Effect _cloth;
private IndexBuffer _indices;
private VertexBuffer _vertices;
private Matrix _viewProjection;
private Vector3 _cameraPosition;
public ClothGame()
{
// Compute requires HiDef. Reach has no compute stage to compile the solver into.
_ = new GraphicsDeviceManager(this) { GraphicsProfile = GraphicsProfile.HiDef };
Content.RootDirectory = "Content";
}
protected override void LoadContent()
{
_settings = new FabricSettings
{
WidthInParticles = 96,
HeightInParticles = 64,
RestLength = 0.06f,
RelaxationIterations = 10,
Wind = new Vector3(0.0f, 0.0f, -6.0f)
};
_solver = new FabricEffect(GraphicsDevice, Content);
_fabric = new Fabric(_solver, _settings);
// Nothing is built until Rebuild - or the first Update - so the layout comes first.
_fabric.Origin = new Vector3(0.0f, 3.0f, 0.0f);
_fabric.PinMode = FabricPinMode.TopEdge;
_fabric.Rebuild();
// Two triangles per cell, indexing the particle buffer directly. 32-bit
// indices, because 16-bit overflows silently past 65,536 particles.
var indices = _fabric.CreateTriangleIndices();
_indices = new IndexBuffer(GraphicsDevice, IndexElementSize.ThirtyTwoBits, indices.Length, BufferUsage.WriteOnly);
_indices.SetData(indices);
// A draw call needs a vertex buffer bound, but nothing reads it: the shader
// takes everything from the particle buffer, by vertex id. One float per
// vertex satisfies that - no struct, no IVertexType.
var vertexLayout = new VertexDeclaration(
new VertexElement(0, VertexElementFormat.Single, VertexElementUsage.Position, 0));
_vertices = new VertexBuffer(GraphicsDevice, vertexLayout, _fabric.ParticleCount, BufferUsage.WriteOnly);
_cloth = Content.Load<Effect>("Effects/Cloth");
_cameraPosition = new Vector3(0.0f, 3.0f, 7.0f);
_viewProjection =
Matrix.CreateLookAt(_cameraPosition, new Vector3(0.0f, 2.6f, 0.0f), Vector3.Up) *
Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 100.0f);
}
protected override void Update(GameTime gameTime)
{
_fabric.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// Both sides of the sheet become visible as soon as it folds.
GraphicsDevice.RasterizerState = RasterizerState.CullNone;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
// Every frame: which of the solver's two buffers holds the latest step can
// change with any step. The grid as built, which the settings may run ahead of.
_cloth.Parameters["FabricParticles"].SetValue(_solver.ParticleBuffer);
_cloth.Parameters["FabricWidthInParticles"].SetValue(_fabric.WidthInParticles);
_cloth.Parameters["FabricHeightInParticles"].SetValue(_fabric.HeightInParticles);
// Identity world matrix: the particles are already in world space.
_cloth.Parameters["WorldViewProjection"].SetValue(_viewProjection);
// The pixel shader turns the solver normal towards the camera before lighting.
_cloth.Parameters["CameraPosition"].SetValue(_cameraPosition);
GraphicsDevice.SetVertexBuffer(_vertices);
GraphicsDevice.Indices = _indices;
foreach (var pass in _cloth.CurrentTechnique.Passes)
{
pass.Apply();
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _fabric.TriangleCount);
}
base.Draw(gameTime);
}
protected override void UnloadContent() => _solver.Dispose();
}
Content/Effects/Cloth.fx — yours, not the package's. The #include resolves because the package put the header next
door, at Content/Effects/Fabric:
#include "Fabric/FabricParticleBuffer.fxh"
float4x4 WorldViewProjection;
float3 CameraPosition;
struct VSOutput
{
float4 Position : SV_POSITION;
float3 WorldPosition : TEXCOORD1;
float3 Normal : NORMAL0;
float2 TexCoord : TEXCOORD0;
};
VSOutput VS(float unused : POSITION0, uint vertexId : SV_VertexID)
{
FabricParticle p = FabricParticles[vertexId];
VSOutput output;
output.Position = mul(float4(p.Position, 1.0), WorldViewProjection);
output.WorldPosition = p.Position; // already in world space
output.Normal = p.Normal; // the solver's, not the triangle's
output.TexCoord = FabricTextureCoordinates(vertexId);
return output;
}
float4 PS(VSOutput input) : SV_TARGET
{
float3 normal = normalize(input.Normal);
float3 toCamera = normalize(CameraPosition - input.WorldPosition);
// Culling is off, so half the sheet shows its back face while the solver's
// normal points one way only. Flip it towards the camera before lighting, or
// the far side of every fold shades as though lit from behind.
if (dot(normal, toCamera) < 0.0)
normal = -normal;
float lambert = saturate(dot(normal, normalize(float3(0.3, 0.8, 0.6))));
return float4(float3(0.85, 0.25, 0.30) * (0.25 + 0.75 * lambert), 1.0);
}
technique ClothTechnique
{
pass MainPass
{
VertexShader = compile vs_5_0 VS();
PixelShader = compile ps_5_0 PS();
}
}
And Content/Content.mgcb, your own content build, with Cloth.fx in it. The solver has its own response file
alongside, which the package wrote.
That gives a 96 x 64 sheet pinned along its top edge, falling under gravity and blowing away from the camera, lit from the solver's own normals. From there: Knobs for the tunables, Placement, attitude and custom pins for where the sheet hangs and what holds it, Diagnostics for the measurements a screenshot cannot give you.
Simulate
using BorrowedTorch.FabricSimulator.Simulation;
// LoadContent
_settings = new FabricSettings
{
WidthInParticles = 96,
HeightInParticles = 64,
RestLength = 0.06f,
RelaxationIterations = 10,
Wind = new Vector3(0.0f, 0.0f, -6.0f)
};
_effect = new FabricEffect(GraphicsDevice, Content); // FabricEffect.DefaultEffectPath
_fabric = new Fabric(_effect, _settings);
_fabric.Origin = new Vector3(0.0f, 3.0f, 0.0f);
_fabric.PinMode = FabricPinMode.TopEdge;
_fabric.Rebuild(); // the layout properties, the grid and RestLength are read here
// Update
_fabric.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
Fabric owns the grid, FabricEffect owns the GPU buffers and the step loop, and FabricSettings is a plain object
you mutate in place — the solver re-uploads it every frame, so a knob changed while running takes effect on the next
step. A knob set to something that is not a finite number throws at that upload, naming it, rather than reaching the
GPU, where one NaN would spread through the whole sheet within a few steps.
The layout properties on Fabric, and the grid, RestLength and SeedRipple in the settings, work differently: they
are read when the sheet is built, so set them and then call Rebuild(). Until then the live sheet keeps the ones it was
built with, so it never shears or stretches out of step with its own pins, folds and cuts. The constructor builds
nothing - the first Update builds the sheet if Rebuild() has not - so the layout can go in an object initializer
too. WidthInParticles, HeightInParticles and RestLength on Fabric report the sheet as built.
Or set AutoRebuild in the settings, and every Update and Step compares what Rebuild() reads with what the live
sheet was built from, and rebuilds when any of it differs. A rebuild starts over — a fresh sheet, every tear mended,
SetPinned changes dropped — so it suits a setup being edited, from a tuning panel say, not an Origin animated every
frame. Every rebuild, called or automatic, raises Rebuilt: the one place to size the buffers to the new sheet.
_fabric.Rebuilt += (_, _) =>
{
var indices = _fabric.CreateTriangleIndices();
_indices?.Dispose();
_indices = new IndexBuffer(GraphicsDevice, IndexElementSize.ThirtyTwoBits, indices.Length, BufferUsage.WriteOnly);
_indices.SetData(indices);
_vertices?.Dispose();
_vertices = new VertexBuffer(GraphicsDevice,
new VertexDeclaration(new VertexElement(0, VertexElementFormat.Single, VertexElementUsage.Position, 0)),
_fabric.ParticleCount, BufferUsage.WriteOnly);
};
_settings.AutoRebuild = true;
_settings.WidthInParticles = 128; // the next Update rebuilds, and the handler resizes
Each FabricEffect runs its own copy of the loaded solver, so several sheets can share one ContentManager: give each
its own FabricEffect and Fabric.
Wind is the knob made for animating. It is the air's velocity, not a force, and gusts are yours to compute: set it
every frame from any formula you like, and every step of that frame blows with it.
// Update, before _fabric.Update: a few sines at unrelated rates, so the breeze never quite repeats.
var t = (float)gameTime.TotalGameTime.TotalSeconds;
var gust = new Vector3(MathF.Sin(t * 1.9f) * MathF.Cos(t * 1.1f), 0.0f, MathF.Sin(t * 2.3f) * MathF.Cos(t * 0.9f));
_settings.Wind = new Vector3(0.0f, 0.0f, -1.2f) + gust * 0.5f;
The whole sheet feels the same air at any one moment; the ripples across it come from the cloth itself, as each panel turns towards or away from the flow. For air that varies across the sheet, give the solver a function of position.
Drag only ever pushes along the wind, so a flag in steady air streams out flat and stays there. LiftCoefficient adds
the rest of the air's push on a tilted face: across the wind, a flat plate's at 1 - strongest at 45 degrees to the flow,
none edge-on or face-on. A panel tilted to the flow is pushed further, the cloth's tension pulls it back, and the waves
run down to the free edge: the flag flaps in air that does not change at all. It is off by default, so a sheet tuned for
1.0 moves as it did; 0.5 to 1 suits a flag.
_settings.LiftCoefficient = 0.8f;
Wind that varies across the sheet
A gust front rolling across a flag, eddies, a helicopter's downwash: air that differs from place to place is a function of position, and it has to run where the particles are — on the GPU, for every particle at its current position, every step. So it is written in HLSL, in an effect of your own that wraps the solver:
// Content/Effects/ClothSolver.fx: the package's solver, with our own wind.
float3 GustBands(float3 position); // declared before the solver, defined after it
#define FABRIC_WIND_AT GustBands
#include "Fabric/FabricCompute.fx"
float GustStrength; // our own knob
// Bands of stronger wind drifting across the sheet, scaled by Wind, so still air stays still.
float3 GustBands(float3 position)
{
float band = saturate(sin(position.x * 1.5 - FabricTime * 2.5));
return Wind * (1.0 + GustStrength * band * band);
}
Add it to your Content.mgcb like any effect, and load the solver from it instead of the default:
_solver = new FabricEffect(GraphicsDevice, Content, "Effects/ClothSolver");
_solver.Shader.Parameters["GustStrength"].SetValue(0.5f);
The function is declared before the include and defined after it, where the solver's Wind — whatever you set this
frame — and FabricTime, simulated seconds updated every step, are in scope. Anything else it needs, declare as a
uniform of your own and set through FabricEffect.Shader — the sheet's own copy of the effect, not the instance
Content.Load returns. An answer that is not finite falls back to Wind, since one NaN would spread through the
whole sheet within a few steps. The formula is compiled with your content, so changing it means a rebuild, and each
formula is a solver of its own. Without FABRIC_WIND_AT nothing is called: the default solver compiles exactly as
before. The demo runs its breeze through one of these.
Your own scene
The sphere and the floor are the solver's own. A world of your own — walls, tables, a statue — the cloth can rest on and fall against through a function of position, in an effect that wraps the solver as a wind function's does:
// Content/Effects/ClothSolver.fx: the package's solver, with our own table to lie on.
bool TableSurface(float3 position, float reach, out float3 surface, out float3 normal);
#define FABRIC_SCENE_SURFACE TableSurface
#include "Fabric/FabricCompute.fx"
float3 TableCentre; // our own: a box, and half its size each way
float3 TableHalf;
// The box's nearest point to position, and the way out of it there; false when that is out of reach.
bool TableSurface(float3 position, float reach, out float3 surface, out float3 normal)
{
float3 local = position - TableCentre;
float3 outside = local - clamp(local, -TableHalf, TableHalf);
if (dot(outside, outside) > 0.0)
{
surface = position - outside;
normal = normalize(outside);
return dot(outside, outside) <= reach * reach;
}
// Inside: out through the nearest face.
float3 gap = TableHalf - abs(local);
float3 axis = gap.x < gap.y && gap.x < gap.z ? float3(1, 0, 0) : gap.y < gap.z ? float3(0, 1, 0) : float3(0, 0, 1);
normal = axis * sign(local);
surface = position + normal * dot(gap, axis);
return true;
}
_settings.UseSceneCollider = true;
_solver.Shader.Parameters["TableCentre"].SetValue(new Vector3(0.0f, 0.4f, 0.0f));
_solver.Shader.Parameters["TableHalf"].SetValue(new Vector3(0.6f, 0.4f, 0.4f));
It is asked once a step for each free particle, where the step begins: the nearest point of your scene within reach,
and the outward normal there — towards the outside of a closed shape, or, for a surface with no inside, towards the side
the particle is on. reach is as far as the step can carry the particle, with SceneColliderThickness and a weave's
length on top for the threads' pull; return false when nothing is that close. From the answer the step keeps a plane,
which every round holds the particle outside of, SceneColliderThickness off it, and which rubs with ColliderFriction
and holds settled cloth as the floor does. In front of the surface the plane faces the particle from the nearest point —
off an edge or a corner, the plane that parts them; inside, it is the surface's own, and the particle goes back out
through the nearest face. A plane is not the surface: a particle sliding past an edge within a step is held to the
edge's line until the next step lets it go. And only the particles are tested, not the cloth between them, so an edge
thinner than their spacing can slip through; SceneColliderThickness gives a little room for that.
The function runs for every free particle every step, so its cost is the cloth's: for a large scene, walk an
acceleration structure, as a ray tracer does. An answer that is no number, or no direction, holds nothing. Without
FABRIC_SCENE_SURFACE none of it is compiled, and UseSceneCollider does nothing.
Placement, attitude and custom pins
Origin is the middle of the sheet, on both axes and in both orientations, so placement does not depend on size:
change the resolution or the rest length and the sheet stays where you put it. Orientation picks the
plane — Vertical spans X and Y, Horizontal spans X and Z. A 96 × 64 sheet at rest length 0.06, vertical, with
Origin at (0, 3, 0), spans x −2.85…2.85 and y 1.11…4.89.
Extent is (count - 1) × RestLength per axis, exposed as Width and Height. To place a sheet by its suspended edge
rather than its middle, subtract half of Height. SeedRipple's starting wave narrows the sheet as built by a few
percent at most; BuiltWidth and BuiltHeight give that figure.
Rotation then tilts it to any attitude, pivoting about Origin, so it turns in place:
_fabric.Rotation = Quaternion.CreateFromYawPitchRoll(yaw, pitch, roll);
That is a starting attitude only. Gravity, wind and the colliders all stay in world space, so a tilted sheet still falls down Y and still lands on the ground plane. What holds a tilt is the pins, which rotate with everything else and never move. Any angle is safe, because a rigid rotation preserves every distance and dihedral angle: the rest lengths, anchor distances and rest angles seeded from the built shape stay valid, and the first step has nothing to correct. Texture coordinates are index-space, so neither orientation nor rotation affects them.
Pins are the union of the PinMode preset — LeftEdge unless you set it — and PinnedIndices, a mutable set of flat
grid indices, so FabricPinMode.None plus explicit indices is a fully custom set:
_fabric.PinMode = FabricPinMode.None;
_fabric.PinnedIndices.Add(_fabric.ParticleIndex(column: 0, row: 47));
_fabric.PinnedIndices.Add(_fabric.ParticleIndex(column: 32, row: 24)); // interior is fine
_fabric.Rebuild();
Any particle can be pinned, interior ones included: the long-range attachment metric is a multi-source shortest path
through the weave, so it starts from wherever the pins actually are. ParticleIndex(column, row) does the row-major
arithmetic and range-checks it, because swapping row and column yields a valid index almost every time.
Pins can change on the live sheet. SetPinned(index, pinned) pins a point where it hangs now, or lets it go — with no
kick, since a pin carries no motion — and IsPinned(index) reads it back. The pins' reach along the weave is
re-measured once before the next step, however many points changed, on the CPU and without reading anything back —
unless an UpdateParticles of your own has changed the sheet since, when the first SetPinned or IsPinned after it
reads the pins back once. PinMode and PinnedIndices still describe the next Rebuild().
// Let the top edge go, all but its corners. They drop from where they hang, at rest.
var top = _fabric.HeightInParticles - 1;
for (var column = 1; column < _fabric.WidthInParticles - 1; column++)
_fabric.SetPinned(_fabric.ParticleIndex(column, top), false);
Pins may move. Each particle stores the index of its nearest pin rather than that pin's position, so the attachment
resolves against wherever the pin is on the step it is read. The path length behind it describes the weave rather than
space, so it survives any amount of pin motion, and a host that animates a pinned edge needs nothing refreshed. The way
to move them is FabricEffect.UpdateParticles, which takes the whole sheet: ReadBack() it, move the pins, upload it.
That is a stall every time, and it needs a fresh readback every time, since an older array would rewind the cloth.
Only changing which particles are pinned invalidates the path lengths. SetPinned re-measures them by itself; after
changing IsPinned through UpdateParticles, call RefreshAnchors().
Rips and tears
The weave can be cut on the live sheet, without resetting the drape:
// A rip climbing from the free edge, in metres on the flat cloth: (0, 0) is the
// point ParticleIndex(0, 0), u runs along Width, v along Height.
var u = _fabric.Width * 0.45f;
var severed = _fabric.Cut(new Vector2(u, 0.0f), new Vector2(u + 0.4f, _fabric.Height * 0.6f));
// Triangles that spanned the cut are gone, so refresh the index buffer. The one
// allocated at build is never too small - tears only remove triangles.
_indices.SetData(_fabric.CreateTriangleIndices());
// ...and draw _fabric.TriangleCount triangles from here on.
Cut severs every thread its stroke crosses — structural, shearing, and the folds built over them — and returns how
many. The stroke is drawn on the flat cloth, so it lands in the same place at any resolution, and it takes effect
immediately: the severed threads stop pulling, the lips no longer share a normal, they collide as ordinary cloth rather
than being skipped as weave neighbours, and the pin distances are measured again through whatever weave remains, so a
piece cut free of every pin falls. Drawn from the plain list the lips come out jagged at grid scale; see Clean lips
below for lips that follow the stroke itself. Chain strokes for a rip that wanders — Cut(ReadOnlySpan<Vector2>) takes
the whole polyline in one call and re-measures the pin distances once for the chain rather than once per stroke. Every
point is checked before anything is cut, so a bad one throws and leaves the sheet as it was. Tear(indexA, indexB)
severs a single thread instead, ClearTears() mends everything in place, and Rebuild() always starts from whole
cloth — to open a scene pre-torn, cut right after it.
Rip takes the same strokes Cut does — a straight one, a polyline, a recorded drag — and severs the same threads with
all the same effects, but records no stroke: CreateCutMesh draws its lips jagged at the weave's scale, as torn cloth's
are, where a cut's are clipped clean along the knife.
Clean lips. CreateCutMesh() returns the same sheet with the damaged triangles clipped along the strokes that cut
them, at whatever angle those ran, so a straight cut draws as a straight cut rather than a staircase:
var mesh = _fabric.CreateCutMesh();
// Ids below ParticleCount are particles as before; ids at or above it name
// mesh.SeamVertices[id - ParticleCount] - lip vertices the vertex shader blends
// from live particles on their own side of the cut, so the lips separate when
// the rip opens. The mesh can hold MORE triangles than the whole sheet, so size
// the buffers from it and draw ITS TriangleCount.
_indexBuffer.SetData(mesh.Indices);
_seamBuffer.SetData(mesh.SeamVertices); // a StructuredBuffer of FabricSeamVertex
On the shader side, bind the seam buffer to FabricSeamVertices alongside FabricParticles and fetch every vertex
through FabricEvaluateVertex(vertexId, position, normal, texCoord). It ships in FabricParticleBuffer.fxh and draws
plain meshes identically, so one vertex shader covers both. The clipping is flat 2D geometry computed once per cut,
never per frame, and the simulation underneath is exactly the one the plain list draws — still torn thread by thread, so
the drawn lip and the simulated one differ by at most about a cell. The demo's cutting runs entirely through this path
if you want to see it working end to end.
Two sizes to keep on the host. The seam buffer stays at least one element long on whole cloth too, since the shader
declares it and a real resource has to sit behind the binding. And the placeholder vertex buffer covers every id the
indices name, ParticleCount + SeamVertices.Length. The demo's RefreshTopology does both, growing the buffers only
when a cut outgrows them.
What the clipped mesh does at the awkward cases:
- Only strokes can be clipped along. Damage done through
Tearhas no stroke and keeps its jagged hole. - A stroke's tip resting inside a cell draws closed, as cloth about to give rather than as a hole — unless the tip rests on, or just short of, a crossing stroke, which already severed the cloth there. The rip then opens all the way through to that crossing, so a T-shaped rip parts cleanly.
- Crossing strokes free all four quadrants of each other. Where two cuts meet, the seam point gets four copies, one per flap, told apart by which side of each stroke the flap lies on. Cross cuts, T-junctions and X-shaped cuts all open without the flaps staying stitched to one another.
- A drag sampled finely draws one lip. Every segment of a cut is recorded, joints and all, so a stroke sampled far finer than the grid parts as cleanly as a straight one.
- A cut through a line of points leaves no crack. The points belong to the side their surviving threads hold them to, and that side's lip shares them with the cloth beyond.
- A strip one particle wide still has its width. Between two cuts about a cell apart there is a single row of particles to blend from; its lips are drawn along the row and offset across it, along the cloth's normal.
- Heavily shredded cloth falls back to the jagged hole. A fragment whose supporting particles no longer hang together through the surviving weave is not drawn, rather than being stretched across separated cloth; so is a scrap holding fewer than two particles.
Cutting what the player can see. Cut takes flat-sheet coordinates because damage belongs to the weave, not to
wherever the cloth happens to be. That leaves one step to do: turning a drag on screen into those coordinates. While the
sheet still hangs near the plane it was built in you can intersect the cursor ray with that plane and subtract the
origin. Once the cloth has crumpled, that cuts where the sheet used to be — so pick against the sheet itself, which is
what the demo does:
// On press: one pose for the whole drag, so the cut lands where the preview shows it
// however far the cloth blows meanwhile.
_stroke = new FabricStroke(_fabric.CaptureSurface());
// While the button is held, once a frame. Your camera, your unprojection: the solver
// never sees a matrix or a viewport.
var near = GraphicsDevice.Viewport.Unproject(new Vector3(screen, 0.0f), _projection, _view, Matrix.Identity);
var far = GraphicsDevice.Viewport.Unproject(new Vector3(screen, 1.0f), _projection, _view, Matrix.Identity);
if (_stroke.Add(new Ray(near, far - near), out var hit))
_preview.Add(hit.World); // draw the preview from these
// On release: cut from the samples the preview drew - nothing is picked again.
var severed = _fabric.Cut(_stroke);
CaptureSurface() reads the sheet back once, so capture one per gesture. Each ray takes the nearest layer, and samples
on one layer join into a stroke, which breaks where it crosses a fold onto cloth it never passed over. Where the knife
left the cloth and came back across an open cut, the stroke carries on across it; a stroke that left the cloth within a
sample of a cut, or of the sheet's edge, is carried to it, since the last sample can land short and the piece between
would otherwise hang on by its last threads. A miss anywhere else — off a fold's silhouette, say — ends the stroke, and
the next hit starts a fresh one, which is what a knife lifted and put back down should do. Cut(rays) and
Cut(rays, surface) do all of this from a span of rays.
Which layer is yours to choose. A crumpled sheet stacks several layers under one point, and a hard press stacks
eight or more. Cut(rays) takes the nearest, a blade. For anything else, capture the pose and walk it:
var surface = _fabric.CaptureSurface(); // one readback; hold it for the whole gesture
Span<FabricSurfaceHit> hits = stackalloc FabricSurfaceHit[16];
var count = surface.Raycast(ray, hits); // nearest first, with Distance in metres
// Scissors: every layer within 2 cm of the front one, each its own polyline, matched
// by depth order - layer k of this ray continues layer k of the last. One list for
// all of them would zigzag from layer to layer, cutting straight through cloth between.
for (var k = 0; k < count && hits[k].Distance - hits[0].Distance < 0.02f; k++)
{
if (_layers.Count <= k) _layers.Add([]);
_layers[k].Add(hits[k].Cloth);
}
// On release, one Cut per layer.
foreach (var layer in _layers)
_fabric.Cut(CollectionsMarshal.AsSpan(layer));
Matching layers by depth order is the simplest rule, and holds while the stack under the knife keeps its count; a rule
of your own can follow Distance instead.
Picking runs against the cut mesh, lips and all, so what can be picked is exactly what CreateCutMesh draws. It walks a
uniform grid over the pose rather than testing every triangle, so a ray costs microseconds even on a sheet of half a
million triangles; a ray through a shared edge reports its layer once. A surface knows which sheet and which build it
came from: Cut(stroke) and Cut(rays, surface) throw for one from another sheet or from before a Rebuild(), rather
than cutting the wrong weave. Raycast itself does not check, so hits you gather yourself, as the scissors above do,
are yours to drop when the sheet is rebuilt — Rebuilt says when.
Costs and edge cases. A cut, a rip or a tear is an event rather than per-frame work, and only what it changed is
worked out again, on the CPU with no readback: the folds and the GPU's tear mask about the severed threads — uploaded
for those rows alone — and the pin distances only for the points whose path to a pin ran through one, measured again
from the points about them whose paths still stand. A tear across the foot of a curtain re-measures the strip below it,
not the curtain. Mending is the exception: ClearTears() works the whole sheet out again. With nothing pinned the pins
are skipped, and an uncut sheet pays nothing for the feature existing. The code all this runs is compiled on a worker
thread after the first Rebuild(), so the first cut or tear does not wait on the runtime's compiler either. In a 128 x
128 curtain torn in a gale, the first burst of tears found — two or three thousand threads — cost 3 to 4 ms against 32
before, and its cut mesh 0.6 against 13. Strokes are clipped to two cells past the sheet, so one drawn from far off it
costs only its part near it.
A stroke running exactly along a line of points severs the crossing threads on one side only — deterministic, but arbitrary, so offset the stroke slightly to choose the side. A stroke running exactly along a thread never severs that thread, just as scissors sliding along a thread do not cut it. And the aerodynamic-pressure model does not see holes: the air keeps treating the sheet as unbroken, so a badly torn parachute still catches more air than it should.
CopyTearState() returns the damage, one word of FabricTearFlags bits per point. That is what the diagnostics take on
a torn sheet, and it is enough to save damage and restore it through Tear — though damage restored that way has no
strokes, so CreateCutMesh draws its lips jagged.
Tearing under strain. With FabricSettings.UseStrainTearing on, a thread gives way where it is stretched past
TearStretch times its rest length — a curtain snagged in a gale rips, and a piece torn from every pin falls. A pass
before each step measures every thread over the positions the step starts from, and one stretched too far stops
holding at once: the step solves without it, its lips collide as ordinary cloth, and nothing waits for the CPU. The rest
of the sheet's state — the triangles across the tear, the folds over it, the pins' reach through what is left — is the
CPU's, and follows when you hand it the tears found:
// Once in a while: FabricEffect.TearsFound is the GPU's record of every thread found torn since the
// sheet was built or mended. ReadFoundTears reads it back and stalls until the GPU catches up, as
// ReadBack does, so call it every few frames rather than every one...
_fabric.ReadFoundTears();
// ...or read the buffer back without a stall your own way - a staging copy mapped a frame or two
// later - and hand over what came back. Only threads new to the sheet count.
var added = _fabric.ApplyFoundTears(words);
if (added > 0) _indices.SetData(_fabric.CreateTriangleIndices()); // or CreateCutMesh, as after a cut
TearsFound holds FabricEffect.TearsFoundHeaderWords words — the build it belongs to, then how many threads have been
found — and then a word a particle, in FabricTearFlags' thread bits. Reading the count alone, the second word, tells
whether there is anything new to read the whole buffer for. A read from before the last Rebuild() names another
build, and ApplyFoundTears leaves it alone; ClearTears() mends what was found too, heard of yet or not. Until a tear
is handed over, its triangles stay drawn across the gap the GPU opened, the folds across it still bend, and the pins'
reach still holds a piece torn free of them — so hand them over soon, every few frames: each read that finds something
new makes the triangle list or the cut mesh again over the whole sheet, a fraction of a millisecond for 128 x 128
points, while the rest is worked out about the new threads alone. Tears found under strain have no strokes: their lips
are jagged, and their cut mesh is the plain list's triangles, made without the clipping's work.
How far a thread stretches before TearStretch is reached is this solver's, not real cloth's: Jacobi rounds converge
slowly, so a sheet under load stretches further than its stiffness suggests, and a finer weave further still at the same
rounds. A 2 x 2 m sheet of 41 x 41 points pinned along its top, in a 1.5 m/s breeze, stretched no thread past 1.15; in
a 12 m/s gale, 1.85 at the most and 1.73 for the hundredth furthest — and at a TearStretch of 1.3 it tore from its
rail within a second. A 128 x 128 sheet of the same size, at the same strength in the same gale, all but shredded. The
default, 1.5, leaves a breeze alone and gives in a gale.
Drawing it
The solver leaves the particle state on the GPU. To draw the cloth, fetch from that buffer in your own vertex shader,
indexed by SV_VertexID — no vertex stream, no readback.
Shader. The headers are already in your content tree at Content/Effects/Fabric, next to the solver the package
also copied. Include FabricParticleBuffer.fxh: it brings the particle layout, the grid dimensions, the
texture-coordinate convention and the FabricParticles binding, so you declare nothing yourself. The path is relative
to your own .fx, because that is how MGCB resolves #include; the one below assumes yours sits in Content/Effects.
#include "Fabric/FabricParticleBuffer.fxh"
float4x4 WorldViewProjection;
struct VSOutput
{
float4 Position : SV_POSITION;
float3 Normal : NORMAL0;
float2 TexCoord : TEXCOORD0;
};
VSOutput VS(float unused : POSITION0, uint vertexId : SV_VertexID)
{
FabricParticle p = FabricParticles[vertexId];
VSOutput output;
output.Position = mul(float4(p.Position, 1.0), WorldViewProjection);
output.Normal = p.Normal;
output.TexCoord = FabricTextureCoordinates(vertexId);
return output;
}
(FabricParticleBuffer.fxh pulls in FabricParticle.fxh, which the solver also uses and which declares no bindings.
Include that one directly only if you want the struct without the read binding.)
Those headers are a copy in your tree, and a copy outlives the upgrade that changes what it describes.
FabricParticle.fxh carries #define FabricShaderContractVersion, and FabricEffect compares it with
FabricParticle.ShaderContractVersion at load time. It throws if the two disagree, and also if the define is missing,
since a header predating the contract is older than the assembly by at least the release that introduced it. The version
is bumped for any change of shape: a field added, removed, reordered or resized, a grid parameter renamed, the texture
coordinates laid out differently; and for any input added between the assembly and the solver, which a mismatched
pair would silently miss: an older shader is never given it, a newer one never has it set. GroupSize and
ContactCandidateCapacity in FabricSimulation.fxh are checked the
same way, and the loaded effect must have the solver's technique and passes.
A byte count cannot catch this. Swap two fields of the record and both sides still measure sixty-four bytes, so the
cloth reads one field as another, which looks like a broken solver rather than a stale header. The check is best-effort:
it walks up from the executable looking for Content/Effects/Fabric, and a deployment that kept only the compiled
shader has nothing to compare against and is not failed for it.
Host. Bind the buffer and the grid dimensions every frame: the solver keeps two record buffers and swaps them as
it steps, and SetParticles replaces them, so which buffer holds the latest step is the solver's own business.
_cloth here is your effect, the one that included the header; the buffer comes from the solver, and the
grid from the sheet as built:
// Effect _cloth = Content.Load<Effect>("Effects/Cloth"); your shader
_cloth.Parameters["FabricParticles"].SetValue(_fabric.Effect.ParticleBuffer);
_cloth.Parameters["FabricWidthInParticles"].SetValue(_fabric.WidthInParticles);
_cloth.Parameters["FabricHeightInParticles"].SetValue(_fabric.HeightInParticles);
Set them on your effect, never on the solver's. Its shader declares no FabricParticles — it binds
FabricParticlesInput and FabricParticlesOutput — so that parameter is null there, and its grid sizes are its own,
set by SetParticles: overwriting them breaks the solve. FabricEffect.Shader is for a wrapping effect's own
uniforms, like a wind function's.
Topology. Fabric.CreateTriangleIndices() returns the triangle list — two per grid cell, indexing the particle
buffer directly. Upload it to a 32-bit IndexBuffer after each Rebuild() — the Rebuilt event says when, automatic
ones included; 16-bit overflows silently past 65,536 particles. A draw call still needs a bound vertex buffer, but
nothing reads it, so one float per vertex is enough.
Three things the shader must respect:
- World space. Particles are simulated in world space, so draw them with an identity world matrix. Gravity, wind and
collider positions are all world vectors, so a world matrix that moved the mesh would put the visible cloth somewhere
other than where the solver thinks it is. To move the sheet, change
Originand rebuild. - No back-face culling. Both sides become visible as soon as the cloth folds. Use
RasterizerState.CullNoneand flip the normal towards the camera in the pixel shader. - Use the solver's normal.
FabricParticle.Normalis computed on the GPU each step, for the pose the step ends in; until the first step it holds the flat sheet's facing. Deriving your own from the triangle makes shading disagree with the physics along every crease.
Between steps. The solver steps at SolverFrequencyHz, 120 by default, whatever the frame rate. MonoGame's default
fixed 60 Hz update makes that exactly two steps a frame, but other rhythms — IsFixedTimeStep = false on a 144 Hz
monitor, say, or 90 Hz VR — don't line up: some frames get no step and redraw the same pose, others get two. To draw
between steps instead, bind InterpolationFraction every frame and pass it to the overload of FabricEvaluateVertex
that takes it, or to FabricInterpolatedPosition if you fetch particles yourself:
_cloth.Parameters["ClothInterpolation"].SetValue(_solver.InterpolationFraction);
float ClothInterpolation; // your own uniform, any name
FabricEvaluateVertex(vertexId, ClothInterpolation, worldPosition, normal, texCoord);
Each particle is drawn that fraction of the way from the previous step's pose to the latest, chosen so the cloth moves
evenly on every frame. The price is latency. Drawing the latest step leaves the drawn cloth a varying distance behind
the clock, which is what stutters; even motion needs that lag constant, so it has to be as long as the rhythm's worst
frame. The fraction keeps it the least the rhythm allows — nothing when frames line up with the steps, so binding it at
MonoGame's fixed 60 Hz changes nothing; 3.5 ms on average at 144 Hz; never more than a step. When the rhythm changes the
lag rises at once and sheds slowly, so the cloth never jumps. Pins are drawn where they are. Normals blend by the same
fraction, between the pose a step began in (PreviousNormal, packed into four bytes) and the one it ended in, so
shading turns as smoothly as the cloth moves; FabricInterpolatedNormal does it for a particle you fetch yourself. The
overload without a fraction draws the latest step, exactly as before.
Knobs
Every tunable is a documented property, and the XML docs ship with the package, so IntelliSense carries the defaults, the ranges, and the cases where two knobs are a pair rather than independent.
FabricSettings |
|
|---|---|
| Sheet | WidthInParticles, HeightInParticles, RestLength, SeedRipple — read at Rebuild(); AutoRebuild to have it called for you |
| Solver | SolverFrequencyHz, RelaxationIterations, MaxStepsPerFrame, Stiffness, CompressionSlack, Damping, UseShearingConstraints |
| Bending | UseBendingConstraints, BendingStiffness, BendingIterations, BendingPlasticYieldDegrees, BendingPlasticRate |
| Attachment | UseLongRangeAttachments |
| Physics | Gravity, ArealDensity |
| Air | DragCoefficient, LiftCoefficient, AirDensity, Wind, UseAerodynamicPressure, AddedMassCoefficient |
| Rest | UseRestThreshold, RestSpeedThreshold, RestDriveFraction, UseRestHold, RestHoldDelay, RestHoldWakeFraction |
| Colliders | UseSphereCollider, SphereColliderCenter, SphereColliderRadius, UseGroundCollider, GroundColliderHeight, ColliderFriction |
| Scene | UseSceneCollider, SceneColliderThickness — with a FABRIC_SCENE_SURFACE of yours |
| Self-collision | UseSelfCollision, SelfCollisionThicknessRatio, SelfCollisionStiffness, SelfCollisionFriction, ContactIterations |
| Tearing | UseStrainTearing, TearStretch — the tears found handed over through ApplyFoundTears |
Fabric (read at Rebuild()) |
|
|---|---|
| Placement | Origin, Orientation, Rotation |
| Pins | PinMode, PinnedIndices |
SetPinned, Cut, Tear and ClearTears are the exception on Fabric: they act on the live sheet, and Rebuild()
mends everything and puts the pins back as PinMode and PinnedIndices describe them.
Damping, ColliderFriction, SelfCollisionFriction and BendingPlasticRate are fractions per 1/120 s — per step at
the default frequency — and are rescaled to the step length, as is the motion the cloth carries from step to step. So
raising SolverFrequencyHz, even while running, buys stability at a cost and leaves the feel alone.
Derived and read-only: TimeStep (from SolverFrequencyHz), ShearingRestLength, ParticleMass,
SelfCollisionThickness, MinimumCompressionSlackForContacts.
UseAerodynamicPressure supports sheets up to 4,096 particles along their longer side; Rebuild() and Apply throw
beyond that.
One pairing to keep: CompressionSlack ships at 0.375, which is MinimumCompressionSlackForContacts at the default
thickness. Below that figure the threads fold pairs of points closer than self-collision allows, and a pile re-fights
the same contacts every round instead of settling. So raise the slack with SelfCollisionThicknessRatio (half of it),
and lower it only for cloth that never lies on itself, which may then crumple tighter.
To put every tunable back to its default, assign a fresh FabricSettings to Fabric.Settings and call Rebuild().
That is what you want between presets, since a knob one preset sets and the next does not would otherwise leak across.
Set the grid fields again on the new instance: WidthInParticles, HeightInParticles and RestLength all default to
0, so every setup supplies its own.
Rest
Verlet feeds solver noise back as momentum, so a settled sheet would twitch forever; the rest deadband discards carried
motion below RestSpeedThreshold, unless the force on the point is still driving it (RestDriveFraction) or the motion
persists on a point touching nothing — noise is as likely one way as the other and averages away over a few steps,
while a sheet settling to a new lean as a gust dies does not, so a running average above a quarter of the threshold is
kept; a point touching something is stopped all the same, as friction stops slow sliding. That is not enough for a
pile: every resting point still gets gravity's push each step and an approximate push back from what it
rests on, and the residuals creep — a heap spread flat over a minute and never stopped moving. UseRestHold adds what
friction adds. A point that has rested for RestHoldDelay and is supported — touching the floor, a collider or other
cloth, or joined by a thread to a held point — is held: it still runs every round with every force, except that a push
it can ignore is not applied to it, and at the end of the step a net move within its wake was noise and snaps back to
where the step began; anything more was a pull, by a thread or a contact, and the point is free. A resting point
carried by something gets no push into its carrier, which keeps a settling pile from sinking into itself; of the
rest — down a slope, or from the wind — static friction holds what lies within its cone, whose coefficient is
f / (1 − f) for ColliderFriction or SelfCollisionFriction set to f — the setting itself, not its per-step
rate, so 0.35 holds about 28°, 0.5 holds 45° and 1 any slope, at any SolverFrequencyHz — and the hold ignores what is
left under RestHoldWakeFraction of RestSpeedThreshold per
1/120 s, 3.6 m/s² at the defaults. A larger push frees a held point if it moves it — braced by its neighbours it stays
held — and drives a point that is not held, which then slides under the kinetic friction rather than creeping by one
push a step. The wake is RestHoldWakeFraction of the rest distance at 120 Hz, 0.25 mm at the defaults, for a point
touching something: a pull accumulates in its threads until it passes that. For a point hanging on held cloth, whose
only push is gravity braced by its threads, the wake is the push limit, which the residual it leaves follows. Pushes
are accelerations and pulls distances, each stated at the reference rate, so none of this changes with the step rate.
Its neighbours treat a held point like any other, never as a pin: full corrections against a frozen point overshoot and
wake the pile. A hanging sheet touches nothing and is never held, so it swings and settles exactly as before.
What it costs: cloth lying on something ignores pushes under 3.6 m/s² — a breeze under about 1 m/s — and a collider
sinks 0.25 mm into held cloth before it yields, at any step rate. Past about 300 Hz a step's own residual meets those
distances and the hold errs toward holding: a sheet draped over a ball that slides off in five seconds at 60 to 240 Hz
stays put at 480. SampleHeldFraction() says how much of the sheet is held; a pile at rest reads 1.
Cost
ContactIterations and BendingIterations decide the frame time on a large sheet: they cap how many of the relaxation
iterations also solve contacts and bending. The neighbourhood search behind contacts runs once a step, gathering each
particle's partners — at most FabricEffect.ContactCandidateCapacity — and every contact round then tests only those.
Bending runs a pass of its own before each round that solves it, solving every fold once and letting each particle
gather its share, rather than each particle solving all twelve of its folds. Both are still the knobs to turn first
on a big sheet. Zero — FabricSettings.EveryRound — means every iteration.
Diagnostics
FabricEffect.LastStepCount, DispatchesPerStep, IsSaturated (the solver hit MaxStepsPerFrame and shed the
backlog), Time, TotalStepCount, and SampleRestingFraction() — how much of the sheet is inside the rest deadband,
its carried motion discarded as noise. That is not the same as still: the constraints and contacts may go on moving a
point inside it. SampleHeldFraction() is the stricter figure, how much is held exactly still (see Rest under
Knobs). Both are GPU readbacks, so sample them a few times a second rather than every frame. ReadBack() returns the
particle array for the checks below and for your own, at the cost of a full stall: take one array and run everything you
need over it, rather than reading the sheet back once per question.
BorrowedTorch.FabricSimulator.Diagnostics holds the two measurements a screenshot cannot give you.
PenetrationCheck.Run(particles, width, thickness) counts pairs of non-weave-neighbour particles closer together than
the cloth is thick, and separately those overlapping by more than a quarter of it — which is what "the cloth is not
passing through itself" actually means. CreaseCheck.Run(particles, width, height) compares the live dihedral angles
against the rest angles the plasticity model has set, which separates a sheet folded because something presses on it
from a sheet folded because it wants to be. Both take the array from ReadBack(), both work from that array alone,
and both allocate freely: they are diagnostics, not frame work. On a torn sheet, pass them the array from
CopyTearState() as well, so the lips of a rip count as touching cloth rather than as weave neighbours, and the folds a
rip has killed are not measured across the gap. NumericChecks.IsFinite is the guard they share, and the first thing to
reach for in a check of your own: a diverged solver fills the buffer with NaN, and a statistic that averaged one in is
worse than no statistic.
PenetrationCheck deliberately does not use the solver's spatial hash. It builds its own, unbounded and exact-keyed,
because a check that shares what it checks agrees with it by construction: a bucket the solver overflowed holds a pair
the solver never tested, and a check reading the same buckets would not test that pair either. Keep that separation if
you extend it.
SampleWorstStepMotion() reports how close the sheet has come to outrunning its own collision tests: PeakRatio, the
furthest single-step move as a multiple of the collision thickness, and FastParticleSteps, how many particle-steps
exceeded one. Contacts are tested where particles ended up, not along the path they took, so above one a layer can cross
another with nothing able to see it — neither the solver nor PenetrationCheck. The margin depends on your grid rather
than on the solver: thickness is a fraction of the spacing, so refining the sheet lowers the bar while gravity leaves
the speeds alone. Check it at the resolution you ship. If it reads above one, raising SolverFrequencyHz is the cheap
fix, and doubling it roughly halves the number. It is measured only while UseSelfCollision is on; the peak keeps its
last value until the next Rebuild().
SampleSpatialHashOverflow() reports what self-collision lost: DroppedEntriesPerStep, particles the hash could not
file because their bucket was full, and PeakOccupancy, the deepest bucket seen since the sheet was built — zero until
one overflows, and otherwise the size SpatialHashMaxPerCell would have to grow to. DroppedCandidatesPerStep and
PeakCandidates say the same of the per-particle partner lists and ContactCandidateCapacity; only a deep pile fills
one. A dropped entry is a contact the solver never saw, and it leaves no trace in the positions, so this is the one
thing a check of your own on the particle array cannot reconstruct. It separates cloth that interpenetrates because the
contact response was too weak from cloth that interpenetrates because the neighbour was never in the bucket. It reads
the same buffer as SampleRestingFraction() and is fetched at most once per step, so polling both together costs one
stall rather than two.
SampleCoincidentContacts() counts contacts between particles that sat at the same point with no history to tell them
apart, which the solver pushes apart along an axis picked from their indices — a guess that can swap two layers. Only
cloth crushed hard gets there. It reads zero unless the solver is compiled with FABRIC_COUNT_COINCIDENT defined, since
the count costs an atomic in the innermost contact loop, and it comes from the same fetch as the two above.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0-windows7.0 is compatible. |
-
net10.0-windows7.0
- BorrowedTorch.Math (>= 0.3.0)
- BorrowedTorch.MonoGame.Framework.Compute.WindowsDX (>= 3.8.6.101)
- BorrowedTorch.Randomness (>= 1.4.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on BorrowedTorch.FabricSimulator:
| Package | Downloads |
|---|---|
|
BorrowedTorch.Engine.AdditionalFeatures
Kindling, Borrowed Torch's game engine: its additional features - sound, post effects, vegetation, fabric, sprites, collisions and culling - for a game's own code to build against beside the engine |
GitHub repositories
This package is not used by any popular GitHub repositories.