forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulationDeterminismTest.cs
More file actions
349 lines (310 loc) · 12.8 KB
/
Copy pathSimulationDeterminismTest.cs
File metadata and controls
349 lines (310 loc) · 12.8 KB
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
using NUnit.Framework;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
using Unity.Physics.Systems;
using Unity.Mathematics;
using Unity.Collections;
using Unity.Jobs;
namespace Unity.Physics.Samples.Test
{
// Runs all simulation types on the same cloned physics world for a
// predefined number of steps and compares results.
// Only works in standalone build, since it needs synchronous Burst compilation.
#if !UNITY_EDITOR || UNITY_PHYSICS_INCLUDE_END2END_TESTS
[TestFixture]
#endif
class UnityPhysicsSimulationDeterminismTest
{
#if HAVOK_PHYSICS_EXISTS
public bool SimulateHavok = false;
#endif
static World DefaultWorld => World.DefaultGameObjectInjectionWorld;
// Put the names of demos that shouldn't
// be run in this test in this array
private static string[] s_FilteredOutDemos =
{
"SingleThreadedRagdoll", "LoaderScene",
"InitTestScene",
// Following demos are removed from SimulationDeterminism because they take
// too long to complete, and bring no special value
"PlanetGravity", "LargeMesh", "Force Field", "ComplexStacking"
};
protected static IEnumerable GetScenes()
{
var sceneCount = SceneManager.sceneCountInBuildSettings;
var scenes = new List<string>();
for (int sceneIndex = 0; sceneIndex < sceneCount; ++sceneIndex)
{
var scenePath = SceneUtility.GetScenePathByBuildIndex(sceneIndex);
var shouldAdd = true;
for (int i = 0; i < s_FilteredOutDemos.Length; i++)
{
if (scenePath.Contains(s_FilteredOutDemos[i]))
{
shouldAdd = false;
break;
}
}
if (shouldAdd)
{
scenes.Add(scenePath);
}
}
scenes.Sort();
return scenes;
}
#if !UNITY_EDITOR || UNITY_PHYSICS_INCLUDE_END2END_TESTS
[UnityTest]
[Timeout(240000)]
#endif
public virtual IEnumerator LoadScenes([ValueSource(nameof(GetScenes))] string scenePath)
{
// Log scene name in case Unity crashes and test results aren't written out.
Debug.Log("Loading " + scenePath);
LogAssert.Expect(LogType.Log, "Loading " + scenePath);
// Wait for next frame
yield return null;
// Number of steps to simulate
const int k_StopAfterStep = 100;
// Number of worlds to simulate
const int k_NumWorlds = 3;
// Number of threads in each of the runs (2nd run is immediate mode simulation)
NativeArray<int> numThreadsPerRun = new NativeArray<int>(k_NumWorlds, Allocator.Persistent);
numThreadsPerRun[0] = 4;
numThreadsPerRun[1] = 0;
numThreadsPerRun[2] = -1;
// Load the scene and wait 2 frames
SceneManager.LoadScene(scenePath);
yield return null;
yield return null;
var sampler = DefaultWorld.GetOrCreateSystem<BuildPhysicsWorldSampler>();
sampler.BeginSampling();
while (!sampler.FinishedSampling)
{
yield return new WaitForSeconds(0.05f);
}
var buildPhysicsWorld = DefaultWorld.GetOrCreateSystem<BuildPhysicsWorld>();
var stepComponent = PhysicsStep.Default;
if (buildPhysicsWorld.HasSingleton<PhysicsStep>())
{
stepComponent = buildPhysicsWorld.GetSingleton<PhysicsStep>();
}
// Extract original world and make copies
List<PhysicsWorld> physicsWorlds = new List<PhysicsWorld>(k_NumWorlds);
physicsWorlds.Add(sampler.PhysicsWorld.Clone());
physicsWorlds.Add(physicsWorlds[0].Clone());
physicsWorlds.Add(physicsWorlds[1].Clone());
NativeArray<int> buildStaticTree = new NativeArray<int>(1, Allocator.Persistent);
buildStaticTree[0] = 1;
// Simulation step input
var stepInput = new SimulationStepInput()
{
Gravity = stepComponent.Gravity,
NumSolverIterations = stepComponent.SolverIterationCount,
SolverStabilizationHeuristicSettings = stepComponent.SolverStabilizationHeuristicSettings,
SynchronizeCollisionWorld = true,
TimeStep = DefaultWorld.Time.DeltaTime
};
// Step the simulation on all worlds
for (int i = 0; i < physicsWorlds.Count; i++)
{
int threadCountHint = numThreadsPerRun[i];
if (threadCountHint == -1)
{
stepInput.World = physicsWorlds[i];
stepInput.World.CollisionWorld.BuildBroadphase(
ref stepInput.World, stepInput.TimeStep, stepInput.Gravity, true);
#if HAVOK_PHYSICS_EXISTS
if (SimulateHavok)
{
var simulationContext = new Havok.Physics.SimulationContext(Havok.Physics.HavokConfiguration.Default);
for (int step = 0; step < k_StopAfterStep; step++)
{
simulationContext.Reset(ref stepInput.World);
new StepHavokJob
{
Input = stepInput,
SimulationContext = simulationContext
}.Schedule().Complete();
}
simulationContext.Dispose();
}
else
#endif
{
var simulationContext = new SimulationContext();
for (int step = 0; step < k_StopAfterStep; step++)
{
simulationContext.Reset(stepInput);
new StepJob
{
Input = stepInput,
SimulationContext = simulationContext
}.Schedule().Complete();
}
simulationContext.Dispose();
}
}
else
{
bool multiThreaded = threadCountHint > 0 ? true : false;
#if HAVOK_PHYSICS_EXISTS
if (SimulateHavok)
{
var simulation = new Havok.Physics.HavokSimulation(Havok.Physics.HavokConfiguration.Default);
stepInput.World = physicsWorlds[i];
stepInput.World.CollisionWorld.ScheduleBuildBroadphaseJobs(
ref stepInput.World, stepInput.TimeStep, stepInput.Gravity, buildStaticTree, default, multiThreaded).Complete();
for (int step = 0; step < k_StopAfterStep; step++)
{
var handles = simulation.ScheduleStepJobs(stepInput, null, default, multiThreaded);
handles.FinalExecutionHandle.Complete();
handles.FinalDisposeHandle.Complete();
}
simulation.Dispose();
}
else
#endif
{
var simulation = new Simulation();
stepInput.World = physicsWorlds[i];
stepInput.World.CollisionWorld.ScheduleBuildBroadphaseJobs(
ref stepInput.World, stepInput.TimeStep, stepInput.Gravity, buildStaticTree, default, multiThreaded).Complete();
for (int step = 0; step < k_StopAfterStep; step++)
{
var handles = simulation.ScheduleStepJobs(stepInput, null, default, multiThreaded);
handles.FinalExecutionHandle.Complete();
handles.FinalDisposeHandle.Complete();
}
simulation.Dispose();
}
}
}
// Verify simulation results
for (int i = 0; i < physicsWorlds.Count - 1; i++)
{
for (int j = i + 1; j < physicsWorlds.Count; j++)
{
var world1 = physicsWorlds[i];
var world2 = physicsWorlds[j];
for (int k = 0; k < world1.NumBodies; k++)
{
var result1 = world1.Bodies[k].WorldFromBody;
var result2 = world2.Bodies[k].WorldFromBody;
if (!math.all(result1.pos == result2.pos))
{
Debug.Log($"{i} vs {j}: Expected: {result1.pos}, Actual: {result2.pos}");
}
if (!math.all(result1.rot.value == result2.rot.value))
{
Debug.Log($"{i} vs {j}: Expected: {result1.rot.value}, Actual: {result2.rot.value}");
}
}
}
}
// Clean up
{
SwitchWorlds();
numThreadsPerRun.Dispose();
buildStaticTree.Dispose();
for (int i = 0; i < physicsWorlds.Count; i++)
{
physicsWorlds[i].Dispose();
}
LogAssert.NoUnexpectedReceived();
}
}
[TearDown]
public void TearDown()
{
SwitchWorlds();
}
protected static void SwitchWorlds()
{
var entityManager = DefaultWorld.EntityManager;
entityManager.CompleteAllJobs();
var entities = entityManager.GetAllEntities();
entityManager.DestroyEntity(entities);
entities.Dispose();
foreach (var system in DefaultWorld.Systems)
{
system.Enabled = false;
}
DefaultWorld.Dispose();
DefaultWorldInitialization.Initialize("Default World", false);
}
[Burst.BurstCompile]
internal struct StepJob : IJob
{
public SimulationStepInput Input;
public SimulationContext SimulationContext;
public void Execute()
{
Simulation.StepImmediate(Input, ref SimulationContext);
}
}
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateAfter(typeof(BuildPhysicsWorld))]
class BuildPhysicsWorldSampler : SystemBase
{
public bool FinishedSampling = false;
public World DefaultWorld => World.DefaultGameObjectInjectionWorld;
public PhysicsWorld PhysicsWorld;
public BuildPhysicsWorld BuildPhysicWorldSystem;
public void BeginSampling()
{
Enabled = true;
}
protected override void OnCreate()
{
Enabled = false;
PhysicsWorld = new PhysicsWorld(0, 0, 0);
BuildPhysicWorldSystem = DefaultWorld.GetOrCreateSystem<BuildPhysicsWorld>();
}
protected override void OnUpdate()
{
BuildPhysicWorldSystem.GetOutputDependency().Complete();
if (BuildPhysicWorldSystem.PhysicsWorld.NumBodies != 0)
{
EntityManager.CompleteAllJobs();
PhysicsWorld.Dispose();
PhysicsWorld = BuildPhysicWorldSystem.PhysicsWorld.Clone();
Enabled = false;
FinishedSampling = true;
}
}
protected override void OnDestroy()
{
PhysicsWorld.Dispose();
}
}
#if HAVOK_PHYSICS_EXISTS
[Burst.BurstCompile]
internal struct StepHavokJob : IJob
{
public SimulationStepInput Input;
public Havok.Physics.SimulationContext SimulationContext;
public void Execute()
{
Havok.Physics.HavokSimulation.StepImmediate(Input, ref SimulationContext);
}
}
#endif
}
#if HAVOK_PHYSICS_EXISTS
#if !UNITY_EDITOR || UNITY_PHYSICS_INCLUDE_END2END_TESTS
[TestFixture]
#endif
class HavokPhysicsSimulationDeterminismTest : UnityPhysicsSimulationDeterminismTest
{
public HavokPhysicsSimulationDeterminismTest()
{
SimulateHavok = true;
}
}
#endif
}