forked from bepu/bepuphysics1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolver.cs
322 lines (277 loc) · 13 KB
/
Solver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
using System;
using BEPUphysics.DeactivationManagement;
using BEPUutilities;
using BEPUutilities.DataStructures;
using BEPUutilities.Threading;
namespace BEPUphysics.Constraints
{
///<summary>
/// Iteratively solves solver updateables, converging to a solution for simulated joints and collision pair contact constraints.
///</summary>
public class Solver : MultithreadedProcessingStage
{
RawList<SolverUpdateable> solverUpdateables = new RawList<SolverUpdateable>();
internal int iterationLimit = 10;
///<summary>
/// Gets or sets the maximum number of iterations the solver will attempt to use to solve the simulation's constraints.
///</summary>
public int IterationLimit { get { return iterationLimit; } set { iterationLimit = Math.Max(value, 0); } }
///<summary>
/// Gets the list of solver updateables in the solver.
///</summary>
public ReadOnlyList<SolverUpdateable> SolverUpdateables
{
get
{
return new ReadOnlyList<SolverUpdateable>(solverUpdateables);
}
}
protected internal TimeStepSettings timeStepSettings;
///<summary>
/// Gets or sets the time step settings used by the solver.
///</summary>
public TimeStepSettings TimeStepSettings
{
get
{
return timeStepSettings;
}
set
{
timeStepSettings = value;
}
}
///<summary>
/// Gets or sets the deactivation manager used by the solver.
/// When constraints are added and removed, the deactivation manager
/// gains and loses simulation island connections that affect simulation islands
/// and activity states.
///</summary>
public DeactivationManager DeactivationManager { get; set; }
/// <summary>
/// Gets the permutation mapper used by the solver.
/// </summary>
public PermutationMapper PermutationMapper { get; private set; }
///<summary>
/// Constructs a Solver.
///</summary>
///<param name="timeStepSettings">Time step settings used by the solver.</param>
///<param name="deactivationManager">Deactivation manager used by the solver.</param>
public Solver(TimeStepSettings timeStepSettings, DeactivationManager deactivationManager)
{
TimeStepSettings = timeStepSettings;
DeactivationManager = deactivationManager;
multithreadedPrestepDelegate = MultithreadedPrestep;
multithreadedExclusiveUpdateDelegate = MultithreadedExclusiveUpdate;
multithreadedIterationDelegate = MultithreadedIteration;
Enabled = true;
PermutationMapper = new PermutationMapper();
}
///<summary>
/// Constructs a Solver.
///</summary>
///<param name="timeStepSettings">Time step settings used by the solver.</param>
///<param name="deactivationManager">Deactivation manager used by the solver.</param>
/// <param name="parallelLooper">Parallel loop provider used by the solver.</param>
public Solver(TimeStepSettings timeStepSettings, DeactivationManager deactivationManager, IParallelLooper parallelLooper)
: this(timeStepSettings, deactivationManager)
{
ParallelLooper = parallelLooper;
AllowMultithreading = true;
}
private System.Threading.SpinLock addRemoveLocker = new System.Threading.SpinLock();
///<summary>
/// Adds a solver updateable to the solver.
///</summary>
///<param name="item">Updateable to add.</param>
///<exception cref="ArgumentException">Thrown when the item already belongs to a solver.</exception>
public void Add(SolverUpdateable item)
{
if (item.Solver == null)
{
item.Solver = this;
bool taken = false;
addRemoveLocker.Enter(ref taken);
//addRemoveLocker.Enter();
item.solverIndex = solverUpdateables.Count;
solverUpdateables.Add(item);
addRemoveLocker.Exit();
DeactivationManager.Add(item.simulationIslandConnection);
item.OnAdditionToSolver(this);
}
else
throw new ArgumentException("Solver updateable already belongs to something; it can't be added.", "item");
}
///<summary>
/// Removes a solver updateable from the solver.
///</summary>
///<param name="item">Updateable to remove.</param>
///<exception cref="ArgumentException">Thrown when the item does not belong to the solver.</exception>
public void Remove(SolverUpdateable item)
{
if (item.Solver == this)
{
item.Solver = null;
bool taken = false;
addRemoveLocker.Enter(ref taken);
//addRemoveLocker.Enter();
solverUpdateables.Count--;
if (item.solverIndex < solverUpdateables.Count)
{
//The solver updateable isn't the last element, so put the last element in its place.
solverUpdateables.Elements[item.solverIndex] = solverUpdateables.Elements[solverUpdateables.Count];
//Update the replacement's solver index to its new location.
solverUpdateables.Elements[item.solverIndex].solverIndex = item.solverIndex;
}
solverUpdateables.Elements[solverUpdateables.Count] = null;
addRemoveLocker.Exit();
DeactivationManager.Remove(item.simulationIslandConnection);
item.OnRemovalFromSolver(this);
}
else
throw new ArgumentException("Solver updateable doesn't belong to this solver; it can't be removed.", "item");
}
Action<int> multithreadedPrestepDelegate;
void MultithreadedPrestep(int i)
{
var updateable = solverUpdateables.Elements[i];
updateable.UpdateSolverActivity();
if (updateable.isActiveInSolver)
{
updateable.SolverSettings.currentIterations = 0;
updateable.SolverSettings.iterationsAtZeroImpulse = 0;
updateable.Update(timeStepSettings.TimeStepDuration);
}
}
private Action<int> multithreadedExclusiveUpdateDelegate;
void MultithreadedExclusiveUpdate(int i)
{
var updateable = solverUpdateables.Elements[i];
if (updateable.isActiveInSolver)
{
updateable.EnterLock();
try
{
updateable.ExclusiveUpdate();
}
finally
{
updateable.ExitLock();
}
}
}
Action<int> multithreadedIterationDelegate;
void MultithreadedIteration(int i)
{
//'i' is currently an index into an implicit array of solver updateables that goes from 0 to solverUpdateables.count * iterationLimit.
//It includes iterationLimit copies of each updateable.
//Permute the entire set with duplicates.
var updateable = solverUpdateables.Elements[PermutationMapper.GetMappedIndex(i, solverUpdateables.Count)];
SolverSettings solverSettings = updateable.solverSettings;
//Updateables only ever go from active to inactive during iterations,
//so it's safe to check for activity before we do hard (synchronized) work.
if (updateable.isActiveInSolver)
{
int incrementedIterations = -1;
updateable.EnterLock();
//This duplicate test protects against the possibility that the updateable went inactive between the first check and the lock.
if (updateable.isActiveInSolver)
{
if (updateable.SolveIteration() < solverSettings.minimumImpulse)
{
solverSettings.iterationsAtZeroImpulse++;
if (solverSettings.iterationsAtZeroImpulse > solverSettings.minimumIterationCount)
updateable.isActiveInSolver = false;
}
else
{
solverSettings.iterationsAtZeroImpulse = 0;
}
//Increment the iteration count.
incrementedIterations = solverSettings.currentIterations++;
}
updateable.ExitLock();
//Since the updateables only ever go from active to inactive, it's safe to check outside of the lock.
//Keeping this if statement out of the lock allows other waiters to get to work a few nanoseconds faster.
if (incrementedIterations > iterationLimit ||
incrementedIterations > solverSettings.maximumIterationCount)
{
updateable.isActiveInSolver = false;
}
}
}
protected override void UpdateMultithreaded()
{
ParallelLooper.ForLoop(0, solverUpdateables.Count, multithreadedPrestepDelegate);
//By performing all velocity modifications after the prestep, the prestep is free to read velocities consistently.
//If the exclusive update was performed in the same call as the prestep, the velocities would enter inconsistent states based on update order.
ParallelLooper.ForLoop(0, solverUpdateables.Count, multithreadedExclusiveUpdateDelegate);
++PermutationMapper.PermutationIndex;
ParallelLooper.ForLoop(0, iterationLimit * solverUpdateables.Count, multithreadedIterationDelegate);
}
protected override void UpdateSingleThreaded()
{
int totalUpdateableCount = solverUpdateables.Count;
for (int i = 0; i < totalUpdateableCount; i++)
{
UnsafePrestep(solverUpdateables.Elements[i]);
}
//By performing all velocity modifications after the prestep, the prestep is free to read velocities consistently.
//If the exclusive update was performed in the same call as the prestep, the velocities would enter inconsistent states based on update order.
for (int i = 0; i < totalUpdateableCount; i++)
{
UnsafeExclusiveUpdate(solverUpdateables.Elements[i]);
}
int totalCount = iterationLimit * totalUpdateableCount;
++PermutationMapper.PermutationIndex;
for (int i = 0; i < totalCount; i++)
{
UnsafeSolveIteration(solverUpdateables.Elements[PermutationMapper.GetMappedIndex(i, totalUpdateableCount)]);
}
}
protected internal void UnsafePrestep(SolverUpdateable updateable)
{
updateable.UpdateSolverActivity();
if (updateable.isActiveInSolver)
{
SolverSettings solverSettings = updateable.solverSettings;
solverSettings.currentIterations = 0;
solverSettings.iterationsAtZeroImpulse = 0;
updateable.Update(timeStepSettings.TimeStepDuration);
}
}
protected internal void UnsafeExclusiveUpdate(SolverUpdateable updateable)
{
if (updateable.isActiveInSolver)
{
updateable.ExclusiveUpdate();
}
}
protected internal void UnsafeSolveIteration(SolverUpdateable updateable)
{
if (updateable.isActiveInSolver)
{
SolverSettings solverSettings = updateable.solverSettings;
solverSettings.currentIterations++;
if (solverSettings.currentIterations <= iterationLimit &&
solverSettings.currentIterations <= solverSettings.maximumIterationCount)
{
if (updateable.SolveIteration() < solverSettings.minimumImpulse)
{
solverSettings.iterationsAtZeroImpulse++;
if (solverSettings.iterationsAtZeroImpulse > solverSettings.minimumIterationCount)
updateable.isActiveInSolver = false;
}
else
{
solverSettings.iterationsAtZeroImpulse = 0;
}
}
else
{
updateable.isActiveInSolver = false;
}
}
}
}
}