This repository was archived by the owner on Jan 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 887
Expand file tree
/
Copy pathMyOreDetectorComponent.cs
More file actions
439 lines (378 loc) · 16.7 KB
/
Copy pathMyOreDetectorComponent.cs
File metadata and controls
439 lines (378 loc) · 16.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
#region Using
using ParallelTasks;
using Sandbox.Definitions;
using Sandbox.Engine.Voxels;
using Sandbox.Game.Gui;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using VRage.Collections;
using VRage.Generics;
using VRage.Profiler;
using VRage.Utils;
using VRage.Voxels;
using VRageMath;
using VRageRender.Utils;
#endregion
namespace Sandbox.Game.Entities.Cube
{
public class MyEntityOreDeposit
{
public struct Data
{
public MyVoxelMaterialDefinition Material;
public Vector3D AverageLocalPosition;
internal void ComputeWorldPosition(MyVoxelBase voxelMap, out Vector3D oreWorldPosition)
{
MyVoxelCoordSystems.LocalPositionToWorldPosition(voxelMap.PositionComp.GetPosition() - (Vector3D)voxelMap.StorageMin, ref AverageLocalPosition, out oreWorldPosition);
}
}
public MyVoxelBase VoxelMap;
public Vector3I CellCoord;
public readonly List<Data> Materials = new List<Data>();
public MyEntityOreDeposit(MyVoxelBase voxelMap, Vector3I cellCoord)
{
VoxelMap = voxelMap;
CellCoord = cellCoord;
}
public class TypeComparer : IEqualityComparer<MyEntityOreDeposit>
{
bool IEqualityComparer<MyEntityOreDeposit>.Equals(MyEntityOreDeposit x, MyEntityOreDeposit y)
{
return x.VoxelMap.EntityId == y.VoxelMap.EntityId &&
x.CellCoord == y.CellCoord;
}
int IEqualityComparer<MyEntityOreDeposit>.GetHashCode(MyEntityOreDeposit obj)
{
return (int)(obj.VoxelMap.EntityId ^ obj.CellCoord.GetHashCode());
}
}
public static readonly TypeComparer Comparer = new TypeComparer();
}
class MyOreDepositGroup
{
private static Dictionary<Vector3I, MyEntityOreDeposit> m_swapBuffer = new Dictionary<Vector3I, MyEntityOreDeposit>(Vector3I.Comparer);
private readonly HashSet<Vector3I> m_queriesToIssue = new HashSet<Vector3I>(Vector3I.Comparer);
private readonly HashSet<Vector3I> m_issuedQueries = new HashSet<Vector3I>(Vector3I.Comparer);
private readonly MyVoxelBase m_voxelMap;
private readonly Action<Vector3I, MyEntityOreDeposit> m_onDepositQueryComplete;
private Dictionary<Vector3I, MyEntityOreDeposit> m_depositsByCellCoord = new Dictionary<Vector3I, MyEntityOreDeposit>(Vector3I.Comparer);
private Vector3I m_lastDetectionMin;
private Vector3I m_lastDetectionMax;
public MyOreDepositGroup(MyVoxelBase voxelMap)
{
m_voxelMap = voxelMap;
m_onDepositQueryComplete = OnDepositQueryComplete;
m_lastDetectionMax = new Vector3I(int.MinValue);
m_lastDetectionMin = new Vector3I(int.MaxValue);
}
private void OnDepositQueryComplete(Vector3I depositCell, MyEntityOreDeposit deposit)
{
Debug.Assert(m_issuedQueries.Contains(depositCell));
m_issuedQueries.Remove(depositCell);
m_depositsByCellCoord[depositCell] = deposit;
IssueQueries();
}
public DictionaryValuesReader<Vector3I, MyEntityOreDeposit> Deposits
{
get { return m_depositsByCellCoord; }
}
public void UpdateDeposits(ref BoundingSphereD worldDetectionSphere)
{
Vector3I min, max;
{
var worldMin = worldDetectionSphere.Center - worldDetectionSphere.Radius;
var worldMax = worldDetectionSphere.Center + worldDetectionSphere.Radius;
MyVoxelCoordSystems.WorldPositionToVoxelCoord(m_voxelMap.PositionLeftBottomCorner, ref worldMin, out min);
MyVoxelCoordSystems.WorldPositionToVoxelCoord(m_voxelMap.PositionLeftBottomCorner, ref worldMax, out max);
// mk:TODO Get rid of this computation. Might require a mechanism to figure out whether MyVoxelMap is subpart of MyPlanet or not. (Maybe third class for subparts?)
min += m_voxelMap.StorageMin;
max += m_voxelMap.StorageMin;
m_voxelMap.Storage.ClampVoxelCoord(ref min);
m_voxelMap.Storage.ClampVoxelCoord(ref max);
min >>= (MyOreDetectorComponent.CELL_SIZE_IN_VOXELS_BITS + MyOreDetectorComponent.QUERY_LOD);
max >>= (MyOreDetectorComponent.CELL_SIZE_IN_VOXELS_BITS + MyOreDetectorComponent.QUERY_LOD);
}
if (min == m_lastDetectionMin && max == m_lastDetectionMax)
{
IssueQueries();
return;
}
m_lastDetectionMin = min;
m_lastDetectionMax = max;
Vector3I c;
for (c.Z = min.Z; c.Z <= max.Z; ++c.Z)
{
for (c.Y = min.Y; c.Y <= max.Y; ++c.Y)
{
for (c.X = min.X; c.X <= max.X; ++c.X)
{
MyEntityOreDeposit deposit;
if (m_depositsByCellCoord.TryGetValue(c, out deposit))
{
m_swapBuffer.Add(c, deposit);
}
else if (!m_issuedQueries.Contains(c))
{
m_queriesToIssue.Add(c);
}
}
}
}
MyUtils.Swap(ref m_swapBuffer, ref m_depositsByCellCoord);
m_swapBuffer.Clear();
IssueQueries();
}
private void IssueQueries()
{
while (m_issuedQueries.Count < 100 && m_queriesToIssue.Count > 0)
{ // discard queries which have gone out of range
var e = m_queriesToIssue.GetEnumerator();
e.MoveNext();
var coord = e.Current;
if (!coord.IsInsideInclusive(ref m_lastDetectionMin, ref m_lastDetectionMax))
{
m_queriesToIssue.Remove(coord);
continue;
}
MyDepositQuery.Start(new MyDepositQuery.Args()
{
VoxelMap = m_voxelMap,
CompletionCallback = m_onDepositQueryComplete,
Cell = coord,
});
m_issuedQueries.Add(coord);
m_queriesToIssue.Remove(coord);
}
Stats.Generic.Write("Ore detector queries", m_queriesToIssue.Count + m_issuedQueries.Count, VRage.Stats.MyStatTypeEnum.CurrentValue, 100, 0);
}
}
class MyOreDetectorComponent
{
public const int QUERY_LOD = 1;
public const int CELL_SIZE_IN_VOXELS_BITS = 3;
public const int CELL_SIZE_IN_LOD_VOXELS = 1 << CELL_SIZE_IN_VOXELS_BITS;
public const float CELL_SIZE_IN_METERS = MyVoxelConstants.VOXEL_SIZE_IN_METRES * (1 << (CELL_SIZE_IN_VOXELS_BITS + QUERY_LOD));
public const float CELL_SIZE_IN_METERS_HALF = CELL_SIZE_IN_METERS * 0.5f;
private static readonly List<MyVoxelBase> m_inRangeCache = new List<MyVoxelBase>();
private static readonly List<MyVoxelBase> m_notInRangeCache = new List<MyVoxelBase>();
public HashSet <MyEntityOreDeposit> DetectedDeposits { get; private set; }
public delegate bool CheckControlDelegate();
public float DetectionRadius { get; set; }
public CheckControlDelegate OnCheckControl;
public bool BroadcastUsingAntennas { get; set; }
private readonly Dictionary<MyVoxelBase, MyOreDepositGroup> m_depositGroupsByEntity = new Dictionary<MyVoxelBase, MyOreDepositGroup>();
public MyOreDetectorComponent()
{
DetectionRadius = 50;
SetRelayedRequest = false;
BroadcastUsingAntennas = false;
DetectedDeposits = new HashSet <MyEntityOreDeposit>();
}
public bool SetRelayedRequest { get; set; }
public void Update (Vector3D position, bool onlyUpdateMember, bool checkControl = true)
{
if (onlyUpdateMember == false)
{
Clear(); //It should only clear hud markers if it's prepared to renew them.
if (!SetRelayedRequest && checkControl && !OnCheckControl())
{
//m_depositGroupsByEntity.Clear(); I commented this out because it, in some states, causes DetectedDeposits to ouput as empty. m_depositGroupsByEntity seems to take more than one method one to fully update.
return;
}
SetRelayedRequest = false;
}
else
{
DetectedDeposits.Clear();
}
var sphere = new BoundingSphereD (position, DetectionRadius);
MyGamePruningStructure.GetAllVoxelMapsInSphere (ref sphere, m_inRangeCache);
{ // Find voxel maps which went out of range and then remove them.
foreach (var voxelMap in m_depositGroupsByEntity.Keys)
{
if (!m_inRangeCache.Contains (voxelMap))
m_notInRangeCache.Add (voxelMap);
}
foreach (var notInRange in m_notInRangeCache)
{
m_depositGroupsByEntity.Remove (notInRange);
}
m_notInRangeCache.Clear();
}
{ // Add voxel maps which came into range.
foreach (var voxelMap in m_inRangeCache)
{
if (!m_depositGroupsByEntity.ContainsKey (voxelMap))
m_depositGroupsByEntity.Add (voxelMap, new MyOreDepositGroup(voxelMap));
}
m_inRangeCache.Clear();
}
// Update deposit queries using current detection sphere.
foreach (var entry in m_depositGroupsByEntity)
{
var voxelMap = entry.Key;
var group = entry.Value;
group.UpdateDeposits (ref sphere);
foreach (var deposit in group.Deposits)
{
if (deposit != null)
{
switch (onlyUpdateMember) //the method has been divided into these two choices because previously, oremarkers could not be fetched without a radio antenna.
{
case true:
DetectedDeposits.Add (deposit);
break;
case false:
MyHud.OreMarkers.RegisterMarker (deposit);
break;
}
}
}
}
m_inRangeCache.Clear();
}
public void Clear()
{
foreach (var group in m_depositGroupsByEntity.Values)
{
foreach (var deposit in group.Deposits)
{
if (deposit != null)
{
MyHud.OreMarkers.UnregisterMarker (deposit);
}
}
}
DetectedDeposits.Clear();
}
}
/// <summary>
/// This is not in Sandbox.Engine.Voxels as I consider it gameplay related,
/// rather than voxel engine functionality.
/// </summary>
class MyDepositQuery : IPrioritizedWork
{
public struct Args
{
public Vector3I Cell;
public MyVoxelBase VoxelMap;
public Action<Vector3I, MyEntityOreDeposit> CompletionCallback;
}
struct MaterialPositionData
{
public Vector3 Sum;
public int Count;
}
private static readonly MyDynamicObjectPool<MyDepositQuery> m_instancePool = new MyDynamicObjectPool<MyDepositQuery>(16);
[ThreadStatic]
private static MyStorageData m_cache;
private static MyStorageData Cache
{
get
{
if (m_cache == null)
m_cache = new MyStorageData();
return m_cache;
}
}
[ThreadStatic]
private static MaterialPositionData[] m_materialData;
private static MaterialPositionData[] MaterialData
{
get
{
if (m_materialData == null)
m_materialData = new MaterialPositionData[byte.MaxValue];
return m_materialData;
}
}
private Args m_args;
private MyEntityOreDeposit m_result;
private Action m_onComplete;
public MyDepositQuery()
{
m_onComplete = OnComplete;
}
public static void Start(Args args)
{
var job = m_instancePool.Allocate();
job.m_args = args;
Parallel.Start(job, job.m_onComplete);
}
private void OnComplete()
{
m_args.CompletionCallback(m_args.Cell, m_result);
m_args = default(Args);
m_result = null;
m_instancePool.Deallocate(this);
}
WorkPriority IPrioritizedWork.Priority
{
get { return WorkPriority.VeryLow; }
}
void IWork.DoWork(WorkData workData = null)
{
ProfilerShort.Begin("MyDepositQuery.DoWork");
try
{
var cache = Cache;
cache.Resize(new Vector3I(MyOreDetectorComponent.CELL_SIZE_IN_LOD_VOXELS));
var min = m_args.Cell << MyOreDetectorComponent.CELL_SIZE_IN_VOXELS_BITS;
var max = min + (MyOreDetectorComponent.CELL_SIZE_IN_LOD_VOXELS - 1);
var storage = m_args.VoxelMap.Storage;
if (storage == null || storage.Closed)
return; // voxel map was probably closed in the meantime.
using (storage.Pin())
{
storage.ReadRange(cache, MyStorageDataTypeFlags.Content, MyOreDetectorComponent.QUERY_LOD, ref min, ref max);
if (!cache.ContainsVoxelsAboveIsoLevel())
return;
storage.ReadRange(cache, MyStorageDataTypeFlags.Material, MyOreDetectorComponent.QUERY_LOD, ref min, ref max);
}
var materialData = MaterialData;
Vector3I c;
for (c.Z = 0; c.Z < MyOreDetectorComponent.CELL_SIZE_IN_LOD_VOXELS; ++c.Z)
for (c.Y = 0; c.Y < MyOreDetectorComponent.CELL_SIZE_IN_LOD_VOXELS; ++c.Y)
for (c.X = 0; c.X < MyOreDetectorComponent.CELL_SIZE_IN_LOD_VOXELS; ++c.X)
{
int i = cache.ComputeLinear(ref c);
if (cache.Content(i) > MyVoxelConstants.VOXEL_ISO_LEVEL)
{
const float VOXEL_SIZE = MyVoxelConstants.VOXEL_SIZE_IN_METRES * (1 << MyOreDetectorComponent.QUERY_LOD);
const float VOXEL_SIZE_HALF = VOXEL_SIZE * 0.5f;
var material = cache.Material(i);
Vector3D localPos = (c + min) * VOXEL_SIZE + VOXEL_SIZE_HALF;
materialData[material].Sum += localPos;
materialData[material].Count += 1;
}
}
for (int materialIdx = 0; materialIdx < materialData.Length; ++materialIdx)
{
if (materialData[materialIdx].Count == 0)
continue;
var material = MyDefinitionManager.Static.GetVoxelMaterialDefinition((byte)materialIdx);
if (material.IsRare)
{
if (m_result == null)
m_result = new MyEntityOreDeposit(m_args.VoxelMap, m_args.Cell);
m_result.Materials.Add(new MyEntityOreDeposit.Data()
{
Material = material,
AverageLocalPosition = Vector3D.Transform((materialData[materialIdx].Sum / materialData[materialIdx].Count - m_args.VoxelMap.SizeInMetresHalf), Quaternion.CreateFromRotationMatrix(m_args.VoxelMap.WorldMatrix)),
});
}
}
Array.Clear(materialData, 0, materialData.Length);
}
finally
{
ProfilerShort.End();
}
}
WorkOptions IWork.Options
{
get { return Parallel.DefaultOptions; }
}
}
}