forked from FabianTerhorst/coreclr-module
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEntityThread.cs
More file actions
383 lines (331 loc) · 20.1 KB
/
EntityThread.cs
File metadata and controls
383 lines (331 loc) · 20.1 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
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using AltV.Net.EntitySync.SpatialPartitions;
namespace AltV.Net.EntitySync
{
//TODO: only send position in update when position changed since last time in range of entity
//TODO: add aabb thread, add abstract entitythread class with constructor
/// <summary>
/// The entity thread checks in a endless loop if entities should be created or removed for all clients.
/// And it delivers the results via the provided action callbacks.
/// </summary>
public class EntityThread
{
private bool running = true;
private readonly ulong threadIndex;
private readonly Thread thread;
private readonly EntityThreadRepository entityThreadRepository;
private readonly ClientThreadRepository clientThreadRepository;
private readonly SpatialPartition spatialPartition;
private readonly int syncRate;
private readonly bool netOwnerEvents;
private readonly LinkedList<IEntity> entitiesToRemoveFromClient = new LinkedList<IEntity>();
private readonly LinkedList<IEntity> entitiesToResetFromClient = new LinkedList<IEntity>();
private readonly LinkedList<string> changedEntityDataKeys = new LinkedList<string>();
private readonly Action<IClient, IEntity, LinkedList<string>> onEntityCreate;
private readonly Action<IClient, IEntity> onEntityRemove;
private readonly Action<IClient, IEntity, LinkedList<string>> onEntityDataChange;
private readonly Action<IClient, IEntity, Vector3> onEntityPositionChange;
private readonly Action<IClient, IEntity> onEntityClearCache;
private readonly Action<IClient, IEntity, bool> onEntityNetOwnerChange;
private Vector3 clientPosition = Vector3.Zero;
public EntityThread(ulong threadIndex, EntityThreadRepository entityThreadRepository,
ClientThreadRepository clientThreadRepository,
SpatialPartition spatialPartition, int syncRate, bool netOwnerEvents,
Action<IClient, IEntity, LinkedList<string>> onEntityCreate, Action<IClient, IEntity> onEntityRemove,
Action<IClient, IEntity, LinkedList<string>> onEntityDataChange,
Action<IClient, IEntity, Vector3> onEntityPositionChange, Action<IClient, IEntity> onEntityClearCache,
Action<IClient, IEntity, bool> onEntityNetOwnerChange)
{
this.threadIndex = threadIndex;
this.entityThreadRepository = entityThreadRepository ??
throw new ArgumentException("entityThreadRepository should not be null.");
this.clientThreadRepository = clientThreadRepository;
this.spatialPartition =
spatialPartition ?? throw new ArgumentException("spatialPartition should not be null.");
this.syncRate = syncRate;
this.netOwnerEvents = netOwnerEvents;
this.onEntityCreate = onEntityCreate ?? throw new ArgumentException("onEntityCreate should not be null.");
this.onEntityRemove = onEntityRemove ?? throw new ArgumentException("onEntityRemove should not be null.");
this.onEntityDataChange = onEntityDataChange ??
throw new ArgumentException("onEntityDataChange should not be null.");
this.onEntityPositionChange = onEntityPositionChange ??
throw new ArgumentException("onEntityPositionChange should not be null.");
this.onEntityClearCache = onEntityClearCache ??
throw new ArgumentException("onEntityPositionChange should not be null.");
this.onEntityNetOwnerChange = onEntityNetOwnerChange ??
throw new ArgumentException("onEntityNetOwnerChange should not be null.");
thread = new Thread(OnLoop) {IsBackground = true};
thread.Start();
}
private void OnLoop()
{
while (running)
{
try
{
while (entityThreadRepository.EntitiesChannelReader.TryRead(out var entityQueueResult))
{
var (entityToChange, state) = entityQueueResult;
switch (state)
{
case 0:
entityToChange.SetExistsInternal(true);
spatialPartition.Add(entityToChange);
foreach (var (key, _) in entityToChange.ThreadLocalData)
{
entityToChange.DataSnapshot.Update(key);
}
break;
case 1:
entityToChange.SetExistsInternal(false);
spatialPartition.Remove(entityToChange);
foreach (var client in entityToChange.GetClients())
{
client.RemoveEntityFully(threadIndex, entityToChange);
onEntityRemove(client, entityToChange);
}
// We don't have to do this, but we do for for consistency because entity gets garbage collected anyway
//entityToChange.GetClients().Clear();
foreach (var client in entityToChange.DataSnapshot.GetLastClients())
{
onEntityClearCache(client, entityToChange);
}
break;
case 2:
if (entityToChange.Exists)
{
// Check if position state is new position so we can set the new position to the entity internal position
var (hasNewPosition, hasNewRange, hasNewDimension) =
entityToChange.TrySetPropertiesComputing(
out var oldPosition,
out var oldRange, out var oldDimension,
out var newPosition,
out var newRange, out var newDimension);
if (hasNewPosition)
{
spatialPartition.UpdateEntityPosition(entityToChange, oldPosition, newPosition);
foreach (var entityClient in entityToChange.GetClients())
{
onEntityPositionChange(entityClient, entityToChange, newPosition);
}
}
if (hasNewRange)
{
spatialPartition.UpdateEntityRange(entityToChange, oldRange, newRange);
}
if (hasNewDimension)
{
spatialPartition.UpdateEntityDimension(entityToChange, oldDimension, newDimension);
}
}
break;
}
}
while (entityThreadRepository.EntitiesDataChannelReader.TryRead(out var entityDataQueueResult))
{
var (entityWithChangedData, changedDataKey, changedDataValue, notDeleted) =
entityDataQueueResult;
entityWithChangedData.DataSnapshot.Update(changedDataKey);
if (notDeleted)
{
entityWithChangedData.SetThreadLocalData(changedDataKey, changedDataValue);
}
else
{
entityWithChangedData.ResetThreadLocalData(changedDataKey);
}
}
//TODO: when the id provider add / remove doesn't work use the idprovider inside this loop only
lock (clientThreadRepository.Mutex)
{
if (clientThreadRepository.ClientsToRemove.Count != 0)
{
while (clientThreadRepository.ClientsToRemove.TryDequeue(out var clientToRemove))
{
foreach (var snapshot in clientToRemove.Snapshot.GetSnapshot(threadIndex))
{
var entityFromRemovedClient = snapshot.Key;
entityFromRemovedClient.DataSnapshot.RemoveClient(clientToRemove);
}
foreach (var (entityFromRemovedClient, _) in clientToRemove.GetEntities(threadIndex))
{
entityFromRemovedClient.RemoveClient(clientToRemove);
if (!netOwnerEvents) continue;
if (entityFromRemovedClient.NetOwner == clientToRemove)
{
entityFromRemovedClient.NetOwner = null;
entityFromRemovedClient.NetOwnerRange = float.MaxValue;
}
if (entityFromRemovedClient.TempNetOwner == clientToRemove)
{
entityFromRemovedClient.TempNetOwner = null;
entityFromRemovedClient.TempNetOwnerRange = float.MaxValue;
}
}
}
}
foreach (var (_, client) in clientThreadRepository.Clients)
{
if (!client.TryGetDimensionAndPosition(out var dimension, ref clientPosition))
{
continue;
}
var foundEntities = spatialPartition.Find(clientPosition, dimension);
var lastCheckedEntities = client.GetLastCheckedEntities(threadIndex);
if (lastCheckedEntities.Count != 0)
{
foreach (var (lastCheckedEntity, lastChecked) in lastCheckedEntities)
{
if (lastChecked)
{
entitiesToResetFromClient.AddLast(lastCheckedEntity);
}
else
{
entitiesToRemoveFromClient.AddLast(lastCheckedEntity);
onEntityRemove(client, lastCheckedEntity);
if (!netOwnerEvents) continue;
if (lastCheckedEntity.NetOwner == client)
{
lastCheckedEntity.NetOwner = null;
lastCheckedEntity.NetOwnerRange = float.MaxValue;
}
if (lastCheckedEntity.TempNetOwner == client)
{
lastCheckedEntity.TempNetOwner = null;
lastCheckedEntity.TempNetOwnerRange = float.MaxValue;
}
}
}
if (entitiesToResetFromClient.Count != 0)
{
var currEntity = entitiesToResetFromClient.First;
while (currEntity != null)
{
client.RemoveCheck(threadIndex, currEntity.Value);
currEntity = currEntity.Next;
}
entitiesToResetFromClient.Clear();
}
if (entitiesToRemoveFromClient.Count != 0)
{
var currEntity = entitiesToRemoveFromClient.First;
while (currEntity != null)
{
client.RemoveEntity(threadIndex, currEntity.Value);
currEntity.Value.RemoveClient(client); // not in range anymore so remove
currEntity = currEntity.Next;
}
entitiesToRemoveFromClient.Clear();
}
}
if (foundEntities != null)
{
for (int i = 0, length = foundEntities.Count; i < length; i++)
{
var foundEntity = foundEntities[i];
client.AddCheck(threadIndex, foundEntity);
foundEntity.DataSnapshot.CompareWithClient(threadIndex, changedEntityDataKeys,
client);
// We add client to entity here so we can remove it from the client when the entity got removed
foundEntity.TryAddClient(client);
if (client.TryAddEntity(threadIndex, foundEntity))
{
if (changedEntityDataKeys.Count == 0)
{
onEntityCreate(client, foundEntity, null);
}
else
{
onEntityCreate(client, foundEntity, changedEntityDataKeys);
changedEntityDataKeys.Clear();
}
}
else
{
if (changedEntityDataKeys.Count != 0)
{
onEntityDataChange(client, foundEntity, changedEntityDataKeys);
changedEntityDataKeys.Clear();
}
if (!netOwnerEvents) continue;
// Net Owner
var lastStreamInRange = foundEntity.LastStreamInRange;
if (foundEntity.NetOwner == null)
{
// If net owner is null, we need closest player
if (foundEntity.TempNetOwner == client)
{
var lastNetOwner = foundEntity.NetOwner;
if (lastNetOwner != null)
{
onEntityNetOwnerChange(foundEntity.NetOwner, foundEntity, false);
}
foundEntity.NetOwner = client;
foundEntity.NetOwnerRange = lastStreamInRange;
foundEntity.TempNetOwnerRange = float.MaxValue;
foundEntity.TempNetOwner = null;
onEntityNetOwnerChange(client, foundEntity, true);
}
else if (foundEntity.TempNetOwnerRange > lastStreamInRange)
{
foundEntity.TempNetOwner = client;
foundEntity.TempNetOwnerRange = lastStreamInRange;
}
}
else
{
// If net owner is not null, we need closest player but with migration distance
// And we need to update own range to entity
if (foundEntity.NetOwner == client)
{
foundEntity.NetOwnerRange = lastStreamInRange;
if (foundEntity.TempNetOwnerRange > lastStreamInRange)
{
foundEntity.TempNetOwner = client;
foundEntity.TempNetOwnerRange = lastStreamInRange;
}
}
else if (foundEntity.TempNetOwner == client)
{
var lastNetOwner = foundEntity.NetOwner;
if (lastNetOwner != null)
{
onEntityNetOwnerChange(foundEntity.NetOwner, foundEntity, false);
}
foundEntity.NetOwner = client;
foundEntity.NetOwnerRange = lastStreamInRange;
foundEntity.TempNetOwnerRange = float.MaxValue;
foundEntity.TempNetOwner = null;
onEntityNetOwnerChange(client, foundEntity, true);
}
else if (foundEntity.NetOwnerRange > foundEntity.MigrationDistance
&& foundEntity.TempNetOwnerRange > lastStreamInRange)
{
foundEntity.TempNetOwner = client;
foundEntity.TempNetOwnerRange = lastStreamInRange;
}
}
}
}
}
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
Thread.Sleep(syncRate);
}
}
public void Stop()
{
running = false;
thread.Join();
}
}
}