-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathAsteroidGameSpawnSystem.cs
More file actions
399 lines (341 loc) · 19.2 KB
/
AsteroidGameSpawnSystem.cs
File metadata and controls
399 lines (341 loc) · 19.2 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
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.NetCode.HostMigration;
using Unity.Transforms;
namespace Asteroids.Server
{
/// <summary>Handles spawning of Ships and Asteroids.</summary>
[BurstCompile]
[UpdateInGroup(typeof(InitializationSystemGroup))]
// The system was moved to the InitializationSystemGroup in order to avoid race-conditions with the Netcode systems
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
public partial struct AsteroidGameSpawnSystem : ISystem
{
EntityQuery m_LevelQuery;
EntityQuery m_ConnectionQuery;
EntityQuery m_ShipQuery;
EntityQuery m_DynamicAsteroidsQuery;
EntityQuery m_StaticAsteroidsQuery;
EntityQuery m_HostMigrationQuery;
Entity m_AsteroidPrefab;
Entity m_ShipPrefab;
float m_AsteroidRadius;
float m_ShipRadius;
private NativeReference<Random> randomReference;
ComponentLookup<PlayerStateComponentData> playerStateFromEntity;
ComponentLookup<CommandTarget> commandTargetFromEntity;
ComponentLookup<NetworkId> networkIdFromEntity;
ComponentLookup<LocalTransform> localTransformLookup;
public void OnCreate(ref SystemState state)
{
var builder = new EntityQueryBuilder(Allocator.Temp).WithAll<LocalTransform, ShipStateComponentData>();
m_ShipQuery = state.GetEntityQuery(builder);
builder.Reset();
builder.WithAll<LocalTransform, AsteroidTagComponentData>()
.WithNone<StaticAsteroid>();
m_DynamicAsteroidsQuery = state.GetEntityQuery(builder);
builder.Reset();
builder.WithAll<StaticAsteroid>();
m_StaticAsteroidsQuery = state.GetEntityQuery(builder);
builder.Reset();
builder.WithAllRW<LevelComponent>();
m_LevelQuery = state.GetEntityQuery(builder);
builder.Reset();
builder.WithAllRW<NetworkId>(); // can't use NetworkStreamConnection, doesn't work for single world host.
m_ConnectionQuery = state.GetEntityQuery(builder);
builder.Reset();
builder.WithAll<HostMigrationInProgress>();
m_HostMigrationQuery = state.GetEntityQuery(builder);
state.RequireForUpdate(m_LevelQuery);
state.RequireForUpdate<AsteroidsSpawner>();
// Ensure every random is seeded uniquely (not Burst compatible)...
// AND that the random feedbacks into itself, ensuring better quality randomness for Asteroid spawns.
var fileTimeUtc = System.DateTime.UtcNow.ToFileTimeUtc();
randomReference = new NativeReference<Random>(Random.CreateFromIndex((uint) fileTimeUtc), Allocator.Persistent);
playerStateFromEntity = state.GetComponentLookup<PlayerStateComponentData>();
commandTargetFromEntity = state.GetComponentLookup<CommandTarget>();
networkIdFromEntity = state.GetComponentLookup<NetworkId>();
localTransformLookup = state.GetComponentLookup<LocalTransform>(true);
}
[BurstCompile]
public void OnDestroy(ref SystemState state)
{
randomReference.Dispose();
// Others are disposed automatically.
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
if (m_ConnectionQuery.IsEmptyIgnoreFilter)
{
// No connected players, just destroy all asteroids to save CPU
state.EntityManager.DestroyEntity(m_StaticAsteroidsQuery);
state.EntityManager.DestroyEntity(m_DynamicAsteroidsQuery);
return;
}
// If there is a host migration in progress skip any spawning here until it's done
if (!m_HostMigrationQuery.IsEmptyIgnoreFilter)
return;
var settings = SystemAPI.GetSingleton<ServerSettings>();
if (m_AsteroidPrefab == Entity.Null || m_ShipPrefab == Entity.Null)
{
var asteroidsSpawner = SystemAPI.GetSingleton<AsteroidsSpawner>();
m_AsteroidPrefab = settings.levelData.staticAsteroidOptimization ? asteroidsSpawner.StaticAsteroid : asteroidsSpawner.Asteroid;
m_ShipPrefab = asteroidsSpawner.Ship;
if (m_AsteroidPrefab == Entity.Null || m_ShipPrefab == Entity.Null)
return;
m_AsteroidRadius = settings.levelData.asteroidCollisionRadius;
m_ShipRadius = settings.levelData.shipCollisionRadius;
}
var ecb = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>()
.CreateCommandBuffer(state.WorldUnmanaged);
playerStateFromEntity.Update(ref state);
commandTargetFromEntity.Update(ref state);
networkIdFromEntity.Update(ref state);
localTransformLookup.Update(ref state);
// Optimization: Prevent gathering hundreds of thousands of asteroids, which kills the main thread.
// Note: This will cause the ship to potentially spawn inside asteroids, but the bigger map size
// should make this a low repro event.
// TODO - We could destroy all asteroids chunks within your spawn tile instead?
int currentAsteroidsCount = m_DynamicAsteroidsQuery.CalculateEntityCountWithoutFiltering() + m_StaticAsteroidsQuery.CalculateEntityCountWithoutFiltering();
NativeList<Entity> dynamicAsteroidEntities = default;
NativeList<LocalTransform> dynamicAsteroidTransforms = default;
NativeList<StaticAsteroid> staticAsteroids = default;
NativeList<Entity> staticAsteroidEntities = default;
var tooManyEntitiesToGather = currentAsteroidsCount > 10_000;
if (tooManyEntitiesToGather)
{
dynamicAsteroidEntities = new(0, state.WorldUpdateAllocator);
dynamicAsteroidTransforms = new(0, state.WorldUpdateAllocator);
staticAsteroids = new(0, state.WorldUpdateAllocator);
staticAsteroidEntities = dynamicAsteroidEntities;
}
else
{
dynamicAsteroidEntities = m_DynamicAsteroidsQuery.ToEntityListAsync(state.WorldUpdateAllocator, out var asteroidEntitiesHandle);
dynamicAsteroidTransforms = m_DynamicAsteroidsQuery.ToComponentDataListAsync<LocalTransform>(state.WorldUpdateAllocator, out var asteroidTranslationsHandle);
staticAsteroids = m_StaticAsteroidsQuery.ToComponentDataListAsync<StaticAsteroid>(state.WorldUpdateAllocator, out var staticAsteroidsHandle);
staticAsteroidEntities = m_StaticAsteroidsQuery.ToEntityListAsync(state.WorldUpdateAllocator, out var staticAsteroidEntitiesHandle);
state.Dependency = JobHandle.CombineDependencies(asteroidEntitiesHandle, asteroidTranslationsHandle,
JobHandle.CombineDependencies(staticAsteroidsHandle, staticAsteroidEntitiesHandle, state.Dependency));
}
var shipTransforms = m_ShipQuery.ToComponentDataListAsync<LocalTransform>(state.WorldUpdateAllocator, out var shipTranslationsHandle);
var level = m_LevelQuery.ToComponentDataListAsync<LevelComponent>(state.WorldUpdateAllocator, out var levelHandle);
state.Dependency = JobHandle.CombineDependencies(shipTranslationsHandle, levelHandle, state.Dependency);
var tick = SystemAPI.GetSingleton<NetworkTime>().ServerTick;
SystemAPI.TryGetSingleton<ClientServerTickRate>(out var tickRate);
tickRate.ResolveDefaults();
var fixedDeltaTime = tickRate.SimulationFixedTimeStep;
var shipLevelPadding = m_ShipRadius + 50;
var asteroidLevelPadding = m_AsteroidRadius + 3;
var minShipAsteroidSpawnDistance = m_ShipRadius + m_AsteroidRadius + 100;
var minShipToShipSpawnDistance = (m_ShipRadius + m_ShipRadius) + 300;
var shipTransformsList = new NativeList<LocalTransform>(64, state.WorldUpdateAllocator);
var shipListJob = new CreateShipListJob
{
shipTransformsIn = shipTransforms,
shipTransformsOut = shipTransformsList,
};
state.Dependency = shipListJob.Schedule(state.Dependency);
var spawnPlayerShips = new SpawnPlayerShips
{
ecb = ecb,
playerStateFromEntity = playerStateFromEntity,
commandTargetFromEntity = commandTargetFromEntity,
networkIdFromEntity = networkIdFromEntity,
shipTransforms = shipTransformsList,
dynamicAsteroidTransforms = dynamicAsteroidTransforms,
localTransformLookup = localTransformLookup,
staticAsteroids = staticAsteroids,
dynamicAsteroidEntities = dynamicAsteroidEntities,
staticAsteroidEntities = staticAsteroidEntities,
level = level,
random = randomReference,
tick = tick,
shipPrefab = m_ShipPrefab,
fixedDeltaTime = fixedDeltaTime,
shipLevelPadding = shipLevelPadding,
minShipAsteroidSpawnDistance = minShipAsteroidSpawnDistance,
minShipToShipSpawnDistance = minShipToShipSpawnDistance
};
state.Dependency = spawnPlayerShips.Schedule(state.Dependency);
var spawnAsteroids = new SpawnAllAsteroids
{
ecb = ecb,
shipTransforms = shipTransformsList.AsDeferredJobArray(),
localTransformLookup = localTransformLookup,
level = level,
random = randomReference,
tick = tick,
asteroidPrefab = m_AsteroidPrefab,
asteroidLevelPadding = asteroidLevelPadding,
minShipAsteroidSpawnDistance = minShipAsteroidSpawnDistance,
currentAsteroidsCount = currentAsteroidsCount,
numAsteroids = settings.levelData.numAsteroids,
asteroidVelocity = settings.levelData.asteroidVelocity,
staticAsteroidOptimization = settings.levelData.staticAsteroidOptimization ? 1: 0
};
state.Dependency = spawnAsteroids.Schedule(state.Dependency);
}
[BurstCompile]
struct CreateShipListJob : IJob
{
[ReadOnly] public NativeList<LocalTransform> shipTransformsIn;
public NativeList<LocalTransform> shipTransformsOut;
public void Execute()
{
shipTransformsOut.AddRange(shipTransformsIn.AsArray());
}
}
[BurstCompile]
[WithAll(typeof(PlayerSpawnRequest))]
internal partial struct SpawnPlayerShips : IJobEntity
{
public EntityCommandBuffer ecb;
public ComponentLookup<PlayerStateComponentData> playerStateFromEntity;
public ComponentLookup<CommandTarget> commandTargetFromEntity;
public ComponentLookup<NetworkId> networkIdFromEntity;
public NativeList<LocalTransform> shipTransforms;
[ReadOnly] public NativeList<LocalTransform> dynamicAsteroidTransforms;
[ReadOnly] public ComponentLookup<LocalTransform> localTransformLookup;
[ReadOnly] public NativeList<StaticAsteroid> staticAsteroids;
[ReadOnly] public NativeList<Entity> dynamicAsteroidEntities;
[ReadOnly] public NativeList<Entity> staticAsteroidEntities;
[ReadOnly] public NativeList<LevelComponent> level;
public NativeReference<Random> random;
public NetworkTick tick;
public Entity shipPrefab;
public float fixedDeltaTime;
public float shipLevelPadding;
public float minShipAsteroidSpawnDistance;
public float minShipToShipSpawnDistance;
void Execute(Entity entity, in ReceiveRpcCommandRequest requestSource)
{
// Destroy the spawn request:
ecb.DestroyEntity(entity);
// Is request even valid?
if (!playerStateFromEntity.HasComponent(requestSource.SourceConnection) ||
!commandTargetFromEntity.HasComponent(requestSource.SourceConnection) ||
commandTargetFromEntity[requestSource.SourceConnection].targetEntity != Entity.Null ||
playerStateFromEntity[requestSource.SourceConnection].IsSpawning != 0)
return;
// Try find a random spawn position for the Ship that isn't near another player.
// Don't allow failure though, just take a "bad" position instead.
var rand = random.Value;
TryFindSpawnPos(ref rand, shipTransforms.AsArray(), level[0], shipLevelPadding, minShipToShipSpawnDistance, out var validShipPos);
random.Value = rand;
// Instantiate ship:
var shipEntity = ecb.Instantiate(shipPrefab);
//@ronald. this is necessary since the meshes are not backing the correct scaling factor
var originalScale = localTransformLookup[shipPrefab].Scale;
var trans = LocalTransform.FromPositionRotationScale(
validShipPos,
quaternion.RotateZ(math.radians(90f)),
originalScale
);
ecb.SetComponent(shipEntity, trans);
ecb.SetComponent(shipEntity, new GhostOwner {NetworkId = networkIdFromEntity[requestSource.SourceConnection].Value});
ecb.SetComponent(shipEntity, new PlayerIdComponentData {PlayerEntity = requestSource.SourceConnection});
ecb.SetComponent(requestSource.SourceConnection, new CommandTarget {targetEntity = shipEntity});
ecb.SetComponent(requestSource.SourceConnection, new PlayerStateComponentData {IsSpawning = 0});
ecb.AppendToBuffer(requestSource.SourceConnection, new LinkedEntityGroup {Value = shipEntity});
// Add to the list to prevent asteroids below from spawning near them.
shipTransforms.Add(trans);
// Mark the player as currently spawning
playerStateFromEntity[requestSource.SourceConnection] = new PlayerStateComponentData {IsSpawning = 1};
// Destroy asteroids that are too close to this spawn:
var minShipAsteroidSpawnDistanceSqr = minShipAsteroidSpawnDistance * minShipAsteroidSpawnDistance;
for (int i = 0; i < dynamicAsteroidTransforms.Length; i++)
{
if (math.distancesq(dynamicAsteroidTransforms[i].Position, validShipPos) < minShipAsteroidSpawnDistanceSqr)
ecb.DestroyEntity(dynamicAsteroidEntities[i]);
}
for (int i = 0; i < staticAsteroids.Length; i++)
{
if (math.distancesq(staticAsteroids[i].GetPosition(tick, 1f, fixedDeltaTime), validShipPos) < minShipAsteroidSpawnDistanceSqr)
ecb.DestroyEntity(staticAsteroidEntities[i]);
}
}
}
[BurstCompile]
struct SpawnAllAsteroids : IJob
{
public EntityCommandBuffer ecb;
[ReadOnly] public NativeArray<LocalTransform> shipTransforms;
[ReadOnly] public ComponentLookup<LocalTransform> localTransformLookup;
[ReadOnly] public NativeList<LevelComponent> level;
public NativeReference<Random> random;
public NetworkTick tick;
public Entity asteroidPrefab;
public float asteroidLevelPadding;
public float minShipAsteroidSpawnDistance;
public int currentAsteroidsCount;
public int numAsteroids;
public float asteroidVelocity;
public int staticAsteroidOptimization;
public void Execute()
{
var rand = random.Value;
for (int i = currentAsteroidsCount; i < numAsteroids; ++i)
{
// Spawn asteroid at random pos, assuming we can find a valid one that isn't under a ship.
// Don't treat this as an error (because it may happen occasionally by chance, or if the map is packed with ships).
// Instead, just stop attempting to spawn any more this frame.
if (!TryFindSpawnPos(ref rand, shipTransforms, level[0], asteroidLevelPadding, minShipAsteroidSpawnDistance, out var validAsteroidPos))
break;
var angle = rand.NextFloat(-0.0f, 359.0f);
//@ronald. this is necessary since the meshes are not backing the correct scaling factor
var originalScale = localTransformLookup[asteroidPrefab].Scale;
var trans = LocalTransform.FromPositionRotationScale(
validAsteroidPos,
quaternion.RotateZ(math.radians(angle)),
originalScale);
var vel = new Velocity {Value = math.mul(trans.Rotation, new float3(0, asteroidVelocity, 0)).xy};
var e = ecb.Instantiate(asteroidPrefab);
ecb.SetComponent(e, trans);
if (staticAsteroidOptimization == 1)
{
UnityEngine.Debug.Assert(tick.IsValid);
ecb.SetComponent(e,
new StaticAsteroid
{
InitialPosition = trans.Position.xy, InitialVelocity = vel.Value, InitialAngle = angle,
SpawnTick = tick,
});
}
else
{
ecb.SetComponent(e, vel);
}
}
random.Value = rand;
}
}
static bool TryFindSpawnPos(ref Random rand, NativeArray<LocalTransform> avoidTransforms, LevelComponent levelComponent, float levelPadding, float minSpawnDistance, out float3 validRandomAsteroidPosition)
{
validRandomAsteroidPosition = 0;
var minSpawnDistanceSqr = minSpawnDistance * minSpawnDistance;
for (var attempt = 0; attempt < 5; attempt++)
{
validRandomAsteroidPosition = new float3(rand.NextFloat(levelPadding, levelComponent.levelWidth - levelPadding), rand.NextFloat(levelPadding, levelComponent.levelHeight - levelPadding), 0);
var isValidLocation = true;
for (var i = 0; i < avoidTransforms.Length; i++)
{
if (math.distancesq(avoidTransforms[i].Position, validRandomAsteroidPosition) < minSpawnDistanceSqr)
{
isValidLocation = false;
break;
}
}
if(isValidLocation)
return true;
minSpawnDistanceSqr *= 0.8f; // Reduce size & retry.
}
return false;
}
}
}