-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCompactHierarchy.Internal.cs
More file actions
1570 lines (1319 loc) · 69.9 KB
/
CompactHierarchy.Internal.cs
File metadata and controls
1570 lines (1319 loc) · 69.9 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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
using Debug = UnityEngine.Debug;
using ReadOnlyAttribute = Unity.Collections.ReadOnlyAttribute;
using WriteOnlyAttribute = Unity.Collections.WriteOnlyAttribute;
namespace Chisel.Core
{
// TODO: Should be its own container with its own array pointers (fewer indirections)
[GenerateTestsForBurstCompatibility]
public partial struct CompactHierarchy : IDisposable
{
[NoAlias] UnsafeParallelHashMap<int, CompactNodeID> brushMeshToBrush;
[NoAlias] UnsafeList<CompactChildNode> compactNodes;
[NoAlias] SlotIndexMap slotIndexMap;
bool isCreated;
public struct ReadOnly
{
[NoAlias, ReadOnly] NativeList<CompactHierarchy> hierarchies;
int hierarchyIndex;
public ReadOnly(NativeList<CompactHierarchy> hierarchies, int hierarchyIndex)
{
this.hierarchies = hierarchies;
this.hierarchyIndex = hierarchyIndex;
}
public readonly CompactNodeID RootID { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return hierarchies[hierarchyIndex].RootID; } }
public readonly CompactHierarchyID HierarchyID { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return hierarchies[hierarchyIndex].HierarchyID; } }
public readonly bool IsCreated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return hierarchies.IsCreated && hierarchies[hierarchyIndex].isCreated; } }
[return: MarshalAs(UnmanagedType.U1)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool IsValidCompactNodeID(CompactNodeID compactNodeID) { return hierarchies[hierarchyIndex].IsValidCompactNodeID(compactNodeID); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal readonly bool IsAnyStatusFlagSet(CompactNodeID compactNodeID) { return hierarchies[hierarchyIndex].IsAnyStatusFlagSet(compactNodeID); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ClearStatusFlag(CompactNodeID compactNodeID, NodeStatusFlags flag) { hierarchies[hierarchyIndex].ClearStatusFlag(compactNodeID, flag); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void SetStatusFlag(CompactNodeID compactNodeID, NodeStatusFlags flag) { hierarchies[hierarchyIndex].SetStatusFlag(compactNodeID, flag); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal readonly bool IsStatusFlagSet(CompactNodeID compactNodeID, NodeStatusFlags flag) { return hierarchies[hierarchyIndex].IsStatusFlagSet(compactNodeID, flag); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal readonly Int32 GetBrushMeshID(CompactNodeID compactNodeID) { return hierarchies[hierarchyIndex].GetBrushMeshID(compactNodeID); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public CompactNodeID ParentOf(CompactNodeID compactNodeID)
{
Debug.Assert(IsCreated);
if (compactNodeID == CompactNodeID.Invalid)
throw new ArgumentException(nameof(compactNodeID), $"{nameof(compactNodeID)} is an invalid node");
var nodeIndex = hierarchies[hierarchyIndex].HierarchyIndexOfInternal(compactNodeID);
if (nodeIndex == -1)
return CompactNodeID.Invalid;
return hierarchies[hierarchyIndex].compactNodes[nodeIndex].parentID;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float4x4 GetChildTransformation(CompactNodeID compactNodeID) { return hierarchies[hierarchyIndex].UnsafeGetChildRefAtInternal(compactNodeID).transformation; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly int ChildCount(CompactNodeID compactNodeID) { return hierarchies[hierarchyIndex].ChildCount(compactNodeID); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly CompactNodeID GetChildCompactNodeIDAt(CompactNodeID compactNodeID, int index) { return hierarchies[hierarchyIndex].GetChildCompactNodeIDAt(compactNodeID, index); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal CSGOperationType GetOperation(CompactNodeID compactNodeID) { return hierarchies[hierarchyIndex].GetOperation(compactNodeID); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal CSGNodeType GetTypeOfNode(CompactNodeID compactNodeID) { return hierarchies[hierarchyIndex].GetTypeOfNode(compactNodeID); }
}
public CompactNodeID RootID { [MethodImpl(MethodImplOptions.AggressiveInlining)] readonly get; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal set; }
public CompactHierarchyID HierarchyID { [MethodImpl(MethodImplOptions.AggressiveInlining)] readonly get; [MethodImpl(MethodImplOptions.AggressiveInlining)] private set; }
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return isCreated; }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool CheckConsistency()
{
return CheckConsistency(ref CompactHierarchyManager.HierarchyIDLookup, CompactHierarchyManager.HierarchyList, ref CompactHierarchyManager.NodeIDLookup, CompactHierarchyManager.Nodes);
}
internal readonly bool CheckConsistency( ref SlotIndexMap hierarchyIDLookup, NativeList<CompactHierarchy> hierarchies, ref SlotIndexMap nodeIDLookup, NativeList<CompactNodeID> nodes, bool ignoreBrushMeshHashes = false)
{
#if false
if (HierarchyID == default)
{
return true;
}
if (!IsValidCompactNodeID(RootID))
{
Debug.LogError("!IsValidCompactNodeID(RootID)");
return false;
}
if (!slotIndexMap.CheckConsistency())
return false;
var brushMeshKeyValueArrays = brushMeshToBrush.GetKeyValueArrays(Allocator.Temp);
var brushMeshKeys = brushMeshKeyValueArrays.Keys;
var brushMeshValues = brushMeshKeyValueArrays.Values;
try
{
for (int i = 0; i < compactNodes.Length; i++)
{
// If the node is not used, all its values should be set to default
if (compactNodes[i].compactNodeID == default)
{
if (compactNodes[i].nodeID != default ||
compactNodes[i].parentID != default ||
compactNodes[i].childCount != 0 ||
compactNodes[i].childOffset != 0 ||
(!ignoreBrushMeshHashes && compactNodes[i].nodeInformation.brushMeshHash != 0) ||
compactNodes[i].nodeInformation.instanceID != 0)
{
Debug.LogError($"{compactNodes[i].nodeID} != default ||\n{compactNodes[i].parentID} != default ||\n{compactNodes[i].childCount} != 0 ||\n{compactNodes[i].childOffset} != 0 ||\n{compactNodes[i].nodeInformation.brushMeshHash != 0} ||\n{compactNodes[i].nodeInformation.instanceID} != 0");
return false;
}
continue;
}
if (!IsValidCompactNodeID(compactNodes[i].compactNodeID))
{
Debug.LogError($"!IsValidCompactNodeID(compactNodes[{i}].compactNodeID)");
return false;
}
if (!CompactHierarchyManager.IsValidNodeID(ref nodeIDLookup, ref hierarchyIDLookup, hierarchies, nodes, compactNodes[i].nodeID))
{
Debug.LogError($"!CompactHierarchyManager.IsValidNodeID({compactNodes[i].nodeID})");
return false;
}
var foundCompactNodeID = CompactHierarchyManager.GetCompactNodeIDNoError(ref nodeIDLookup, nodes, compactNodes[i].nodeID);
if (foundCompactNodeID != compactNodes[i].compactNodeID)
{
Debug.LogError($"{foundCompactNodeID} != compactNodes[{i}].compactNodeID");
return false;
}
ref var hierarchy = ref CompactHierarchyManager.GetHierarchy(ref hierarchyIDLookup, hierarchies, compactNodes[i].compactNodeID.hierarchyID);
var foundNodeID = hierarchy.GetNodeID(compactNodes[i].compactNodeID);
if (foundNodeID != compactNodes[i].nodeID)
{
Debug.LogError($"{foundNodeID} != compactNodes[{i}].nodeID");
return false;
}
for (int c = 0; c < compactNodes[i].childCount; c++)
{
var childIndex = compactNodes[i].childOffset + c;
if (childIndex < 0 || childIndex >= compactNodes.Length)
{
Debug.LogError($"{childIndex} < 0 || {childIndex} >= {compactNodes.Length}");
return false;
}
if (!IsValidCompactNodeID(compactNodes[childIndex].compactNodeID))
{
Debug.LogError($"!IsValidCompactNodeID(compactNodes[{childIndex}].compactNodeID)");
return false;
}
if (!IsValidCompactNodeID(compactNodes[childIndex].parentID))
{
Debug.LogError($"!IsValidCompactNodeID(compactNodes[{childIndex}].parentID)");
return false;
}
if (compactNodes[childIndex].parentID != compactNodes[i].compactNodeID)
{
Debug.LogError($"compactNodes[{childIndex}].parentID != compactNodes[{i}].compactNodeID");
return false;
}
}
if (!ignoreBrushMeshHashes // Workaround due to hierarchy being (partially) set up before brushMeshes are set by generators
&& compactNodes[i].nodeInformation.brushMeshHash != Int32.MaxValue)
{
if (compactNodes[i].nodeInformation.brushMeshHash == BrushMeshInstance.InvalidInstance.BrushMeshID)
{
Debug.LogError($"compactNodes[{i}] does not have a valid brushMesh set");
return false;
} else
if (!brushMeshKeys.Contains(compactNodes[i].nodeInformation.brushMeshHash))
{
Debug.LogError($"!brushMeshKeys.Contains(compactNodes[{i}].nodeInformation.brushMeshID) {compactNodes[i].nodeInformation.brushMeshHash}");
return false;
}
if (!brushMeshValues.Contains(foundCompactNodeID))
{
Debug.LogError($"!brushMeshValues.Contains(compactNodeID) {foundCompactNodeID}");
return false;
}
}
}
for (int index = 0; index < slotIndexMap.IndexCount; index++)
{
if (!slotIndexMap.IsValidIndex(index, out var value, out var generation))
{
if (compactNodes[index].compactNodeID != default)
{
Debug.LogError($"!slotIndexMap.IsValidIndex({index}, out var {value}, out var {generation}) && compactNodes[{index}].compactNodeID != default");
return false;
}
continue;
}
if (compactNodes[index].compactNodeID.value != value ||
compactNodes[index].compactNodeID.generation != generation)
{
Debug.LogError($"compactNodes[{index}].compactNodeID.value ({compactNodes[index].compactNodeID.value}) != {value} || compactNodes[{index}].compactNodeID.generation != {generation} ({compactNodes[index].compactNodeID.generation})");
return false;
}
if (!slotIndexMap.IsValidID(value, generation, out var foundIndex))
{
Debug.LogError($"!slotIndexMap.IsValidID({value}, {generation}, out var {foundIndex})");
return false;
}
if (foundIndex != index)
{
Debug.LogError($"{foundIndex} != {index}");
return false;
}
}
for (int i = 0; i < brushMeshValues.Length; i++)
{
var compactNodeID = brushMeshValues[i];
if (!slotIndexMap.IsValidID(compactNodeID.value, compactNodeID.generation, out var foundIndex))
{
Debug.LogError($"!slotIndexMap.IsValidID({compactNodeID.value}, {compactNodeID.generation}, out var {foundIndex})");
return false;
}
}
}
finally
{
brushMeshKeyValueArrays.Dispose();
}
#endif
return true;
}
public void Dispose()
{
// Confirmed to be called
isCreated = false;
if (brushMeshToBrush.IsCreated) brushMeshToBrush.Dispose(); brushMeshToBrush = default;
if (compactNodes.IsCreated) compactNodes.Dispose(); compactNodes = default;
try
{
CompactHierarchyManager.FreeHierarchyID(HierarchyID);
}
finally
{
HierarchyID = CompactHierarchyID.Invalid;
if (slotIndexMap.IsCreated) slotIndexMap.Dispose(); slotIndexMap = default;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal CompactNodeID CreateNode(NodeID nodeID, CompactNode nodeInformation)
{
Debug.Assert(IsCreated, "Hierarchy has not been initialized");
int index = Int32.MaxValue;
return CreateNode(nodeID, ref index, in nodeInformation, CompactNodeID.Invalid);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal CompactNodeID CreateNode(NodeID nodeID, in CompactNode nodeInformation, CompactNodeID parentID)
{
Debug.Assert(IsCreated, "Hierarchy has not been initialized");
int index = Int32.MaxValue;
return CreateNode(nodeID, ref index, in nodeInformation, parentID);
}
internal CompactNodeID CreateNode(NodeID nodeID, ref int index, in CompactNode nodeInformation, CompactNodeID parentID)
{
Debug.Assert(IsCreated, "Hierarchy has not been initialized");
SlotIndex slotIndex;
if (index == Int32.MaxValue)
{
index = slotIndexMap.CreateSlotIndex(out slotIndex);
} else
{
slotIndexMap.GetSlotIndex(index, out slotIndex);
Debug.Assert(index >= compactNodes.Length || compactNodes[index].compactNodeID == default);
}
var compactNodeID = new CompactNodeID(hierarchyID: HierarchyID, slotIndex: slotIndex);
if (index >= compactNodes.Length)
{
compactNodes .Resize(index + 1,
NativeArrayOptions.ClearMemory);
//NativeArrayOptions.UninitializedMemory);
}
compactNodes[index] = new CompactChildNode
{
nodeInformation = nodeInformation,
nodeID = nodeID,
compactNodeID = compactNodeID,
parentID = parentID,
childOffset = 0,
childCount = 0
};
if (nodeInformation.brushMeshHash != 0 &&
nodeInformation.brushMeshHash != Int32.MaxValue)
brushMeshToBrush.TryAdd(nodeInformation.brushMeshHash, compactNodeID);
Debug.Assert(IsValidCompactNodeID(compactNodeID), "newly created ID is invalid");
Debug.Assert(GetChildRef(compactNodeID).instanceID == nodeInformation.instanceID, "newly created ID is invalid");
return compactNodeID;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void UpdateHash(CompactNodeID compactNodeID, int newBrushMeshHash)
{
UpdateHash(ref ChiselMeshLookup.Value.brushMeshBlobCache, compactNodeID, newBrushMeshHash);
}
internal bool UpdateHash([NoAlias] ref NativeParallelHashMap<int, RefCountedBrushMeshBlob> brushMeshBlobCache, CompactNodeID compactNodeID, int newBrushMeshHash)
{
var nodeIndex = HierarchyIndexOfInternal(compactNodeID);
if (nodeIndex == -1)
return false;
var compactNode = compactNodes[nodeIndex];
var prevBrushMeshHash = compactNode.nodeInformation.brushMeshHash;
if (prevBrushMeshHash == newBrushMeshHash)
return false;
BrushMeshManager.RegisterBrushMeshHash(ref brushMeshBlobCache, newBrushMeshHash, prevBrushMeshHash);
if (newBrushMeshHash != 0 &&
newBrushMeshHash != Int32.MaxValue)
brushMeshToBrush.TryAdd(newBrushMeshHash, compactNodeID);
if (compactNode.nodeInformation.brushMeshHash != newBrushMeshHash)
compactNode.nodeInformation.brushMeshHash = newBrushMeshHash;
compactNodes[nodeIndex] = compactNode;
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal readonly Int32 GetBrushMeshID(CompactNodeID compactNodeID)
{
Debug.Assert(IsCreated);
var index = HierarchyIndexOfInternal(compactNodeID);
if (index < 0 || index >= compactNodes.Length)
throw new ArgumentException($"The {nameof(CompactNodeID)} {nameof(compactNodeID)} ({compactNodeID}) is invalid", nameof(compactNodeID));
return compactNodes[index].nodeInformation.brushMeshHash;
}
#region ID / Memory Management
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void RemoveMeshReference(CompactNodeID compactNodeID, int brushMeshID)
{
if (brushMeshID == Int32.MaxValue)
return;
brushMeshToBrush.Remove(brushMeshID);//, compactNodeID.value);
/*
var value = compactNodeID.value;
bool found = true;
while (found)
{
found = false;
if (brushMeshToBrush.TryGetFirstValue(brushMeshID, out var item, out var iterator))
{
do
{
if (item.value == value)
{
found = true;
brushMeshToBrush.Remove(iterator);
break;
}
} while (brushMeshToBrush.TryGetNextValue(out item, ref iterator));
}
}*/
}
void FreeIndexRange(int index, int range)
{
if (index < 0 || index + range > compactNodes.Length)
throw new ArgumentOutOfRangeException();
for (int i = index, lastNode = index + range; i < lastNode; i++)
{
var compactNodeID = compactNodes[i].compactNodeID;
var brushMeshID = compactNodes[i].nodeInformation.brushMeshHash;
RemoveMeshReference(compactNodeID, brushMeshID);
compactNodes[i] = default;
}
slotIndexMap.FreeIndexRange(index, range);
}
void RemoveIndexRange(int parentChildOffset, int parentChildCount, int index, int range)
{
if (index < 0 || index + range > compactNodes.Length)
throw new ArgumentOutOfRangeException();
for (int i = index, lastNode = index + range; i < lastNode; i++)
{
var compactNodeID = compactNodes[i].compactNodeID;
var brushMeshID = compactNodes[i].nodeInformation.brushMeshHash;
RemoveMeshReference(compactNodeID, brushMeshID);
compactNodes[i] = default;
}
slotIndexMap.RemoveIndexRange(parentChildOffset, parentChildCount, index, range);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal int AllocateChildCount(int parentNodeIndex, int length)
{
if (length < 0)
throw new ArgumentException(nameof(length));
if (parentNodeIndex < 0 || parentNodeIndex >= compactNodes.Length)
throw new ArgumentException($"{nameof(parentNodeIndex)} ({parentNodeIndex}) must be between 0 and {compactNodes.Length}", nameof(parentNodeIndex));
var parentNode = compactNodes[parentNodeIndex];
if (parentNode.childCount > 0)
throw new ArgumentException($"{nameof(parentNodeIndex)} already has children", nameof(parentNodeIndex));
parentNode.childOffset = slotIndexMap.AllocateIndexRange(length);
parentNode.childCount = length;
compactNodes[parentNodeIndex] = parentNode;
return parentNode.childOffset;
}
#endregion
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly int HierarchyIndexOfInternal(CompactNodeID compactNodeID)
{
Debug.Assert(IsCreated);
if (compactNodeID == CompactNodeID.Invalid)
return -1;
if (compactNodeID.hierarchyID != HierarchyID)
return -1;
return slotIndexMap.GetIndex(compactNodeID.slotIndex);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly int HierarchyIndexOfInternalNoErrors(CompactNodeID compactNodeID)
{
Debug.Assert(IsCreated);
if (compactNodeID == CompactNodeID.Invalid)
return -1;
if (compactNodeID.hierarchyID != HierarchyID)
return -1;
return slotIndexMap.GetIndexNoErrors(compactNodeID.slotIndex);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly int UnsafeHierarchyIndexOfInternal(CompactNodeID compactNodeID)
{
return slotIndexMap.GetIndex(compactNodeID.slotIndex);
}
// WARNING: The returned reference will become invalid after modifying the hierarchy!
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly ref CompactChildNode UnsafeGetNodeRefAtInternal(CompactNodeID compactNodeID)
{
Debug.Assert(IsCreated, "Hierarchy has not been initialized");
var nodeIndex = UnsafeHierarchyIndexOfInternal(compactNodeID);
unsafe
{
var compactNodesPtr = compactNodes.Ptr;
return ref compactNodesPtr[nodeIndex];
}
}
// WARNING: The returned reference will become invalid after modifying the hierarchy!
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly ref CompactNode UnsafeGetChildRefAtInternal(CompactNodeID compactNodeID)
{
Debug.Assert(IsCreated, "Hierarchy has not been initialized");
var nodeIndex = UnsafeHierarchyIndexOfInternal(compactNodeID);
unsafe
{
var compactNodesPtr = compactNodes.Ptr;
return ref compactNodesPtr[nodeIndex].nodeInformation;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal readonly CompactNodeID GetChildIDAtInternalNoError(CompactNodeID parentD, int index)
{
Debug.Assert(IsCreated, "Hierarchy has not been initialized");
var parentIndex = UnsafeHierarchyIndexOfInternal(parentD);
var parentHierarchy = compactNodes[parentIndex];
var parentChildOffset = parentHierarchy.childOffset;
var parentChildCount = parentHierarchy.childCount;
if (index < 0 || index >= parentChildCount)
return CompactNodeID.Invalid;
var nodeIndex = parentChildOffset + index;
if (nodeIndex < 0 || nodeIndex >= compactNodes.Length)
return CompactNodeID.Invalid;
unsafe
{
var compactNodesPtr = compactNodes.Ptr;
return compactNodesPtr[nodeIndex].compactNodeID;
}
}
// WARNING: The returned reference will become invalid after modifying the hierarchy!
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly CompactNodeID GetChildCompactNodeIDAtInternal(CompactNodeID parentD, int index)
{
Debug.Assert(IsCreated, "Hierarchy has not been initialized");
var parentIndex = UnsafeHierarchyIndexOfInternal(parentD);
var parentHierarchy = compactNodes[parentIndex];
var parentChildOffset = parentHierarchy.childOffset;
var parentChildCount = parentHierarchy.childCount;
if (index < 0 || index >= parentChildCount) throw new ArgumentOutOfRangeException(nameof(index));
var nodeIndex = parentChildOffset + index;
if (nodeIndex < 0 || nodeIndex >= compactNodes.Length) throw new ArgumentOutOfRangeException(nameof(nodeIndex));
unsafe
{
var compactNodesPtr = compactNodes.Ptr;
return compactNodesPtr[nodeIndex].compactNodeID;
}
}
// WARNING: The returned reference will become invalid after modifying the hierarchy!
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal readonly CompactNodeID GetChildCompactNodeIDAtNoError(CompactNodeID parentD, int index)
{
Debug.Assert(IsCreated, "Hierarchy has not been initialized");
var parentIndex = UnsafeHierarchyIndexOfInternal(parentD);
var parentHierarchy = compactNodes[parentIndex];
var parentChildOffset = parentHierarchy.childOffset;
var parentChildCount = parentHierarchy.childCount;
if (index < 0 || index >= parentChildCount)
return CompactNodeID.Invalid;
var nodeIndex = parentChildOffset + index;
if (nodeIndex < 0 || nodeIndex >= compactNodes.Length)
return CompactNodeID.Invalid;
unsafe
{
var compactNodesPtr = compactNodes.Ptr;
return compactNodesPtr[nodeIndex].compactNodeID;
}
}
// WARNING: The returned reference will become invalid after modifying the hierarchy!
[MethodImpl(MethodImplOptions.AggressiveInlining)]
ref CompactNode SafeGetChildRefAtInternal(CompactNodeID parentD, int index)
{
Debug.Assert(IsCreated, "Hierarchy has not been initialized");
var parentIndex = UnsafeHierarchyIndexOfInternal(parentD);
var parentHierarchy = compactNodes[parentIndex];
var parentChildOffset = parentHierarchy.childOffset;
var parentChildCount = parentHierarchy.childCount;
if (index < 0 || index >= parentChildCount) throw new ArgumentOutOfRangeException(nameof(index));
var nodeIndex = parentChildOffset + index;
if (nodeIndex < 0 || nodeIndex >= compactNodes.Length) throw new ArgumentOutOfRangeException(nameof(nodeIndex));
unsafe
{
var compactNodesPtr = compactNodes.Ptr;
return ref compactNodesPtr[nodeIndex].nodeInformation;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly int SiblingIndexOfInternal(int parentIndex, int nodeIndex)
{
var parentHierarchy = compactNodes[parentIndex];
var parentChildOffset = parentHierarchy.childOffset;
var parentChildCount = parentHierarchy.childCount;
var index = nodeIndex - parentChildOffset;
Debug.Assert(index >= 0 && index < parentChildCount);
return index;
}
bool DeleteRangeInternal(int parentIndex, int siblingIndex, int range, bool deleteChildren)
{
if (range == 0)
return false;
Debug.Assert(parentIndex >= 0 && parentIndex < compactNodes.Length);
var parentHierarchy = compactNodes[parentIndex];
var parentChildOffset = parentHierarchy.childOffset;
var parentChildCount = parentHierarchy.childCount;
if (siblingIndex < 0 || siblingIndex + range > parentChildCount)
throw new ArgumentOutOfRangeException(nameof(siblingIndex));
if (deleteChildren)
{
// Delete all children of the nodes we're going to delete
for (int i = parentChildOffset + siblingIndex, lastIndex = (parentChildOffset + siblingIndex + range); i < lastIndex; i++)
{
var childHierarchy = compactNodes[i];
var childCount = childHierarchy.childCount;
DeleteRangeInternal(i, 0, childCount, deleteChildren: true);
}
} else
{
// Detach all children of the nodes we're going to delete
for (int i = parentChildOffset + siblingIndex, lastIndex = (parentChildOffset + siblingIndex + range); i < lastIndex; i++)
{
var childHierarchy = compactNodes[i];
var childCount = childHierarchy.childCount;
DetachRangeInternal(i, 0, childCount);
}
}
var nodeIndex = siblingIndex + parentChildOffset;
// Check if we're deleting from the front of the list of children
if (siblingIndex == 0)
{
// Clear the ids of the children we're deleting
FreeIndexRange(nodeIndex, range);
for (int i = nodeIndex; i < nodeIndex + range; i++)
{
compactNodes[i] = default;
}
// If the range is identical to the number of children, we're deleting all the children
if (parentChildCount == range)
{
parentHierarchy.childCount = 0;
parentHierarchy.childOffset = 0;
compactNodes[parentIndex] = parentHierarchy;
} else
// Otherwise, we can just move the start offset of the parents' children forward
{
Debug.Assert(parentChildCount > range);
parentHierarchy.childCount -= range;
parentHierarchy.childOffset += range;
compactNodes[parentIndex] = parentHierarchy;
}
return true;
} else
// Check if we're deleting from the back of the list of children
if (siblingIndex == parentChildCount - range)
{
// Clear the ids of the children we're deleting
FreeIndexRange(nodeIndex, range);
for (int i = nodeIndex; i < nodeIndex + range; i++)
{
compactNodes[i] = default;
}
// In that case, we can just decrease the number of children in the list
parentHierarchy.childCount -= range;
compactNodes[parentIndex] = parentHierarchy;
return true;
}
// If we get here, it means we're deleting children in the center of the list of children
// Clear the ids of the children we're deleting
RemoveIndexRange(parentChildOffset, parentChildCount, nodeIndex, range);
// Move nodes behind our node on top of the node we're removing
var count = parentChildCount - (siblingIndex + range);
compactNodes.MemMove(nodeIndex, nodeIndex + range, count);
for (int i = nodeIndex + count; i < parentChildOffset + parentChildCount; i++)
{
compactNodes[i] = default;
}
parentHierarchy.childCount -= range;
compactNodes[parentIndex] = parentHierarchy;
return true;
}
// "optimize" - remove holes, reorder them in hierarchy order
bool CompactInternal()
{
// TODO: implement
// could just create a new hierarchy and insert everything in it in order, and replace the hierarchy with this one
throw new NotImplementedException();
}
bool DetachAllChildrenInternal(int parentIndex)
{
Debug.Assert(parentIndex >= 0 && parentIndex < compactNodes.Length);
var parentHierarchy = compactNodes[parentIndex];
var parentChildCount = parentHierarchy.childCount;
return DetachRangeInternal(parentIndex, 0, parentChildCount);
}
bool DeleteAllChildrenInternal(int parentIndex)
{
Debug.Assert(parentIndex >= 0 && parentIndex < compactNodes.Length);
var parentHierarchy = compactNodes[parentIndex];
var parentChildCount = parentHierarchy.childCount;
return DeleteRangeInternal(parentIndex, 0, parentChildCount, true);
}
bool DetachRangeInternal(int parentIndex, int siblingIndex, int range)
{
if (range == 0)
return false;
Debug.Assert(parentIndex >= 0 && parentIndex < compactNodes.Length);
var parentHierarchy = compactNodes[parentIndex];
var parentChildOffset = parentHierarchy.childOffset;
var parentChildCount = parentHierarchy.childCount;
var lastNodeIndex = parentChildCount + parentChildOffset - 1;
if (siblingIndex < 0 || siblingIndex + range > parentChildCount)
throw new ArgumentOutOfRangeException(nameof(siblingIndex));
var nodeIndex = siblingIndex + parentChildOffset;
// Set the parents of our detached nodes to invalid
unsafe
{
var compactNodesPtr = compactNodes.Ptr;
for (int i = nodeIndex; i < nodeIndex + range; i++)
{
compactNodesPtr[i].parentID = CompactNodeID.Invalid;
}
}
// Check if we're detaching from the front of the list of children
if (siblingIndex == 0)
{
// If the range is identical to the number of children, we're detaching all the children
if (parentChildCount == range)
{
parentHierarchy.childCount = 0;
parentHierarchy.childOffset = 0;
compactNodes[parentIndex] = parentHierarchy;
} else
// Otherwise, we can just move the start offset of the parents' children forward
{
parentHierarchy.childCount -= range;
parentHierarchy.childOffset += range;
compactNodes[parentIndex] = parentHierarchy;
}
return true;
} else
// Check if we're detaching from the back of the list of children
if (siblingIndex == parentChildCount - range)
{
// In that case, we can just decrease the number of children in the list
parentHierarchy.childCount -= range;
compactNodes[parentIndex] = parentHierarchy;
return true;
}
// If we get here, it means we're detaching children in the center of the list of children
var prevLength = compactNodes.Length;
// Resize compactNodes to have space for the nodes we're detaching (compactNodes will probably have capacity for this already)
compactNodes.Resize(prevLength + range,
NativeArrayOptions.ClearMemory);
//NativeArrayOptions.UninitializedMemory);
// Copy the original nodes to behind all our other nodes
compactNodes.MemMove(prevLength, nodeIndex, range);
// Move nodes behind our node on top of the node we're removing
var count = parentChildCount - (siblingIndex + range);
compactNodes.MemMove(nodeIndex, nodeIndex + range, count);
// Copy original nodes to behind the new parent child list
compactNodes.MemMove(lastNodeIndex, prevLength, range);
// Set the compactNodes length to its original size
compactNodes.Resize(prevLength,
NativeArrayOptions.ClearMemory);
//NativeArrayOptions.UninitializedMemory);
slotIndexMap.SwapIndexRangeToBack(parentChildOffset, parentChildCount, siblingIndex, range);
parentHierarchy.childCount -= range;
compactNodes[parentIndex] = parentHierarchy;
return true;
}
// Note: assumes the given compactNodeID and their respective nodeIDs are consecutive
internal int SetChildrenUncheckedSlowPath(int parentChildOffset, int parentChildCount, int insertStartIndex, CompactNodeID parentID, NativeList<CompactNodeID> compactNodeIDs, int startCompactNodeIndex, int count)
{
var compactNodeID = compactNodeIDs[startCompactNodeIndex];
var nodeIndex = HierarchyIndexOfInternal(compactNodeID);
var prevChildOffset = parentChildOffset;
var prevChildCount = parentChildCount;
var insertIndex = insertStartIndex;
Debug.Assert(!slotIndexMap.IsAnyIndexFree(nodeIndex, count));
// Find (or create) a span of enough elements that we can use to copy our children into
parentChildOffset = slotIndexMap.InsertIndexRange(prevChildOffset, prevChildCount, srcIndex: nodeIndex, dstIndex: insertIndex, count);
Debug.Assert(parentChildOffset >= 0 && parentChildOffset < compactNodes.Length + prevChildCount + count);
//Debug.Log($"{parentChildCount} {count} | {parentChildOffset} {prevChildOffset} | {prevChildCount - insertIndex} | {parentChildOffset} {insertIndex} | {nodeIndex} {parentChildOffset + insertIndex}");
if (compactNodes.Length < parentChildOffset + prevChildCount + count)
{
compactNodes.Resize(parentChildOffset + prevChildCount + count, NativeArrayOptions.ClearMemory);
}
// We first move the last nodes to the correct new offset ..
var items = prevChildCount - insertIndex;
if (items != 0)
{
compactNodes.MemMove(parentChildOffset + insertIndex + count, prevChildOffset + insertIndex, items);
}
// If our offset is different then the front section will not be in the right location, so we might need to copy this
// We'd also need to reset the old nodes to invalid, if we don't we'd create new dangling nodes
if (prevChildOffset != parentChildOffset && insertIndex != 0)
{
// Then we move the first part (if necesary)
compactNodes.MemMove(parentChildOffset, prevChildOffset, insertIndex);
}
compactNodes .ClearValues(parentChildOffset + insertIndex, count);
for (int c = 0; c < count; c++)
{
// Then we copy our node to the new location
var oldNodeIndex = nodeIndex + c;
var newNodeIndex = parentChildOffset + insertIndex + c;
var nodeItem = compactNodes[oldNodeIndex];
nodeItem.parentID = parentID;
compactNodes[newNodeIndex] = nodeItem;
// Then we set the old indices to 0
if (oldNodeIndex < parentChildOffset || oldNodeIndex > (parentChildOffset + parentChildCount + count))
{
compactNodes[oldNodeIndex] = default;
}
}
if (prevChildOffset != parentChildOffset)
{
// Set the old indices to 0
for (int c = prevChildOffset; c < prevChildOffset + prevChildCount; c++)
{
if (c < parentChildOffset || c > (parentChildOffset + parentChildCount + count))
{
compactNodes[c] = default;
}
}
}
return parentChildOffset;
}
internal bool SetChildrenUnchecked(ref SlotIndexMap hierarchyIDLookup, NativeList<CompactHierarchy> hierarchies, ref SlotIndexMap nodeIDLookup, NativeList<CompactNodeID> nodes, CompactNodeID parentID, NativeList<CompactNodeID> compactNodeIDs, bool ignoreBrushMeshHashes = false)
{
Debug.Assert(IsCreated);
var parentIndex = HierarchyIndexOfInternal(parentID);
if (parentIndex == -1)
throw new ArgumentException(nameof(parentID), $"{nameof(parentID)} is invalid");
Debug.Assert(parentID != CompactNodeID.Invalid);
var parentHierarchy = compactNodes[parentIndex];
bool noChange = true;
for (int c = compactNodeIDs.Length - 1; c >= 0; c--)
{
var compactNodeID = compactNodeIDs[c];
var nodeIndex = HierarchyIndexOfInternal(compactNodeID);
if (nodeIndex == -1)
throw new ArgumentException($"{nameof(CompactNodeID)} is invalid", nameof(compactNodeID));
var parentChildOffset = parentHierarchy.childOffset;
var desiredIndex = parentChildOffset + c;
if (desiredIndex != nodeIndex)
noChange = false;
}
if (noChange &&
parentHierarchy.childCount == compactNodeIDs.Length)
return true;
DetachAllChildrenInternal(parentIndex);
//Debug.Log($"Start {compactNodeIDs.Length}");
bool needIdFixup = false;
int insertIndex = 0;
for (int c = 0; c < compactNodeIDs.Length; c++)
{
var parentChildCount = parentHierarchy.childCount;
Debug.Assert(insertIndex >= 0 && insertIndex <= parentChildCount);
var compactNodeID = compactNodeIDs[c];
var nodeIndex = HierarchyIndexOfInternal(compactNodeID);
var parentChildOffset = parentHierarchy.childOffset;
var desiredIndex = parentChildOffset + insertIndex;
// If our new parent doesn't have any child nodes yet, we don't need to move our node and just set
// our node as the location for our children
if (parentChildCount == 0)
{
// Make a temporary copy of our node in case we need to move it
var nodeItem = compactNodes[nodeIndex];
parentHierarchy.childOffset = nodeIndex;
parentHierarchy.childCount = 1;
compactNodes[parentIndex] = parentHierarchy;
nodeItem.parentID = parentID;
compactNodes[nodeIndex] = nodeItem;
insertIndex++;
continue;
}
// If the desired index of our node is already at the index we want it to be, things are simple
if (desiredIndex == nodeIndex)
{
// Make a temporary copy of our node in case we need to move it
var nodeItem = compactNodes[nodeIndex];
parentHierarchy.childCount ++;
compactNodes[parentIndex] = parentHierarchy;
nodeItem.parentID = parentID;
compactNodes[nodeIndex] = nodeItem;
insertIndex++;
continue;
}
// If, however, the desired index of our node is NOT at the index we want it to be,
// we need to move nodes around
// find all nodes that are consecutive so we can move them together
var prevNodeIndex = nodeIndex;
var lastCompactNodeIndex = c;
do
{
lastCompactNodeIndex++;
if (lastCompactNodeIndex >= compactNodeIDs.Length)
break;
var nextNodeIndex = HierarchyIndexOfInternal(compactNodeIDs[lastCompactNodeIndex]);
if (nextNodeIndex - prevNodeIndex != 1)
break;
prevNodeIndex = nextNodeIndex;
} while (true);
//Debug.Log($"{lastCompactNodeIndex - c} | {c} {lastCompactNodeIndex} {compactNodeIDs.Length} | {nodeIndex}");
needIdFixup = true;
UnityEngine.Profiling.Profiler.BeginSample("Slow path");
var count = (lastCompactNodeIndex - c);
var insertStartIndex = insertIndex;
parentChildOffset = SetChildrenUncheckedSlowPath(parentChildOffset, parentChildCount, insertStartIndex, parentID, compactNodeIDs, c, count);
parentHierarchy.childOffset = parentChildOffset; // We make sure we set the parent child offset correctly
parentHierarchy.childCount += count; // And we increase the childCount of our parent