forked from Unity-Technologies/EntityComponentSystemSamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollisionSystem.cs
More file actions
441 lines (391 loc) · 22.7 KB
/
Copy pathCollisionSystem.cs
File metadata and controls
441 lines (391 loc) · 22.7 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
using System.Threading;
using Unity.Assertions;
using Unity.Burst;
using Unity.Burst.CompilerServices;
using Unity.Burst.Intrinsics;
using Unity.Entities;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Transforms;
using Unity.NetCode;
namespace Asteroids.Server
{
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct CollisionSystem : ISystem
{
private EntityQuery shipQuery;
private EntityQuery bulletQuery;
private EntityQuery asteroidQuery;
private EntityQuery m_LevelQuery;
private NativeQueue<Entity> playerClearQueue;
private EntityQuery settingsQuery;
ComponentTypeHandle<LocalTransform> transformType;
ComponentTypeHandle<GhostOwner> ghostOwnerType;
ComponentTypeHandle<StaticAsteroid> staticAsteroidType;
ComponentTypeHandle<PlayerIdComponentData> playerIdType;
SharedComponentTypeHandle<GhostDistancePartitionShared> distancePartitionSharedType;
EntityTypeHandle entityType;
ComponentLookup<CommandTarget> commandTarget;
BufferLookup<LinkedEntityGroup> linkedEntityGroupFromEntity;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
var builder = new EntityQueryBuilder(Allocator.Temp)
.WithAll<LocalTransform, ShipTagComponentData, GhostOwner>();
shipQuery = state.GetEntityQuery(builder);
builder.Reset();
builder.WithAll<LocalTransform, BulletTagComponent, BulletAgeComponent, GhostOwner>();
bulletQuery = state.GetEntityQuery(builder);
builder.Reset();
builder.WithAll<LocalTransform, AsteroidTagComponentData>();
asteroidQuery = state.GetEntityQuery(builder);
builder.Reset();
builder.WithAll<ServerSettings>();
settingsQuery = state.GetEntityQuery(builder);
builder.Reset();
builder.WithAll<LevelComponent>();
m_LevelQuery = state.GetEntityQuery(builder);
playerClearQueue = new NativeQueue<Entity>(Allocator.Persistent);
state.RequireForUpdate(m_LevelQuery);
transformType = state.GetComponentTypeHandle<LocalTransform>(true);
ghostOwnerType = state.GetComponentTypeHandle<GhostOwner>(true);
staticAsteroidType = state.GetComponentTypeHandle<StaticAsteroid>(true);
playerIdType = state.GetComponentTypeHandle<PlayerIdComponentData>(true);
distancePartitionSharedType = state.GetSharedComponentTypeHandle<GhostDistancePartitionShared>();
entityType = state.GetEntityTypeHandle();
commandTarget = state.GetComponentLookup<CommandTarget>();
linkedEntityGroupFromEntity = state.GetBufferLookup<LinkedEntityGroup>();
state.RequireForUpdate<AsteroidScore>();
}
[BurstCompile]
public void OnDestroy(ref SystemState state)
{
playerClearQueue.Dispose();
}
private static bool WithinTileBroadphase(int3 shipTile, int3 bulletTile)
{
var tileDistance = math.abs(shipTile - bulletTile);
return math.all(tileDistance <= 1);
}
[BurstCompile]
internal struct DestroyAsteroidJob : IJobChunk
{
public EntityCommandBuffer.ParallelWriter commandBuffer;
[ReadOnly] public NativeList<ArchetypeChunk> bulletChunks;
[ReadOnly] public ComponentTypeHandle<LocalTransform> transformType;
[ReadOnly] public ComponentTypeHandle<StaticAsteroid> staticAsteroidType;
[ReadOnly] public EntityTypeHandle entityType;
[ReadOnly] public SharedComponentTypeHandle<GhostDistancePartitionShared> distancePartitionSharedType;
[ReadOnly] public NativeList<LevelComponent> level;
[NativeDisableUnsafePtrRestriction] public RefRW<AsteroidScore> asteroidScore;
public NetworkTick tick;
public uint simulationStepBatchSize;
public float fixedDeltaTime;
public void Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
{
// This job is not written to support queries with enableable component types.
Assert.IsFalse(useEnabledMask);
// Rate-limit this, as it gets incredibly expensive on high chunk counts.
if ((chunk.SequenceNumber + tick.TickIndexForValidTick) % level[0].collisionSystemRoundRobinSegments != 0) return;
var destroyedAsteroidCounter = 0;
var shipTile = chunk.Has(distancePartitionSharedType) ? chunk.GetSharedComponent(distancePartitionSharedType).Index : 0;
var asteroidEntity = chunk.GetNativeArray(entityType);
var staticAsteroid = chunk.GetNativeArray(ref staticAsteroidType);
if (staticAsteroid.IsCreated)
{
for (int asteroid = 0; asteroid < asteroidEntity.Length; ++asteroid)
{
var firstPos = staticAsteroid[asteroid].GetPosition(tick, 1, fixedDeltaTime).xy;
CheckOutOfBounds(unfilteredChunkIndex, asteroidEntity[asteroid], firstPos, level[0].asteroidCollisionRadius);
}
for (int bc = 0; bc < bulletChunks.Length; ++bc)
{
var bulletChunk = bulletChunks[bc];
var bulletTile = bulletChunk.Has(distancePartitionSharedType) ? bulletChunk.GetSharedComponent(distancePartitionSharedType).Index : 0;
if (!WithinTileBroadphase(shipTile, bulletTile)) continue;
var bulletEntities = bulletChunk.GetNativeArray(entityType);
var bulletTrans = bulletChunk.GetNativeArray(ref transformType);
for (int asteroid = 0; asteroid < asteroidEntity.Length; ++asteroid)
{
var firstPos = staticAsteroid[asteroid].GetPosition(tick, 1, fixedDeltaTime).xy;
CheckCollisionsInner(unfilteredChunkIndex, asteroidEntity[asteroid], bulletEntities, bulletTrans, firstPos, ref destroyedAsteroidCounter);
}
}
}
else
{
var asteroidPos = chunk.GetNativeArray(ref transformType);
for (int asteroid = 0; asteroid < asteroidPos.Length; ++asteroid)
{
var firstPos = asteroidPos[asteroid].Position.xy;
CheckOutOfBounds(unfilteredChunkIndex, asteroidEntity[asteroid], firstPos, level[0].asteroidCollisionRadius);
}
for (int bc = 0; bc < bulletChunks.Length; ++bc)
{
var bulletChunk = bulletChunks[bc];
var bulletTile = bulletChunk.Has(distancePartitionSharedType) ? bulletChunk.GetSharedComponent(distancePartitionSharedType).Index : 0;
if (!WithinTileBroadphase(shipTile, bulletTile)) continue;
var bulletEntities = bulletChunk.GetNativeArray(entityType);
var bulletTrans = bulletChunk.GetNativeArray(ref transformType);
for (int asteroid = 0; asteroid < asteroidPos.Length; ++asteroid)
{
var firstPos = asteroidPos[asteroid].Position.xy;
CheckCollisionsInner(unfilteredChunkIndex, asteroidEntity[asteroid], bulletEntities, bulletTrans, firstPos, ref destroyedAsteroidCounter);
}
}
}
// This sum theoretically causes thread contention, but said contention should be minimal (as bullets
// destroying asteroids is relatively rare).
if(destroyedAsteroidCounter > 0)
Interlocked.Add(ref asteroidScore.ValueRW.Value, destroyedAsteroidCounter);
}
private void CheckCollisionsInner(int unfilteredChunkIndex, in Entity asteroidEntity,
NativeArray<Entity> bulletEntities, NativeArray<LocalTransform> bulletTrans,
in float2 asteroidPos, ref int destroyedAsteroidCounter)
{
for (int bullet = 0; bullet < bulletEntities.Length; ++bullet)
{
var secondPos = bulletTrans[bullet].Position.xy;
if (Intersect(level[0].bulletCollisionRadius, level[0].asteroidCollisionRadius, asteroidPos, secondPos))
{
commandBuffer.DestroyEntity(unfilteredChunkIndex, asteroidEntity);
destroyedAsteroidCounter++;
if (level[0].bulletsDestroyedOnContact)
commandBuffer.DestroyEntity(unfilteredChunkIndex, bulletEntities[bullet]);
}
}
}
private void CheckOutOfBounds(int unfilteredChunkIndex, in Entity asteroidEntity, in float2 firstPos, float firstRadius)
{
if (Hint.Unlikely(firstPos.x - firstRadius < 0 || firstPos.y - firstRadius < 0 ||
firstPos.x + firstRadius > level[0].levelHeight ||
firstPos.y + firstRadius > level[0].levelHeight))
{
commandBuffer.DestroyEntity(unfilteredChunkIndex, asteroidEntity);
}
}
}
[BurstCompile]
internal struct DestroyShipJob : IJobChunk
{
public EntityCommandBuffer.ParallelWriter commandBuffer;
[ReadOnly] public NativeList<ArchetypeChunk> asteroidChunks;
[ReadOnly] public NativeList<ArchetypeChunk> bulletChunks;
[ReadOnly] public ComponentTypeHandle<LocalTransform> transformType;
[ReadOnly] public ComponentTypeHandle<GhostOwner> ghostOwnerType;
[ReadOnly] public ComponentTypeHandle<StaticAsteroid> staticAsteroidType;
[ReadOnly] public ComponentTypeHandle<PlayerIdComponentData> playerIdType;
[ReadOnly] public SharedComponentTypeHandle<GhostDistancePartitionShared> distancePartitionSharedType;
[ReadOnly] public EntityTypeHandle entityType;
[ReadOnly] public NativeList<ServerSettings> serverSettings;
public NativeQueue<Entity>.ParallelWriter playerClearQueue;
[ReadOnly] public NativeList<LevelComponent> level;
public NetworkTick tick;
public float fixedDeltaTime;
public void Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
{
// This job is not written to support queries with enableable component types.
Assert.IsFalse(useEnabledMask);
var shipTile = chunk.Has(distancePartitionSharedType) ? chunk.GetSharedComponent(distancePartitionSharedType).Index : 0;
var shipTrans = chunk.GetNativeArray(ref transformType);
var shipPlayerId = chunk.GetNativeArray(ref playerIdType);
var shipEntity = chunk.GetNativeArray(entityType);
var shipGhostOwner = chunk.GetNativeArray(ref ghostOwnerType);
for (int ship = 0; ship < shipTrans.Length; ++ship)
{
int alive = 1;
var firstPos = shipTrans[ship].Position.xy;
var firstRadius = level[0].shipCollisionRadius;
if (firstPos.x - firstRadius < 0 || firstPos.y - firstRadius < 0 ||
firstPos.x + firstRadius > level[0].levelHeight ||
firstPos.y + firstRadius > level[0].levelHeight)
{
if (shipPlayerId.IsCreated)
playerClearQueue.Enqueue(shipPlayerId[ship].PlayerEntity);
commandBuffer.DestroyEntity(unfilteredChunkIndex, shipEntity[ship]);
continue;
}
if (serverSettings.Length > 0 && serverSettings[0].levelData.shipPvP)
{
var shipNetworkId = shipGhostOwner[ship].NetworkId;
var secondRadius = level[0].bulletCollisionRadius;
for (int bc = 0; bc < bulletChunks.Length && alive != 0; ++bc)
{
var bulletChunk = bulletChunks[bc];
var bulletTile = bulletChunk.Has(distancePartitionSharedType) ? bulletChunk.GetSharedComponent(distancePartitionSharedType).Index : 0;
if (!WithinTileBroadphase(shipTile, bulletTile)) continue;
var bulletEntities = bulletChunks[bc].GetNativeArray(entityType);
var bulletPos = bulletChunks[bc].GetNativeArray(ref transformType);
var bulletGhostOwner = bulletChunks[bc].GetNativeArray(ref ghostOwnerType);
for (int bullet = 0; bullet < bulletEntities.Length; ++bullet)
{
if (bulletGhostOwner[bullet].NetworkId == shipNetworkId)
continue;
var secondPos = bulletPos[bullet].Position.xy;
if (Intersect(firstRadius, secondRadius, firstPos, secondPos))
{
if (shipPlayerId.IsCreated)
playerClearQueue.Enqueue(shipPlayerId[ship].PlayerEntity);
commandBuffer.DestroyEntity(unfilteredChunkIndex, shipEntity[ship]);
if(serverSettings[0].levelData.bulletsDestroyedOnContact)
commandBuffer.DestroyEntity(unfilteredChunkIndex, bulletEntities[bullet]);
alive = 0;
break;
}
}
}
}
if (alive != 0 && serverSettings.Length > 0 && serverSettings[0].levelData.asteroidsDamageShips)
{
var secondRadius = level[0].asteroidCollisionRadius;
for (int ac = 0; ac < asteroidChunks.Length && alive != 0; ++ac)
{
var asteroidChunk = asteroidChunks[ac];
var asteroidTile = asteroidChunk.Has(distancePartitionSharedType) ? asteroidChunk.GetSharedComponent(distancePartitionSharedType).Index : 0;
if (!WithinTileBroadphase(shipTile, asteroidTile)) continue;
var asteroidEntity = asteroidChunk.GetNativeArray(entityType);
var staticAsteroid = asteroidChunk.GetNativeArray(ref staticAsteroidType);
if (staticAsteroid.IsCreated)
{
for (int asteroid = 0; asteroid < staticAsteroid.Length; ++asteroid)
{
var secondPos = staticAsteroid[asteroid].GetPosition(tick, 1, fixedDeltaTime).xy;
if (Intersect(firstRadius, secondRadius, firstPos, secondPos))
{
if (shipPlayerId.IsCreated)
playerClearQueue.Enqueue(shipPlayerId[ship].PlayerEntity);
commandBuffer.DestroyEntity(unfilteredChunkIndex, shipEntity[ship]);
if(serverSettings[0].levelData.asteroidsDestroyedOnShipContact)
commandBuffer.DestroyEntity(unfilteredChunkIndex, asteroidEntity[asteroid]);
alive = 0;
break;
}
}
}
else
{
var asteroidTrans = asteroidChunk.GetNativeArray(ref transformType);
for (int asteroid = 0; asteroid < asteroidTrans.Length; ++asteroid)
{
var secondPos = asteroidTrans[asteroid].Position.xy;
if (Intersect(firstRadius, secondRadius, firstPos, secondPos))
{
if (shipPlayerId.IsCreated)
playerClearQueue.Enqueue(shipPlayerId[ship].PlayerEntity);
commandBuffer.DestroyEntity(unfilteredChunkIndex, shipEntity[ship]);
if(serverSettings[0].levelData.asteroidsDestroyedOnShipContact)
commandBuffer.DestroyEntity(unfilteredChunkIndex, asteroidEntity[asteroid]);
alive = 0;
break;
}
}
}
}
}
}
}
}
[BurstCompile]
internal struct ClearShipPointerJob : IJob
{
public NativeQueue<Entity> playerClearQueue;
public ComponentLookup<CommandTarget> commandTarget;
public BufferLookup<LinkedEntityGroup> linkedEntityGroupFromEntity;
public void Execute()
{
Entity ent;
while (playerClearQueue.TryDequeue(out ent))
{
if (commandTarget.HasComponent(ent))
{
var state = commandTarget[ent];
state.targetEntity = Entity.Null;
commandTarget[ent] = state;
var linkedEntityGroup = linkedEntityGroupFromEntity[ent];
linkedEntityGroup.RemoveAt(1);
}
}
}
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
JobHandle bulletHandle;
JobHandle asteroidHandle;
JobHandle levelHandle;
JobHandle settingsHandle;
var networkTime = SystemAPI.GetSingleton<NetworkTime>();
var asteroidScoreRef = SystemAPI.GetSingletonRW<AsteroidScore>();
SystemAPI.TryGetSingleton<ClientServerTickRate>(out var tickRate);
tickRate.ResolveDefaults();
var level = m_LevelQuery.ToComponentDataListAsync<LevelComponent>(state.WorldUpdateAllocator,
out levelHandle);
transformType.Update(ref state);
ghostOwnerType.Update(ref state);
staticAsteroidType.Update(ref state);
playerIdType.Update(ref state);
entityType.Update(ref state);
distancePartitionSharedType.Update(ref state);
commandTarget.Update(ref state);
linkedEntityGroupFromEntity.Update(ref state);
var asteroidJob = new DestroyAsteroidJob
{
commandBuffer = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>().CreateCommandBuffer(state.WorldUnmanaged).AsParallelWriter(),
bulletChunks = bulletQuery.ToArchetypeChunkListAsync(state.WorldUpdateAllocator, out bulletHandle),
transformType = transformType,
asteroidScore = asteroidScoreRef,
staticAsteroidType = staticAsteroidType,
entityType = entityType,
distancePartitionSharedType = distancePartitionSharedType,
level = level,
tick = networkTime.ServerTick,
simulationStepBatchSize = (uint) networkTime.SimulationStepBatchSize,
fixedDeltaTime = tickRate.SimulationFixedTimeStep,
};
var serverSettings =
settingsQuery.ToComponentDataListAsync<ServerSettings>(state.WorldUpdateAllocator,
out settingsHandle);
var shipJob = new DestroyShipJob
{
commandBuffer = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>().CreateCommandBuffer(state.WorldUnmanaged).AsParallelWriter(),
asteroidChunks = asteroidQuery.ToArchetypeChunkListAsync(state.WorldUpdateAllocator, out asteroidHandle),
bulletChunks = asteroidJob.bulletChunks,
transformType = asteroidJob.transformType,
ghostOwnerType = ghostOwnerType,
staticAsteroidType = asteroidJob.staticAsteroidType,
playerIdType = playerIdType,
entityType = asteroidJob.entityType,
distancePartitionSharedType = distancePartitionSharedType,
serverSettings = serverSettings,
playerClearQueue = playerClearQueue.AsParallelWriter(),
level = asteroidJob.level,
tick = networkTime.ServerTick,
fixedDeltaTime = tickRate.SimulationFixedTimeStep,
};
var asteroidDep = JobHandle.CombineDependencies(state.Dependency, bulletHandle, levelHandle);
var shipDep = JobHandle.CombineDependencies(asteroidDep, asteroidHandle, settingsHandle);
var h1 = asteroidJob.ScheduleParallel(asteroidQuery, asteroidDep);
var h2 = shipJob.ScheduleParallel(shipQuery, shipDep);
JobHandle.ScheduleBatchedJobs(); // We call this because waiting for the above jobs to start can
// often take significantly longer than their execution.
var cleanupShipJob = new ClearShipPointerJob
{
playerClearQueue = playerClearQueue,
commandTarget = commandTarget,
linkedEntityGroupFromEntity = linkedEntityGroupFromEntity,
};
var h3 = cleanupShipJob.Schedule(h2);
state.Dependency = JobHandle.CombineDependencies(h1, h2, h3);
}
private static bool Intersect(float firstRadius, float secondRadius, float2 firstPos, float2 secondPos)
{
float2 diff = firstPos - secondPos;
float distSq = math.dot(diff, diff);
return distSq <= (firstRadius + secondRadius) * (firstRadius + secondRadius);
}
}
}