Docs / Fabric simulation

Glossary: FabricEffect

The members of FabricEffect, in alphabetical order.

Color legend plain property method

Owns the particle buffers and runs the solver: each step is a series of compute dispatches of FabricCompute.fx over the sheet, whose positions stay on the GPU.

A sealed class that implements IDisposable, in the namespace BorrowedTorch.FabricSimulator.Simulation. Double-buffered: the passes read neighbors, so updating in place would race. Each instance runs its own copy of the loaded effect, so any number of sheets can share one ContentManager, one FabricEffect each. A Fabric drives it; without one, SetParticles, Apply and Update do. Three read-only record structs nested in it carry its diagnostics: FabricEffect.SpatialHashOverflow, FabricEffect.StepMotion and FabricEffect.CoincidentContacts. The sheet and step page shows it in context, with code. Use it from the thread that owns the graphics device.

Names are colored by what they are: a property or a method; values and fields keep the plain color.

Properties

DispatchesPerStep →

int · Read-only. The compute dispatches one step makes, as the settings last applied decide: one to integrate; one per round of RelaxationIterations, at least one, and one more for each round that solves bending; three for self-collision, to clear the spatial hash, fill it and gather each point’s partners; and with UseAerodynamicPressure, one per level of its pyramid. Per step, not per frame: times LastStepCount for a frame, and at a high frame rate most frames run none.

InterpolationFraction →

float · Read-only. Where to draw between the last two steps, from 0, the previous step’s pose, to 1, the latest. Chosen so the drawn cloth moves evenly at the least constant lag the frame rhythm allows: none when frames line up with the steps, where it settles at 1, as under MonoGame’s fixed 60 Hz; 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. Bind it to a uniform of your own every frame, for FabricEvaluateVertex or FabricInterpolatedPosition. Follows Update; Step alone leaves it where it was.

IsSaturated →

bool · Read-only. Whether the last Update ran MaxStepsPerFrame steps and still owed time, which it dropped rather than carry into the next frame: the cloth ran slower than the clock that frame. false after SetParticles.

LastStepCount →

int · Read-only. How many steps the last Update ran: 0 for a frame shorter than what was left of a step, two a frame under MonoGame’s fixed 60 Hz at the default 120 Hz, at most MaxStepsPerFrame.

ParticleBuffer →

StructuredBuffer · Read-only. The particles as of the latest step, one FabricParticle record each, in the layout FabricParticleBuffer.fxh declares, for your vertex shader’s FabricParticles. Bind it every frame: the solver keeps two record buffers and swaps them as it steps, and SetParticles replaces them. null before the first SetParticles, and after Dispose. Never bind it to the solver’s own effect, which declares no FabricParticles.

ParticleCount →

int · Read-only. The particles the buffers hold: 0 before SetParticles and after Dispose.

Shader →

Effect · Read-only. This sheet’s own copy of the compiled solver, cloned from the one the ContentManager loaded and disposed with it: the place to set a wrapping effect’s own uniforms, such as a wind function’s knobs. Set them here, not on the instance Content.Load returns, which every FabricEffect copies from. Not for drawing: it declares no FabricParticles. Leave its grid sizes and buffers alone: SetParticles sets them, and the solve depends on them.

Time →

float · Read-only. Simulated seconds since the sheet was uploaded: one TimeStep more at every step. A clock for your own gusts, which should follow the cloth rather than the frame when it falls behind. Wind functions in HLSL see it as FabricTime. Back to 0 at SetParticles.

TotalStepCount →

long · Read-only. Steps since the sheet was uploaded. Back to 0 at SetParticles.

Fields

ComputeGroupSize →

int · Constant, 256. Threads per compute group: each dispatch covers the sheet in groups of this many. Must equal GroupSize in FabricSimulation.fxh, or each dispatch covers only part of the sheet, and the rest freezes; the constructor checks it when it can find the header.

ContactCandidateCapacity →

int · Constant, 32. The self-collision partners each point keeps per step: gathered once a step, tested at every round that solves contacts. Must equal ContactCandidateCapacity in FabricSimulation.fxh, which the constructor checks as it does ComputeGroupSize. A point with more partners loses the rest for that step, which only a crushed pile reaches; SampleSpatialHashOverflow reports it.

DefaultEffectPath →

string · Constant, "Effects/Fabric/FabricCompute". Where the package’s content build puts the compiled solver, for a ContentManager rooted at Content: what the constructor loads unless told otherwise.

MaxParticles →

int · Constant, 16,776,960: 65,535 groups of ComputeGroupSize, the most one compute dispatch can cover. The largest sheet: Rebuild and SetParticles refuse more.

SpatialHashMaxPerCell →

uint · Constant, 32. Entries per bucket of the spatial hash self-collision files the points in. A point that finds its bucket full isn’t filed, and its contacts go unseen for that step; SampleSpatialHashOverflow reports it. A crushed pile wants about 30: with 16, its contacts changed from step to step and it never came to rest.

Methods

FabricEffect() →

FabricEffect(GraphicsDevice graphicsDevice, ContentManager contentManager, string effectPath = DefaultEffectPath) · Loads the solver through the content pipeline and takes a copy of it for this sheet, Shader: one ContentManager hands every caller the same instance, and the buffers and uniforms belong to one sheet. Holds no sheet until SetParticles, which Rebuild calls. The device needs GraphicsProfile.HiDef, the profile with a compute stage.

Throws ArgumentNullException for a null device or content manager, and InvalidOperationException when the effect has no FabricTechnique or lacks one of its eight passes, or when a shader header it can find disagrees with this assembly: FabricShaderContractVersion in FabricParticle.fxh, or GroupSize or ContactCandidateCapacity in FabricSimulation.fxh. It looks for the headers in Content/Effects/Fabric/ beside the executable and in the folders above it; a deployment that kept only the compiled shader has nothing to compare, and passes.

Parameter Type Description
graphicsDevice GraphicsDevice The device the buffers are made on and the passes dispatched on.
contentManager ContentManager Loads the compiled solver.
effectPath string The solver’s content path. Default: DefaultEffectPath, the package’s own. Name your own effect here when it wraps FabricCompute.fx, to add a wind function.

Apply() →

Apply(FabricSettings settings) · Uploads every setting, cheap enough to call every frame: they take effect at the next step. The grid comes from SetParticles, never from the settings, and the spacing from the settings’ RestLength. Makes the buffers self-collision, bending and pressure need, sized to the sheet, the first time they are switched on. A Fabric calls it before every step, with the spacing it was built with: leave it to Update on a sheet a Fabric drives.

Everything is checked before anything is uploaded: throws ArgumentNullException for null settings, ArgumentException for a setting that isn’t a finite number or a SolverFrequencyHz or RestLength that isn’t positive, naming it, and InvalidOperationException for UseAerodynamicPressure on a sheet over 4,096 points along its longer side.

Parameter Type Description
settings FabricSettings The settings to upload.

Dispose() →

Dispose() · Releases every buffer and this sheet’s copy of the effect. The instance is unusable afterwards: its methods throw ObjectDisposedException, except Dispose, which does nothing the second time. Call it from UnloadContent.

ReadBack() →

ReadBack() · Returns FabricParticle[]: a copy of every particle as of the latest step, in flat index order, see ParticleIndex. It waits for the GPU to catch up, a full stall: use it for events and diagnostics, not every frame, and take one array for every check you run rather than one per question. An empty array before SetParticles.

SampleCoincidentContacts() →

SampleCoincidentContacts() · Returns FabricEffect.CoincidentContacts: the contacts between points the solver found at the same spot with no history to tell them apart, since they began the step at one spot too, so it pushed them apart along an axis picked from their indices, a guess that can put two layers on each other’s side. Only cloth crushed hard gets there. Always zero unless the solver was compiled with FABRIC_COUNT_COINCIDENT defined, since the count costs an atomic in the innermost contact loop. A GPU readback, so a stall: sample it a few times a second, not every frame. The counters behind every Sample method are fetched at most once per step, so sampling several of them together costs one stall. default before SetParticles.

SampleHeldFraction() →

SampleHeldFraction() · Returns float: the share of the unpinned points held exactly still by UseRestHold, over the steps since the last call. The stricter figure than SampleRestingFraction: 1 for a pile at rest. Always 0 without the hold, 1 when every point is pinned, and 0 before SetParticles. When the hold was off, or the pins changed, during the window, it starts a new window and returns the last figure meanwhile. A GPU readback, so a stall: sample it a few times a second, not every frame. The counters behind every Sample method are fetched at most once per step, so sampling several of them together costs one stall.

SampleRestingFraction() →

SampleRestingFraction() · Returns float: the share of the unpinned points inside the rest deadband, their carried motion discarded as noise, over the steps since the last call, so a settled sheet reads 1 however it is pinned. Not the same as still: the threads and contacts may go on moving a point inside it; SampleHeldFraction is the figure for still. 1 when every point is pinned, and 0 before SetParticles. When the deadband was off, or the pins changed, during the window, it starts a new window and returns the last figure meanwhile. A GPU readback, so a stall: sample it a few times a second, not every frame. The counters behind every Sample method are fetched at most once per step, so sampling several of them together costs one stall.

SampleSpatialHashOverflow() →

SampleSpatialHashOverflow() · Returns FabricEffect.SpatialHashOverflow: what self-collision lost, the points the spatial hash couldn’t file and the partners a full list left out, per step since the last call, and the deepest bucket and longest list wanted since the sheet was uploaded. A contact lost this way leaves no trace in the positions, so this is the one thing a check of your own on ReadBack’s array can’t work out: it tells cloth that passes through itself because a neighbor was never seen from cloth whose contacts were answered too weakly. After self-collision was off, it starts a new window and returns the last rates meanwhile. A GPU readback, so a stall: sample it a few times a second, not every frame. The counters behind every Sample method are fetched at most once per step, so sampling several of them together costs one stall. default before SetParticles.

SampleWorstStepMotion() →

SampleWorstStepMotion() · Returns FabricEffect.StepMotion: how close the sheet has come, since it was uploaded, to outrunning its own collision tests. Contacts are tested where the points end a step, not along the way, so a point that moves more than the cloth’s thickness in one step can cross another layer with nothing able to see it. The thickness is a fraction of the spacing, so check at the resolution you ship; raising SolverFrequencyHz is the cheap fix. Measured only while UseSelfCollision is on. A GPU readback, so a stall: sample it a few times a second, not every frame. The counters behind every Sample method are fetched at most once per step, so sampling several of them together costs one stall. default before SetParticles.

SetParticles() →

SetParticles(FabricParticle[] particles, int widthInParticles, int heightInParticles) · Makes the buffers for a sheet and uploads it, whole and untorn, restarting the clock, Time and TotalStepCount, the diagnostics and the drawing lag. The next Update runs exactly one step, rather than catching up on the upload’s stall. Call it again to resize: everything is checked and the new buffers made before the old ones are released, so a failure leaves the previous sheet running. Bind ParticleBuffer again afterwards. Rebuild calls it; a sheet given to a Fabric’s effect this way makes that Fabric throw until it is rebuilt.

The pins come from the records: a point with IsPinned set is pinned where it is; any other with a positive MaxAnchorDistance hangs from the point AnchorIndex names, at most that far along the weave; and with none, no pin reaches it.

Throws ArgumentNullException for a null array; ArgumentOutOfRangeException for a width or height under 1; ArgumentException for an empty array, one whose length isn’t width × height, more than MaxParticles particles, a position, previous position or rest angle that isn’t finite, a NaN anchor distance, or an anchor outside the sheet; and InvalidOperationException when FabricParticle doesn’t marshal to its SizeInBytes.

Parameter Type Description
particles FabricParticle[] The sheet, in flat index order: row by row, row × widthInParticles + column.
widthInParticles int Points across. Every neighbor is found from it, so a wrong one shears the rows apart.
heightInParticles int Points from the first row to the last.

Step() →

Step() · Runs exactly one step: integrates the particles, applies the aerodynamic pressure when it is on, fills the spatial hash and gathers each point’s partners when self-collision is on, then runs the constraint rounds, the folds solved before each round that solves them. One more Time and TotalStepCount. Does nothing before SetParticles; apply settings with Apply first. Leaves InterpolationFraction where it was.

Update() →

Update(float elapsedSeconds) · Runs as many whole fixed steps as the time owed affords, up to MaxStepsPerFrame, and drops any backlog beyond rather than spiral, setting IsSaturated. Time left under a step waits for the next frame. Then moves InterpolationFraction on. Apply settings with Apply first. Does nothing before SetParticles, and the first call after it runs exactly one step, whatever the time.

Parameter Type Description
elapsedSeconds float The frame’s time, in seconds. NaN and negative times count as none, and anything over 0.25 s as 0.25 s.

UpdateParticles() →

UpdateParticles(FabricParticle[] particles) · Overwrites the particles of a sheet of the same size, without SetParticles’ restarts: for live changes to positions, pins, anchors or rest angles on a sheet that keeps simulating, such as moving a pinned edge. The clock carries on. The pins come from the records, as for SetParticles. Take the array from a fresh ReadBack every time: an older one rewinds the cloth. On a sheet a Fabric drives, call RefreshAnchors after changing which points are pinned. Does nothing before SetParticles.

Everything is checked before anything is uploaded: throws ArgumentNullException for a null array, and ArgumentException for one of another length, a position, previous position or rest angle that isn’t finite, a NaN anchor distance, or an anchor outside the sheet.

Parameter Type Description
particles FabricParticle[] Every particle, in flat index order, as many as ParticleCount.

UpdateTearState() →

UpdateTearState(uint[] tearState, bool anyTorn) · Uploads the damage: one word of FabricTearFlags per point, with the dead-fold bits set as Fabric sets them, which the solver expands into the mask its passes read. Cut, Tear and ClearTears call it for you. An upload, so no stall. Does nothing before SetParticles. Throws ArgumentNullException for a null array, and ArgumentException for one whose length isn’t ParticleCount.

Parameter Type Description
tearState uint[] The damage, one word per point, as CopyTearState returns it.
anyTorn bool Whether anything is torn: false lets the passes skip the mask altogether.