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 pathMyCubeGrid.Static.cs
More file actions
2566 lines (2225 loc) · 118 KB
/
Copy pathMyCubeGrid.Static.cs
File metadata and controls
2566 lines (2225 loc) · 118 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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Havok;
using Sandbox.Common;
using Sandbox.Common.ObjectBuilders;
using Sandbox.Definitions;
using Sandbox.Engine.Models;
using Sandbox.Engine.Physics;
using Sandbox.Engine.Utils;
using Sandbox.Game.Entities.Cube;
using Sandbox.Game.Entities.Blocks;
using Sandbox.Game.World;
using VRage.Utils;
using VRageMath;
using VRageMath.PackedVector;
using VRageRender;
using VRage;
using Sandbox.Graphics.GUI;
using System.Text;
using Sandbox.Common.ObjectBuilders.Definitions;
using VRage.Plugins;
using System.Reflection;
using Sandbox.Common.Components;
using Sandbox.Game.Entities;
using VRage.Voxels;
using Sandbox.Game.GameSystems.Electricity;
using Sandbox.Game.Localization;
using Sandbox.Game.GameSystems.StructuralIntegrity;
using VRage.Library.Utils;
using VRage.Import;
using MyFileSystem = VRage.FileSystem.MyFileSystem;
using VRage.Game.Components;
using VRage.ObjectBuilders;
using Sandbox.Game.Entities.Character;
using VRage.Game;
using VRage.Network;
using VRage.Render.Models;
using VRage.Game.Models;
using VRage.Game.Entity;
namespace Sandbox.Game.Entities
{
partial class MyCubeGrid
{
class AreaConnectivityTest : IMyGridConnectivityTest
{
Dictionary<Vector3I, Vector3I> m_lookup = new Dictionary<Vector3I, Vector3I>();
MyBlockOrientation m_orientation;
MyCubeBlockDefinition m_definition;
Vector3I m_posInGrid;
Vector3I m_blockMin;
Vector3I m_blockMax;
Vector3I m_stepDelta;
public void Initialize(ref MyBlockBuildArea area, MyCubeBlockDefinition definition)
{
m_definition = definition;
m_orientation = new MyBlockOrientation(area.OrientationForward, area.OrientationUp);
m_posInGrid = area.PosInGrid;
m_blockMin = area.BlockMin;
m_blockMax = area.BlockMax;
m_stepDelta = area.StepDelta;
m_lookup.Clear();
}
public void AddBlock(Vector3UByte offset)
{
Vector3I pos = m_posInGrid + offset * m_stepDelta;
Vector3I cube;
for (cube.X = m_blockMin.X; cube.X <= m_blockMax.X; cube.X++)
{
for (cube.Y = m_blockMin.Y; cube.Y <= m_blockMax.Y; cube.Y++)
{
for (cube.Z = m_blockMin.Z; cube.Z <= m_blockMax.Z; cube.Z++)
{
m_lookup.Add(pos + cube, pos);
}
}
}
}
public void GetConnectedBlocks(Vector3I minI, Vector3I maxI, Dictionary<Vector3I, ConnectivityResult> outOverlappedCubeBlocks)
{
Vector3I cube;
for (cube.X = minI.X; cube.X <= maxI.X; cube.X++)
{
for (cube.Y = minI.Y; cube.Y <= maxI.Y; cube.Y++)
{
for (cube.Z = minI.Z; cube.Z <= maxI.Z; cube.Z++)
{
Vector3I pos;
if (m_lookup.TryGetValue(cube, out pos) && !outOverlappedCubeBlocks.ContainsKey(pos))
{
outOverlappedCubeBlocks.Add(pos, new ConnectivityResult() { Definition = m_definition, FatBlock = null, Position = pos, Orientation = m_orientation });
}
}
}
}
}
}
// Empty function, but forces static variable preload during game load
public static void Preload() { }
private const double GRID_PLACING_AREA_FIX_VALUE = 0.11;
const string EXPORT_DIRECTORY = "ExportedModels";
const string SOURCE_DIRECTORY = "SourceModels";
private static List<MyObjectBuilder_CubeGrid[]> m_prefabs = new List<MyObjectBuilder_CubeGrid[]>();
private static List<MyEntity> m_tmpResultList = new List<MyEntity>();
private static List<MyVoxelBase> m_tmpVoxelList = new List<MyVoxelBase>();
static int materialID = 0;
static Vector2 tumbnailMultiplier = new Vector2();
private static float m_maxDimensionPreviousRow = 0.0f;
private static Vector3D m_newPositionForPlacedObject = new Vector3D(0, 0, 0);
private const int m_numRowsForPlacedObjects = 4;
public static bool ShowSenzorGizmos { get; set; }
public static bool ShowGravityGizmos { get; set; }
public static bool ShowCenterOfMass {get; set;}
public static bool ShowGridPivot { get; set; }
public static bool ShowAntennaGizmos { get; set; }
public static bool ShowStructuralIntegrity { get; set; }
private static List<MyLineSegmentOverlapResult<MyEntity>> m_lineOverlapList = new List<MyLineSegmentOverlapResult<MyEntity>>();
private static List<HkBodyCollision> m_physicsBoxQueryList = new List<HkBodyCollision>();
private static Dictionary<Vector3I, MySlimBlock> m_tmpBoneSet = new Dictionary<Vector3I, MySlimBlock>(Vector3I.Comparer);
private static MyDisconnectHelper m_disconnectHelper = new MyDisconnectHelper();
private static List<NeighborOffsetIndex> m_neighborOffsetIndices = new List<NeighborOffsetIndex>(26);
private static List<float> m_neighborDistances = new List<float>(26);
private static List<Vector3I> m_neighborOffsets = new List<Vector3I>(26);
private static MyRandom m_deformationRng = new MyRandom();
// Caching structures to avoid allocations in functions.
[ThreadStatic]
private static List<Vector3I> m_cacheRayCastCellsPerThread;
private static List<Vector3I> m_cacheRayCastCells { get { return MyUtils.Init(ref m_cacheRayCastCellsPerThread); } }
[ThreadStatic]
private static Dictionary<Vector3I, ConnectivityResult> m_cacheNeighborBlocksPerThread;
private static Dictionary<Vector3I, ConnectivityResult> m_cacheNeighborBlocks { get { return MyUtils.Init(ref m_cacheNeighborBlocksPerThread); } }
[ThreadStatic]
private static List<MyCubeBlockDefinition.MountPoint> m_cacheMountPointsAPerThread;
private static List<MyCubeBlockDefinition.MountPoint> m_cacheMountPointsA { get { return MyUtils.Init(ref m_cacheMountPointsAPerThread); } }
[ThreadStatic]
private static List<MyCubeBlockDefinition.MountPoint> m_cacheMountPointsBPerThread;
private static List<MyCubeBlockDefinition.MountPoint> m_cacheMountPointsB { get { return MyUtils.Init(ref m_cacheMountPointsBPerThread); } }
static private MyComponentList m_buildComponents = new MyComponentList();
[ThreadStatic]
private static List<MyPhysics.HitInfo> m_tmpHitListPerThread;
private static List<MyPhysics.HitInfo> m_tmpHitList { get { return MyUtils.Init(ref m_tmpHitListPerThread); } }
private static readonly HashSet<Vector3UByte> m_tmpAreaMountpointPass = new HashSet<Vector3UByte>();
private static AreaConnectivityTest m_areaOverlapTest = new AreaConnectivityTest();
[ThreadStatic]
private static List<Vector3I> m_tmpCubeNeighboursPerThread;
private static List<Vector3I> m_tmpCubeNeighbours { get { return MyUtils.Init(ref m_tmpCubeNeighboursPerThread); } }
private static readonly HashSet<Tuple<MySlimBlock, ushort?>> m_tmpBlocksInMultiBlock = new HashSet<Tuple<MySlimBlock, ushort?>>();
private static readonly List<MySlimBlock> m_tmpSlimBlocks = new List<MySlimBlock>();
[ThreadStatic]
private static List<int> m_tmpMultiBlockIndicesPerThread;
private static List<int> m_tmpMultiBlockIndices { get { return MyUtils.Init(ref m_tmpMultiBlockIndicesPerThread); } }
private static readonly Type m_gridSystemsType = ChooseGridSystemsType();
private static List<Tuple<Vector3I, ushort>> m_tmpRazeList = new List<Tuple<Vector3I, ushort>>();
private static readonly List<Vector3I> m_tmpLocations = new List<Vector3I>();
private static HkBoxShape m_lastQueryBox = new HkBoxShape(Vector3.One);
private static MatrixD m_lastQueryTransform;
private const double ROTATION_PRECISION = 0.001f;
public static void GetCubeParts(
MyCubeBlockDefinition block,
Vector3I inputPosition,
Matrix rotation,
float gridSize,
List<string> outModels,
List<MatrixD> outLocalMatrices,
List<Vector3> outLocalNormals,
List<Vector2> outPatternOffsets)
{
// CH:TODO: Is rotation argument really needed as a Matrix? It should suffice for it to be MyBlockOrientation
outModels.Clear();
outLocalMatrices.Clear();
outLocalNormals.Clear();
outPatternOffsets.Clear();
if (block.CubeDefinition == null)
return;
Base6Directions.Direction forward = Base6Directions.GetDirection(Vector3I.Round(rotation.Forward));
Base6Directions.Direction up = Base6Directions.GetDirection(Vector3I.Round(rotation.Up));
MyCubeGridDefinitions.GetTopologyUniqueOrientation(block.CubeDefinition.CubeTopology, new MyBlockOrientation(forward, up)).GetMatrix(out rotation);
MyTileDefinition[] tiles = MyCubeGridDefinitions.GetCubeTiles(block);
int count = tiles.Length;
int start = 0;
int avoidZeroMirrorOffset = 32768;
float epsilon = 0.01f;
for (int i = 0; i < count; i++)
{
var entry = tiles[start + i];
var localMatrix = (MatrixD)entry.LocalMatrix * rotation;
var localNormal = Vector3.Transform(entry.Normal, rotation.GetOrientation());
var position = inputPosition;
if(block.CubeDefinition.CubeTopology == MyCubeTopology.Slope2Base)
{
var addition = new Vector3I(Vector3.Sign(localNormal.MaxAbsComponent()));
position += addition;
}
string modelPath = block.CubeDefinition.Model[i];
Vector2I patternSize = block.CubeDefinition.PatternSize[i];
int scale = (int)MyModels.GetModelOnlyData(modelPath).PatternScale;
patternSize = new Vector2I(patternSize.X * scale, patternSize.Y * scale);
const float sinConst = 10;
int u = 0;
int v = 0;
float yAxis = Vector3.Dot(Vector3.UnitY, localNormal);
float xAxis = Vector3.Dot(Vector3.UnitX, localNormal);
float zAxis = Vector3.Dot(Vector3.UnitZ, localNormal);
if (MyUtils.IsZero(Math.Abs(yAxis) - 1, epsilon))
{
int patternRow = (position.X + avoidZeroMirrorOffset) / patternSize.Y;
int offset = (MyMath.Mod(patternRow + (int)(patternRow * Math.Sin(patternRow * sinConst)), patternSize.X));
u = MyMath.Mod(position.Z + position.Y + offset + avoidZeroMirrorOffset, patternSize.X);
v = MyMath.Mod(position.X + avoidZeroMirrorOffset, patternSize.Y);
if (Math.Sign(yAxis) == 1)
v = (patternSize.Y - 1) - v;
}
else if (MyUtils.IsZero(Math.Abs(xAxis) - 1, epsilon))
{
int patternRow = (position.Z + avoidZeroMirrorOffset) / patternSize.Y;
int offset = (MyMath.Mod(patternRow + (int)(patternRow * Math.Sin(patternRow * sinConst)), patternSize.X));
u = MyMath.Mod(position.X + position.Y + offset + avoidZeroMirrorOffset, patternSize.X);
v = MyMath.Mod(position.Z + avoidZeroMirrorOffset, patternSize.Y);
if (Math.Sign(xAxis) == 1)
v = (patternSize.Y - 1) - v;
}
else if (MyUtils.IsZero(Math.Abs(zAxis) - 1, epsilon))
{
int patternRow = (position.Y + avoidZeroMirrorOffset) / patternSize.Y;
int offset = (MyMath.Mod(patternRow + (int)(patternRow * Math.Sin(patternRow * sinConst)), patternSize.X));
u = MyMath.Mod(position.X + offset + avoidZeroMirrorOffset, patternSize.X);
v = MyMath.Mod(position.Y + avoidZeroMirrorOffset, patternSize.Y);
if (Math.Sign(zAxis) == 1)
u = (patternSize.X - 1) - u;
}
else if (MyUtils.IsZero(xAxis, epsilon))
{ //slope in YZ
u = MyMath.Mod(position.X + avoidZeroMirrorOffset, patternSize.X);
v = MyMath.Mod(position.Z + avoidZeroMirrorOffset, patternSize.Y);
if (Math.Sign(zAxis) == -1)
{
if (Math.Sign(yAxis) == 1)
{
//v = (patternSize.Y - 1) - v;
//u = (patternSize.X - 1) - u;
}
else
{
// u = (patternSize.X - 1) - u;
v = (patternSize.Y - 1) - v;
}
}
else
{
if (Math.Sign(yAxis) == -1)
{
//u = (patternSize.X - 1) - u;
v = (patternSize.Y - 1) - v;
}
else
{
//u = (patternSize.X - 1) - u;
// v = (patternSize.Y - 1) - v;
}
}
}
else if (MyUtils.IsZero(zAxis, epsilon))
{ //slope in XY
u = MyMath.Mod(position.Z + avoidZeroMirrorOffset, patternSize.X);
v = MyMath.Mod(position.Y + avoidZeroMirrorOffset, patternSize.Y);
if (Math.Sign(xAxis) == 1)
{
if (Math.Sign(yAxis) == 1)
{
//u = (patternSize.X - 1) - u;
//v = (patternSize.Y - 1) - v;
}
else
{
u = (patternSize.X - 1) - u;
v = (patternSize.Y - 1) - v;
}
}
else
{
if (Math.Sign(yAxis) == 1)
{
u = (patternSize.X - 1) - u;
// v = (patternSize.Y - 1) - v;
}
else
{
// u = (patternSize.X - 1) - u;
v = (patternSize.Y - 1) - v;
}
}
}
else if (MyUtils.IsZero(yAxis, epsilon))
{ //slope in XZ
u = MyMath.Mod(position.Y + avoidZeroMirrorOffset, patternSize.X);
v = MyMath.Mod(position.Z + avoidZeroMirrorOffset, patternSize.Y);
if (Math.Sign(zAxis) == -1)
{
if (Math.Sign(xAxis) == 1)
{
//u = (patternSize.X - 1) - u;
v = (patternSize.Y - 1) - v;
}
else
{
u = (patternSize.X - 1) - u;
v = (patternSize.Y - 1) - v;
}
}
else
{
if (Math.Sign(xAxis) == 1)
{
u = (patternSize.X - 1) - u;
//v = (patternSize.Y - 1) - v;
}
else
{
//u = (patternSize.X - 1) - u;
// v = (patternSize.Y - 1) - v;
}
}
}
localMatrix.Translation = inputPosition * gridSize;
if (entry.DontOffsetTexture)
{
u = 0;
v = 0;
}
Vector2 uv = new Vector2(u, v);
Vector2 patternOffset = uv / patternSize;
outPatternOffsets.Add(patternOffset);
outModels.Add(modelPath);
outLocalMatrices.Add(localMatrix);
outLocalNormals.Add(localNormal);
}
}
public static void CheckAreaConnectivity(MyCubeGrid grid, ref MyBlockBuildArea area, List<Vector3UByte> validOffsets, HashSet<Vector3UByte> resultFailList)
{
try
{
var definition = MyDefinitionManager.Static.GetCubeBlockDefinition(area.DefinitionId) as MyCubeBlockDefinition;
if (definition == null)
{
Debug.Fail("Block definition not found");
return;
}
Quaternion orientation = Base6Directions.GetOrientation(area.OrientationForward, area.OrientationUp);
Vector3I stepDir = area.StepDelta;
var mountPoints = definition.GetBuildProgressModelMountPoints(MyComponentStack.NewBlockIntegrity);
// Step 1: Add blocks which are connected directly to existing grid
for (int i = validOffsets.Count - 1; i >= 0; i--)
{
Vector3I center = area.PosInGrid + validOffsets[i] * stepDir;
if (MyCubeGrid.CheckConnectivity(grid, definition, mountPoints, ref orientation, ref center))
{
m_tmpAreaMountpointPass.Add(validOffsets[i]);
validOffsets.RemoveAtFast(i);
}
}
// Step 2: Add remaining blocks which are connected to any newly added block
m_areaOverlapTest.Initialize(ref area, definition);
foreach (var block in m_tmpAreaMountpointPass) m_areaOverlapTest.AddBlock(block);
int prevCount = int.MaxValue;
while (validOffsets.Count > 0 && validOffsets.Count < prevCount)
{
prevCount = validOffsets.Count;
for (int i = validOffsets.Count - 1; i >= 0; i--)
{
Vector3I center = area.PosInGrid + validOffsets[i] * stepDir;
if (MyCubeGrid.CheckConnectivity(m_areaOverlapTest, definition, mountPoints, ref orientation, ref center))
{
m_tmpAreaMountpointPass.Add(validOffsets[i]);
m_areaOverlapTest.AddBlock(validOffsets[i]);
validOffsets.RemoveAtFast(i);
}
}
}
// Step 3: Remaining blocks failed
foreach (var item in validOffsets)
{
resultFailList.Add(item);
}
validOffsets.Clear();
validOffsets.AddHashset(m_tmpAreaMountpointPass);
}
finally
{
m_tmpAreaMountpointPass.Clear();
}
}
public static bool CheckMergeConnectivity(MyCubeGrid hitGrid, MyCubeGrid gridToMerge, Vector3I gridOffset)
{
// CH: Beware, this funtion seems horribly inefficient! Think twice before using it (e.g. don't use it in a 10000x loop) or optimize it :-)
MatrixI mergeTransform = hitGrid.CalculateMergeTransform(gridToMerge, gridOffset);
Quaternion mergeOri;
mergeTransform.GetBlockOrientation().GetQuaternion(out mergeOri);
foreach (var block in gridToMerge.GetBlocks())
{
Quaternion ori;
Vector3I pos = Vector3I.Transform(block.Position, mergeTransform);
block.Orientation.GetQuaternion(out ori);
//Matrix mergeGridMatrix = Matrix.CreateFromQuaternion(mergeOri);
//Matrix oriMatrix = Matrix.CreateFromQuaternion(ori);
//Matrix result = oriMatrix * mergeGridMatrix;
//Quaternion quatFromMatrix = Quaternion.CreateFromRotationMatrix(result);
// Seems that quaternion multiplication is reversed to matrix multiplication!
ori = mergeOri * ori;
var mountPoints = block.BlockDefinition.GetBuildProgressModelMountPoints(block.BuildLevelRatio);
if (MyCubeGrid.CheckConnectivity(hitGrid, block.BlockDefinition, mountPoints, ref ori, ref pos))
return true;
}
return false;
}
/// <summary>
/// Performs check whether cube block given by its definition, rotation and position is connected to some other
/// block in a given grid.
/// </summary>
/// <param name="grid">Grid in which the check is performed.</param>
/// <param name="rotation">Rotation of the cube block within grid.</param>
/// <param name="position">Position of the cube block within grid.</param>
/// <returns>True when there is a connectable neighbor connected by a mount point, otherwise false.</returns>
public static bool CheckConnectivity(IMyGridConnectivityTest grid, MyCubeBlockDefinition def, MyCubeBlockDefinition.MountPoint[] mountPoints, ref Quaternion rotation, ref Vector3I position)
{
ProfilerShort.Begin("MyCubeBuilder.CheckMountPoints");
try
{
if (mountPoints == null)
return false;
var center = def.Center;
var size = def.Size;
Vector3I rotatedSize;
Vector3I rotatedCenter;
Vector3I.Transform(ref center, ref rotation, out rotatedCenter);
Vector3I.Transform(ref size, ref rotation, out rotatedSize);
for (int i = 0; i < mountPoints.Length; ++i)
{
var thisMountPoint = mountPoints[i];
Vector3 centeredStart = thisMountPoint.Start - center;
Vector3 centeredEnd = thisMountPoint.End - center;
if (MyFakes.ENABLE_TEST_BLOCK_CONNECTIVITY_CHECK)
{
// This code is used to avoid mixed start, end values, overlapped values on sides. So as result we need precise neighbour(s). Not neighbours touched on edges.
// Start and end sometimes have exchanged values
Vector3 start, end;
Vector3.MinMax(thisMountPoint.Start, thisMountPoint.End, out start, out end);
// Clamp only overlapped values on sides not thickness of aabb of mount point
Vector3I clampMask = Vector3I.One - Vector3I.Abs(thisMountPoint.Normal);
Vector3I invClampMask = Vector3I.One - clampMask;
Vector3 clampedStart = invClampMask * start + Vector3.Clamp(start, Vector3.Zero, size) * clampMask + 0.001f * clampMask;
Vector3 clampedEnd = invClampMask * end + Vector3.Clamp(end, Vector3.Zero, size) * clampMask - 0.001f * clampMask;
centeredStart = clampedStart - center;
centeredEnd = clampedEnd - center;
}
var centeredStartI = Vector3I.Floor(centeredStart);
var centeredEndI = Vector3I.Floor(centeredEnd);
Vector3 rotatedStart, rotatedEnd;
Vector3.Transform(ref centeredStart, ref rotation, out rotatedStart);
Vector3.Transform(ref centeredEnd, ref rotation, out rotatedEnd);
Vector3I rotatedStartICorrect, rotatedEndICorrect;
Vector3I.Transform(ref centeredStartI, ref rotation, out rotatedStartICorrect);
Vector3I.Transform(ref centeredEndI, ref rotation, out rotatedEndICorrect);
// Correction of rotation. Normally we perform computations in integers and so these are not needed, but when
// transforming floats, we can end up rotating eg. 0.5f to -0.5f which, after Floor operation, would be like rotation of 0 to -1 (ie. wrong).
// By rotating both floored and floating point versions, I can find out what change occured and handle it accordingly.
var rotatedStartI = Vector3I.Floor(rotatedStart);
var rotatedEndI = Vector3I.Floor(rotatedEnd);
var correctionStart = rotatedStartICorrect - rotatedStartI;
var correctionEnd = rotatedEndICorrect - rotatedEndI;
rotatedStart += correctionStart;
rotatedEnd += correctionEnd;
Vector3 gridPosStart = position + rotatedStart;
Vector3 gridPosEnd = position + rotatedEnd;
m_cacheNeighborBlocks.Clear();
Vector3 currentMin, currentMax;
Vector3.MinMax(gridPosStart, gridPosEnd, out currentMin, out currentMax);
var minI = Vector3I.Floor(currentMin);
var maxI = Vector3I.Floor(currentMax);
grid.GetConnectedBlocks(minI, maxI, m_cacheNeighborBlocks);
//MyCubeBuilder.Static.GetOverlappedGizmoBlocks(minI, maxI, m_cacheNeighborBlocks);
if (m_cacheNeighborBlocks.Count == 0)
continue;
Vector3I transformedNormal;
Vector3I.Transform(ref thisMountPoint.Normal, ref rotation, out transformedNormal);
Debug.Assert(transformedNormal.RectangularLength() == 1);
minI -= transformedNormal;
maxI -= transformedNormal;
Vector3I transformedNormalNegative = -transformedNormal;
foreach (var neighbor in m_cacheNeighborBlocks.Values)
{
if (neighbor.Position == position)
{
if (MyFakes.ENABLE_COMPOUND_BLOCKS)
{
// If this neighbor does not want to connect, check another one
if (neighbor.FatBlock != null && neighbor.FatBlock.CheckConnectionAllowed && !neighbor.FatBlock.ConnectionAllowed(ref minI, ref maxI, ref transformedNormalNegative, def))
continue;
if (neighbor.FatBlock is MyCompoundCubeBlock)
{
MyCompoundCubeBlock compoundBlock = neighbor.FatBlock as MyCompoundCubeBlock;
foreach (var blockInCompound in compoundBlock.GetBlocks())
{
var blockInCompoundMountPoints = blockInCompound.BlockDefinition.GetBuildProgressModelMountPoints(blockInCompound.BuildLevelRatio);
if (CheckNeighborMountPointsForCompound(currentMin, currentMax, thisMountPoint, ref transformedNormal, def,
neighbor.Position, blockInCompound.BlockDefinition, blockInCompoundMountPoints, blockInCompound.Orientation, m_cacheMountPointsA))
return true;
}
}
else
{
continue;
}
}
else
{
continue;
}
}
else
{
// If this neighbor does not want to connect, check another one
if (neighbor.FatBlock != null && neighbor.FatBlock.CheckConnectionAllowed && !neighbor.FatBlock.ConnectionAllowed(ref minI, ref maxI, ref transformedNormalNegative, def))
continue;
if (neighbor.FatBlock is MyCompoundCubeBlock)
{
MyCompoundCubeBlock compoundBlock = neighbor.FatBlock as MyCompoundCubeBlock;
foreach (var blockInCompound in compoundBlock.GetBlocks())
{
var blockInCompoundMountPoints = blockInCompound.BlockDefinition.GetBuildProgressModelMountPoints(blockInCompound.BuildLevelRatio);
if (CheckNeighborMountPoints(currentMin, currentMax, thisMountPoint, ref transformedNormal, def,
neighbor.Position, blockInCompound.BlockDefinition, blockInCompoundMountPoints, blockInCompound.Orientation, m_cacheMountPointsA))
return true;
}
}
else
{
var buildLevelRatio = 1.0f;
if(neighbor.FatBlock != null && neighbor.FatBlock.SlimBlock != null)
buildLevelRatio = neighbor.FatBlock.SlimBlock.BuildLevelRatio;
var neighborMountPoints = neighbor.Definition.GetBuildProgressModelMountPoints(buildLevelRatio);
if (CheckNeighborMountPoints(currentMin, currentMax, thisMountPoint, ref transformedNormal, def,
neighbor.Position, neighbor.Definition, neighborMountPoints, neighbor.Orientation, m_cacheMountPointsA))
return true;
}
}
}
}
return false;
}
finally
{
m_cacheNeighborBlocks.Clear();
ProfilerShort.End();
}
}
/// <summary>
/// Performs check whether small cube block given by its definition, rotation can be connected to large grid.
/// Function checks whether a mount point on placed block exists in opposite direction than addNomal.
/// </summary>
/// <param name="grid">Grid in which the check is performed.</param>
/// <param name="def">Definition of small cube block for checking.</param>
/// <param name="rotation">Rotation of the small cube block.</param>
/// <param name="addNormal">Grid hit normal.</param>
/// <returns>True when small block can be connected, otherwise false.</returns>
public static bool CheckConnectivitySmallBlockToLargeGrid(MyCubeGrid grid, MyCubeBlockDefinition def, ref Quaternion rotation, ref Vector3I addNormal)
{
Debug.Assert(grid.GridSizeEnum == MyCubeSize.Large);
Debug.Assert(def.CubeSize == MyCubeSize.Small);
ProfilerShort.Begin("MyCubeBuilder.CheckMountPoints");
try
{
var mountPoints = def.MountPoints;
if (mountPoints == null)
return false;
for (int i = 0; i < mountPoints.Length; ++i)
{
var thisMountPoint = mountPoints[i];
Vector3I transformedNormal;
Vector3I.Transform(ref thisMountPoint.Normal, ref rotation, out transformedNormal);
Debug.Assert(transformedNormal.RectangularLength() == 1);
if (addNormal == -transformedNormal)
return true;
}
return false;
}
finally
{
m_cacheNeighborBlocks.Clear();
ProfilerShort.End();
}
}
public static bool CheckNeighborMountPoints(
Vector3 currentMin, Vector3 currentMax, MyCubeBlockDefinition.MountPoint thisMountPoint, ref Vector3I thisMountPointTransformedNormal, MyCubeBlockDefinition thisDefinition,
Vector3I neighborPosition, MyCubeBlockDefinition neighborDefinition, MyCubeBlockDefinition.MountPoint[] neighborMountPoints, MyBlockOrientation neighborOrientation,
List<MyCubeBlockDefinition.MountPoint> otherMountPoints)
{
if (!thisMountPoint.Enabled)
return false;
var currentBox = new BoundingBox(currentMin - neighborPosition, currentMax - neighborPosition);
TransformMountPoints(otherMountPoints, neighborDefinition, neighborMountPoints, ref neighborOrientation);
foreach (var otherMountPoint in otherMountPoints)
{
// Skip mount points which exclude themselves (are not allowed to touch).
if ((((thisMountPoint.ExclusionMask & otherMountPoint.PropertiesMask) != 0 ||
(thisMountPoint.PropertiesMask & otherMountPoint.ExclusionMask) != 0) &&
thisDefinition.Id != neighborDefinition.Id) || !otherMountPoint.Enabled)
continue;
if (MyFakes.ENABLE_TEST_BLOCK_CONNECTIVITY_CHECK && (thisMountPointTransformedNormal + otherMountPoint.Normal != Vector3I.Zero))
continue;
var otherBox = new BoundingBox(Vector3.Min(otherMountPoint.Start, otherMountPoint.End), Vector3.Max(otherMountPoint.Start, otherMountPoint.End));
if (currentBox.Intersects(otherBox))
return true;
}
return false;
}
public static bool CheckNeighborMountPointsForCompound(
Vector3 currentMin, Vector3 currentMax, MyCubeBlockDefinition.MountPoint thisMountPoint, ref Vector3I thisMountPointTransformedNormal, MyCubeBlockDefinition thisDefinition,
Vector3I neighborPosition, MyCubeBlockDefinition neighborDefinition, MyCubeBlockDefinition.MountPoint[] neighborMountPoints, MyBlockOrientation neighborOrientation,
List<MyCubeBlockDefinition.MountPoint> otherMountPoints)
{
if (!thisMountPoint.Enabled)
return false;
var currentBox = new BoundingBox(currentMin - neighborPosition, currentMax - neighborPosition);
TransformMountPoints(otherMountPoints, neighborDefinition, neighborMountPoints, ref neighborOrientation);
foreach (var otherMountPoint in otherMountPoints)
{
// Skip mount points which exclude themselves (are not allowed to touch).
if ((((thisMountPoint.ExclusionMask & otherMountPoint.PropertiesMask) != 0 ||
(thisMountPoint.PropertiesMask & otherMountPoint.ExclusionMask) != 0) &&
thisDefinition.Id != neighborDefinition.Id) || !otherMountPoint.Enabled)
continue;
// Check normals on compound side with the same direction (we are in the same block)
if (MyFakes.ENABLE_TEST_BLOCK_CONNECTIVITY_CHECK && (thisMountPointTransformedNormal - otherMountPoint.Normal != Vector3I.Zero))
continue;
var otherBox = new BoundingBox(Vector3.Min(otherMountPoint.Start, otherMountPoint.End), Vector3.Max(otherMountPoint.Start, otherMountPoint.End));
if (currentBox.Intersects(otherBox))
return true;
}
return false;
}
/// <summary>
/// Checkes whether blocks A and B have matching mount point on one of their sides. Each block is given by its
/// definition, rotation and position in grid. Position has to be relative to same center. Also, normal relative to block A specifies
/// wall which is used for checking.
/// </summary>
public static bool CheckMountPointsForSide(MyCubeBlockDefinition defA, MyCubeBlockDefinition.MountPoint[] mountPointsA, ref MyBlockOrientation orientationA, ref Vector3I positionA, ref Vector3I normalA,
MyCubeBlockDefinition defB, MyCubeBlockDefinition.MountPoint[] mountPointsB, ref MyBlockOrientation orientationB, ref Vector3I positionB)
{
TransformMountPoints(m_cacheMountPointsA, defA, mountPointsA, ref orientationA);
TransformMountPoints(m_cacheMountPointsB, defB, mountPointsB, ref orientationB);
return CheckMountPointsForSide(m_cacheMountPointsA, ref orientationA, ref positionA, defA.Id, ref normalA, m_cacheMountPointsB, ref orientationB, ref positionB, defB.Id);
}
/// <summary>
/// Checkes whether blocks A and B have matching mount point on one of their sides. Each block is given by its
/// definition, rotation and position in grid. Position has to be relative to same center. Also, normal relative to block A specifies
/// wall which is used for checking.
/// </summary>
public static bool CheckMountPointsForSide(List<MyCubeBlockDefinition.MountPoint> transormedA, ref MyBlockOrientation orientationA, ref Vector3I positionA, MyDefinitionId idA, ref Vector3I normalA,
List<MyCubeBlockDefinition.MountPoint> transormedB, ref MyBlockOrientation orientationB, ref Vector3I positionB, MyDefinitionId idB)
{
var offsetAB = positionB - positionA;
var normalB = -normalA;
for (int i = 0; i < transormedA.Count; ++i)
{
if(!transormedA[i].Enabled)
continue;
var mountPointA = transormedA[i];
if (mountPointA.Normal != normalA)
continue;
var minA = Vector3.Min(mountPointA.Start, mountPointA.End);
var maxA = Vector3.Max(mountPointA.Start, mountPointA.End);
minA -= offsetAB;
maxA -= offsetAB;
var bboxA = new BoundingBox(minA, maxA);
for (int j = 0; j < transormedB.Count; ++j)
{
if(!transormedB[j].Enabled)
continue;
var mountPointB = transormedB[j];
if (mountPointB.Normal != normalB)
continue;
// Skip mount points which exclude themselves (are not allowed to touch).
if (((mountPointA.ExclusionMask & mountPointB.PropertiesMask) != 0 || (mountPointA.PropertiesMask & mountPointB.ExclusionMask) != 0) &&
idA != idB)
continue;
var bboxB = new BoundingBox(Vector3.Min(mountPointB.Start, mountPointB.End), Vector3.Max(mountPointB.Start, mountPointB.End));
if (bboxA.Intersects(bboxB))
return true;
}
}
return false;
}
#region model export
private static void ConvertNextGrid(bool placeOnly)
{
MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
timeoutInMiliseconds: 1000,
styleEnum: MyMessageBoxStyleEnum.Info,
buttonType: MyMessageBoxButtonsType.NONE_TIMEOUT,
messageText: new StringBuilder(MyTexts.GetString(MyCommonTexts.ConvertingObjs)),
callback: (result) =>
{
ConvertNextPrefab(m_prefabs, placeOnly);
}));
}
private static void ConvertNextPrefab(List<MyObjectBuilder_CubeGrid[]> prefabs, bool placeOnly)
{
if (prefabs.Count > 0)
{
MyObjectBuilder_CubeGrid[] currentPrefab = prefabs[0];
int modelNumber = prefabs.Count;
prefabs.RemoveAt(0);
if (placeOnly)
{
BoundingSphere boundingSphere = GetBoundingSphereForGrids(currentPrefab);
float maxSize = boundingSphere.Radius;
m_maxDimensionPreviousRow = VRageMath.MathHelper.Max(maxSize, m_maxDimensionPreviousRow);
if (prefabs.Count % m_numRowsForPlacedObjects != 0)
{
m_newPositionForPlacedObject.X += (2.0f * maxSize + 10.0f);
}
else
{
m_newPositionForPlacedObject.X = -(2.0f * maxSize + 10.0f);
m_newPositionForPlacedObject.Z -= (2.0f * m_maxDimensionPreviousRow + 30.0f);
m_maxDimensionPreviousRow = 0.0f;
}
PlacePrefabToWorld(currentPrefab, MySector.MainCamera.Position + m_newPositionForPlacedObject);
ConvertNextPrefab(m_prefabs, placeOnly);
}
else
{
List<MyCubeGrid> prefabGrids = new List<MyCubeGrid>();
foreach (var currentGrid in currentPrefab)
{
prefabGrids.Add(MyEntities.CreateFromObjectBuilderAndAdd(currentGrid) as MyCubeGrid);
}
ExportToObjFile(prefabGrids, true,false);
foreach (var grid in prefabGrids)
{
grid.Close();
}
}
}
else
{
MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
styleEnum: MyMessageBoxStyleEnum.Info,
buttonType: MyMessageBoxButtonsType.OK,
messageText: new StringBuilder(MyTexts.GetString(MyCommonTexts.ConvertToObjDone))));
}
}
private static BoundingSphere GetBoundingSphereForGrids(MyObjectBuilder_CubeGrid[] currentPrefab)
{
BoundingSphere boundingSphere = new BoundingSphere(Vector3.Zero, float.MinValue);
foreach (var gridBuilder in currentPrefab)
{
BoundingSphere localSphere = gridBuilder.CalculateBoundingSphere();
MatrixD gridTransform = gridBuilder.PositionAndOrientation.HasValue ? gridBuilder.PositionAndOrientation.Value.GetMatrix() : MatrixD.Identity;
boundingSphere.Include(localSphere.Transform(gridTransform));
}
return boundingSphere;
}
public static void StartConverting(bool placeOnly)
{
string folder = Path.Combine(MyFileSystem.UserDataPath, SOURCE_DIRECTORY);
if (Directory.Exists(folder) == false)
{
return;
}
m_prefabs.Clear();
foreach (var zipFile in Directory.GetFiles(folder, "*.zip"))
{
foreach (var file in MyFileSystem.GetFiles(zipFile, "*.sbc", VRage.FileSystem.MySearchOption.AllDirectories))
{
if (MyFileSystem.FileExists(file))
{
MyObjectBuilder_Definitions loadedPrefab = null;
MyObjectBuilderSerializer.DeserializeXML(file, out loadedPrefab);
if (loadedPrefab.Prefabs[0].CubeGrids != null)
{
m_prefabs.Add(loadedPrefab.Prefabs[0].CubeGrids);
}
}
}
}
ConvertNextPrefab(m_prefabs, placeOnly);
}
public static void ConvertPrefabsToObjs()
{
MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
timeoutInMiliseconds: 1000,
styleEnum: MyMessageBoxStyleEnum.Info,
buttonType: MyMessageBoxButtonsType.NONE_TIMEOUT,
messageText: new StringBuilder(MyTexts.GetString(MyCommonTexts.ConvertingObjs)),
callback: (result) =>
{
StartConverting(false);
}));
}
public static void PackFiles(string path,string objectName)
{
if (Directory.Exists(path) == false)
{
MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
styleEnum: MyMessageBoxStyleEnum.Error,
buttonType: MyMessageBoxButtonsType.OK,
messageText: new StringBuilder(string.Format(MyTexts.GetString(MyCommonTexts.ExportToObjFailed), path))));
return;
}
using (var arc = VRage.Compression.MyZipArchive.OpenOnFile(Path.Combine(path, objectName + "_objFiles.zip"), FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
PackFilesToDirectory(path, "*.png", arc);
PackFilesToDirectory(path, "*.obj", arc);
PackFilesToDirectory(path, "*.mtl", arc);
}
using (var arc = VRage.Compression.MyZipArchive.OpenOnFile(Path.Combine(path, objectName+ ".zip"), FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
PackFilesToDirectory(path, objectName+".png", arc);
PackFilesToDirectory(path, "*.sbc", arc);
}
RemoveFilesFromDirectory(path,"*.png");
RemoveFilesFromDirectory(path, "*.sbc");
RemoveFilesFromDirectory(path, "*.obj");
RemoveFilesFromDirectory(path, "*.mtl");
}
private static void RemoveFilesFromDirectory(string path,string fileType)
{
string[] filePaths = Directory.GetFiles(path, fileType);
foreach (string filePath in filePaths)
{
File.Delete(filePath);
}
}
private static void PackFilesToDirectory(string path, string searchString , VRage.Compression.MyZipArchive arc)
{
int len = path.Length + 1;
foreach (var file in Directory.GetFiles(path, searchString, SearchOption.AllDirectories))
{
using (var inStream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var outStream = arc.AddFile(file.Substring(len), VRage.Compression.CompressionMethodEnum.Deflated, VRage.Compression.DeflateOptionEnum.Maximum).GetStream(FileMode.Open, FileAccess.Write))
{
inStream.CopyTo(outStream, 0x1000);
}
}
}
}
public static void ExportObject(MyCubeGrid baseGrid, bool convertModelsFromSBC, bool exportObjAndSBC = false)
{
MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
timeoutInMiliseconds: 1000,
styleEnum: MyMessageBoxStyleEnum.Info,
buttonType: MyMessageBoxButtonsType.NONE_TIMEOUT,
messageText: new StringBuilder(MyTexts.GetString(MyCommonTexts.ExportingToObj)),
callback: (result) =>
{
List<MyCubeGrid> gridsToExport = new List<MyCubeGrid>();
var gridGroup = MyCubeGridGroups.Static.Logical.GetGroup(baseGrid);
foreach (var node in gridGroup.Nodes)
{
gridsToExport.Add(node.NodeData);
}
ExportToObjFile(gridsToExport, convertModelsFromSBC, exportObjAndSBC);
}));
}
private static void ExportToObjFile(List<MyCubeGrid> baseGrids, bool convertModelsFromSBC, bool exportObjAndSBC)
{
materialID = 0;