-
Notifications
You must be signed in to change notification settings - Fork 0
/
Saturine Ship AI.cs
2229 lines (1989 loc) · 59.9 KB
/
Saturine Ship AI.cs
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
/*
* Ship AI System
* Built by mlq1616
* https://github.com/mlq1819
*/
const string ProgramName = "Saturine Ship AI";
Color DefaultTextColor=new Color(197,137,255,255);
Color DefaultBackgroundColor=new Color(44,0,88,255);
// Runtime Logic and Methods
public void Main(string argument,UpdateType updateSource){
UpdateProgramInfo();
Write("Connected to "+Ships.Count+" Ships");
int updateFrequency=100;
for(int i=0;i<Ships.Count;i++){
MyShip ship=Ships[i];
ship.RunSystemUpdate(SecondsSinceLastUpdate);
if(i==CurrentShip){
bool runMe=true;
switch(LastUpdate){
case UpdateFrequency.Update10:
runMe=ship.UpdateFrequency<=10||((ShipCycle*10)%ship.UpdateFrequency==0);
break;
case UpdateFrequency.Update1:
runMe=ship.UpdateFrequency<=1||((ShipCycle)%ship.UpdateFrequency==0);
break;
}
if(runMe){
if(Ships.Count==1)
Write("Performing Operations for:\n"+ship.Grid.CustomName);
else if(i==0||!ship.Grid.CustomName.Equals(Ships[0].Grid.CustomName))
Write("Performing Operations for "+(i+1).ToString()+"/"+Ships.Count+":\n"+ship.Grid.CustomName);
else
Write("Performing Operations for "+(i+1).ToString()+"/"+Ships.Count);
try{
ship.RunSystemOperations();
}
catch(Exception e){
Write("Encountered error with "+ship.Grid.CustomName);
throw e;
}
}
else
CurrentShip++;
}
updateFrequency=Math.Min(updateFrequency,ship.UpdateFrequency);
Write(ship.Status);
}
if(++CurrentShip>=Ships.Count){
ShipCycle=(ShipCycle%long.MaxValue)+1;
CurrentShip=0;
switch(updateFrequency){
case 1:
Runtime.UpdateFrequency=UpdateFrequency.Update1;
break;
case 10:
Runtime.UpdateFrequency=UpdateFrequency.Update10;
break;
default:
Runtime.UpdateFrequency=UpdateFrequency.Update100;
break;
}
LastUpdate=Runtime.UpdateFrequency;
}
else
Runtime.UpdateFrequency=UpdateFrequency.Update1;
}
UpdateFrequency LastUpdate=UpdateFrequency.Update1;
bool TryAddNewShip(IMyShipController controller){
if(controller==null)
return false;
foreach(MyShip ship in Ships){
if(ship.Grid.IsSameConstructAs(controller.CubeGrid))
return false;
}
var altControllers=new List<IMyShipController>();
if(!controller.IsMainCockpit)
altControllers=CollectionMethods<IMyShipController>.AllByGrid(controller.CubeGrid);
try{
MyShip newShip=new MyShip(controller,altControllers);
if(newShip!=null)
Ships.Add(newShip);
if(newShip!=null){
MyShip.ShipCount++;
}
return newShip!=null;
}
catch{
return false;
}
}
int CurrentShip=0;
// Initialization and Object Definitions
public Program(){
Write("Beginning initialization.");
Prog.P=this;
Me.CustomName=(ProgramName+" Programmable block").Trim();
for(int i=0;i<Me.SurfaceCount;i++){
Me.GetSurface(i).FontColor=DefaultTextColor;
Me.GetSurface(i).BackgroundColor=DefaultBackgroundColor;
Me.GetSurface(i).Alignment=TextAlignment.CENTER;
Me.GetSurface(i).ContentType=ContentType.TEXT_AND_IMAGE;
Me.GetSurface(i).Font="Monospace";
Me.GetSurface(i).WriteText("",false);
}
Me.GetSurface(0).FontSize=0.75f;
Me.GetSurface(1).FontSize=1.5f;
Me.GetSurface(1).TextPadding=30.0f;
MyShip.WriteFull=Write;
// Initialize runtime objects
Write("Initializing objects...");
Ships=new List<MyShip>();
IMyShipController mainController=CollectionMethods<IMyShipController>.ByGrid(Me.CubeGrid,CollectionMethods<IMyShipController>.AllByName("Main"));
if(mainController==null){
Write("Failed to retrieve main controller");
}
if(TryAddNewShip(mainController)){
Write("Added Main Ship\n"+mainController.CustomName);
}
List<IMyShipController> mainControllers=CollectionMethods<IMyShipController>.AllByName("Main",CollectionMethods<IMyShipController>.AllBlocks);
foreach(IMyShipController newController in mainControllers){
if(TryAddNewShip(newController))
Write("Added New Ship\n"+newController.CustomName);
}
// Load runtime variables from CustomData
Write("Setting variables...");
string storageMode="";
string[] storageArgs=Me.CustomData.Trim().Split('\n');
foreach(string line in storageArgs){
switch(line){
case "GlobalSpeedLimit":
storageMode=line;
break;
default:
switch(storageMode){
case "GlobalSpeedLimit":
var globalSpeedLimit=MyShip.GlobalSpeedLimit;
if(float.TryParse(line,out globalSpeedLimit))
MyShip.GlobalSpeedLimit=globalSpeedLimit;
break;
}
break;
}
}
// Load data from Storage
Write("Loading data...");
storageMode="";
storageArgs=this.Storage.Trim().Split('\n');
foreach(string line in storageArgs){
switch(line){
case "SampleData":
storageMode=line;
break;
default:
switch(storageMode){
case "SampleData":
// Load Data from line
break;
}
break;
}
}
Runtime.UpdateFrequency=UpdateFrequency.Once;
Write("Completed initialization!");
}
List<MyShip> Ships;
public class MyShip{
public static List<List<MyEntity>> AllEntities;
public static Action<string,bool,bool> WriteFull;
public static void Write(string text){
WriteFull(text,true,true);
}
public static int ShipCount=0;
public static float GlobalSpeedLimit=100;
public string Status;
public int UpdateFrequency=1;
public IMyShipController Controller;
public List<IMyShipController> AltControllers;
public IMyGyro Gyroscope;
List<IMyGyro> AllGyroscopes;
public List<IMyParachute> Parachutes;
public List<IMyLandingGear> LandingGear;
public List<MyAirlock> Airlocks;
public IMyShipConnector Connector;
public Vector3D? DockingForward=null;
public Vector3D? DockingUp=null;
public Vector3D? TargetPosition=null;
public Vector3D? TargetDirection=null;
public Vector3D? TargetUp=null;
public IMyCubeGrid Grid{
get{
return Controller.CubeGrid;
}
}
public double ShipMass{
get{
return Controller.CalculateShipMass().PhysicalMass;
}
}
float MassAccomodation{
get{
return (float)(ShipMass*Gravity.Length());
}
}
public Vector3D Velocity{
get{
return Controller.GetShipVelocities().LinearVelocity;
}
}
public Roo<Vector3D> Position;
public Vector3D DampenVelocity=new Vector3D(0,0,0);
double SecondsSinceLastRun=0;
public double SpeedDeviation{
get{
return (Velocity-DampenVelocity).Length();
}
}
public Vector3D Relative(Vector3D input){
Vector3D output=Vector3D.Transform(input+Position,MatrixD.Invert(Controller.WorldMatrix));
output.Normalize();
output*=input.Length();
return output;
}
public List<IMyThrust>[] AllThrusters=new List<IMyThrust>[6];
List<IMyThrust> ForwardThrusters{
set{
AllThrusters[0]=value;
}
get{
return AllThrusters[0];
}
}
List<IMyThrust> BackwardThrusters{
set{
AllThrusters[1]=value;
}
get{
return AllThrusters[1];
}
}
List<IMyThrust> UpThrusters{
set{
AllThrusters[2]=value;
}
get{
return AllThrusters[2];
}
}
List<IMyThrust> DownThrusters{
set{
AllThrusters[3]=value;
}
get{
return AllThrusters[3];
}
}
List<IMyThrust> LeftThrusters{
set{
AllThrusters[4]=value;
}
get{
return AllThrusters[4];
}
}
List<IMyThrust> RightThrusters{
set{
AllThrusters[5]=value;
}
get{
return AllThrusters[5];
}
}
public Vector3D ForwardVector{
get{
return GenMethods.LocalToGlobal(new Vector3D(0,0,-1),Controller);
}
}
public Vector3D BackwardVector{
get{
return ForwardVector*-1;
}
}
public Vector3D UpVector{
get{
return GenMethods.LocalToGlobal(new Vector3D(0,1,0),Controller);
}
}
public Vector3D DownVector{
get{
return UpVector*-1;
}
}
public Vector3D LeftVector{
get{
return GenMethods.LocalToGlobal(new Vector3D(-1,0,0),Controller);
}
}
public Vector3D RightVector{
get{
return LeftVector*-1;
}
}
float GetThrust(int i){
float total=0;
foreach(IMyThrust Thruster in AllThrusters[i]){
if(Thruster.IsWorking)
total+=Thruster.MaxEffectiveThrust;
}
return Math.Max(total,1);
}
Roo<int,float> ForwardThrust;
Roo<int,float> BackwardThrust;
Roo<int,float> UpThrust;
Roo<int,float> DownThrust;
Roo<int,float> LeftThrust;
Roo<int,float> RightThrust;
double ForwardAcc{
get{
return ForwardThrust/ShipMass;
}
}
double BackwardAcc{
get{
return BackwardThrust/ShipMass;
}
}
double UpAcc{
get{
return UpThrust/ShipMass;
}
}
double DownAcc{
get{
return DownThrust/ShipMass;
}
}
double LeftAcc{
get{
return LeftThrust/ShipMass;
}
}
double RightAcc{
get{
return RightThrust/ShipMass;
}
}
double ForwardGs{
get{
return ForwardAcc/9.81;
}
}
double BackwardGs{
get{
return BackwardAcc/9.81;
}
}
double UpGs{
get{
return UpAcc/9.81;
}
}
double DownGs{
get{
return DownAcc/9.81;
}
}
double LeftGs{
get{
return LeftAcc/9.81;
}
}
double RightGs{
get{
return RightAcc/9.81;
}
}
Base6Directions.Direction Forward{
get{
return Controller.Orientation.Forward;
}
}
Base6Directions.Direction Backward{
get{
return Base6Directions.GetOppositeDirection(Forward);
}
}
Base6Directions.Direction Up{
get{
return Controller.Orientation.Up;
}
}
Base6Directions.Direction Down{
get{
return Base6Directions.GetOppositeDirection(Up);
}
}
Base6Directions.Direction Left{
get{
return Controller.Orientation.Left;
}
}
Base6Directions.Direction Right{
get{
return Base6Directions.GetOppositeDirection(Left);
}
}
double GetElevation(){
double output=double.MaxValue;
Controller.TryGetPlanetElevation(MyPlanetElevation.Surface,out output);
return output;
}
public Roo<double> Elevation;
double GetSealevel(){
double output=double.MaxValue;
Controller.TryGetPlanetElevation(MyPlanetElevation.Sealevel,out output);
return output;
}
public Roo<double> Sealevel;
Vector3D GetPlanetCenter(){
Vector3D output=new Vector3D(double.MaxValue,double.MaxValue,double.MaxValue);
Controller.TryGetPlanetPosition(out output);
return output;
}
public Roo<Vector3D> PlanetCenter;
public bool Landed(){
if(Velocity.Length()<2.5f&&GetEffectiveElevation()<10)
return true;
foreach(IMyLandingGear gear in LandingGear){
if(gear.IsLocked)
return true;
}
return false;
}
public Vector3D Gravity{
get{
return Controller.GetNaturalGravity();
}
}
public MyShip(IMyShipController controller, List<IMyShipController> altControllers){
Status="Initializing";
Controller=controller;
Position=new Roo<Vector3D>(Controller.GetPosition);
AltControllers=new List<IMyShipController>();
foreach(var altController in altControllers){
if(altController!=null&&altController!=controller&&altController.ControlThrusters){
AltControllers.Add(altController);
}
}
AllGyroscopes=CollectionMethods<IMyGyro>.AllByGrid(Grid);
if(AllGyroscopes.Count==0)
throw new ArgumentException("Error initializing ship: No valid gyroscopes");
Gyroscope=CollectionMethods<IMyGyro>.ByName("Control Gyroscope",AllGyroscopes);
if(Gyroscope==null)
Gyroscope=AllGyroscopes[0];
for(int i=0;i<6;i++)
AllThrusters[i]=new List<IMyThrust>();
List<IMyThrust> myThrusters=CollectionMethods<IMyThrust>.AllByGrid(Grid);
foreach(IMyThrust thrust in myThrusters){
Base6Directions.Direction direction=thrust.Orientation.Forward;
if(direction==Backward)
ForwardThrusters.Add(thrust);
else if(direction==Forward)
BackwardThrusters.Add(thrust);
else if(direction==Down)
UpThrusters.Add(thrust);
else if(direction==Up)
DownThrusters.Add(thrust);
else if(direction==Right)
LeftThrusters.Add(thrust);
else if(direction==Left)
RightThrusters.Add(thrust);
}
ForwardThrust=new Roo<int,float>(GetThrust,0);
BackwardThrust=new Roo<int,float>(GetThrust,1);
UpThrust=new Roo<int,float>(GetThrust,2);
DownThrust=new Roo<int,float>(GetThrust,3);
LeftThrust=new Roo<int,float>(GetThrust,4);
RightThrust=new Roo<int,float>(GetThrust,5);
List<IMyLandingGear> allLandingGear=CollectionMethods<IMyLandingGear>.AllByGrid(Grid);
LandingGear=new List<IMyLandingGear>();
foreach(IMyLandingGear gear in allLandingGear){
if(gear.IsParkingEnabled)
LandingGear.Add(gear);
}
Parachutes=CollectionMethods<IMyParachute>.AllByGrid(Grid);
Connector=CollectionMethods<IMyShipConnector>.ByGrid(Grid);
List<IMyDoor> airlockDoors=CollectionMethods<IMyDoor>.AllByName("Airlock",CollectionMethods<IMyDoor>.AllByConstruct(Grid));
Dictionary<string,int> airlockNames=new Dictionary<string,int>();
for(int i=0;i<airlockDoors.Count;i++){
IMyDoor door=airlockDoors[i];
string name=door.CustomName;
if(!name.Contains("Door")){
airlockDoors.RemoveAt(i--);
continue;
}
name=name.Substring(0,name.IndexOf("Door")).Trim();
if(airlockNames.ContainsKey(name))
airlockNames[name]=airlockNames[name]+1;
else
airlockNames.Add(name,1);
}
Airlocks=new List<MyAirlock>();
foreach(string airlockName in airlockNames.Keys){
if(airlockNames[airlockName]<2)
continue;
List<List<IMyDoor>> myAirlockDoors=new List<List<IMyDoor>>();
for(int i=0;i<4;i++)
myAirlockDoors.Add(new List<IMyDoor>());
for(int i=0;i<airlockDoors.Count;i++){
IMyDoor door=airlockDoors[i];
string name=door.CustomName;
string numerator=name.Substring(name.IndexOf("Door")).Trim();
name=name.Substring(0,name.IndexOf("Door")).Trim();
if(name.Contains(airlockName)&&name.IndexOf(airlockName)==0){
if(numerator.Contains("1"))
myAirlockDoors[0].Add(door);
else if(numerator.Contains("2"))
myAirlockDoors[1].Add(door);
else if(numerator.Contains("3"))
myAirlockDoors[2].Add(door);
else if(numerator.Contains("4"))
myAirlockDoors[3].Add(door);
else
continue;
airlockDoors.RemoveAt(i--);
continue;
}
}
for(int i=0;i<myAirlockDoors.Count;i++){
if(myAirlockDoors[i].Count==0)
myAirlockDoors.RemoveAt(i--);
}
if(myAirlockDoors.Count>1)
Airlocks.Add(new MyAirlock(airlockName,myAirlockDoors));
}
Elevation=new Roo<double>(GetElevation);
Sealevel=new Roo<double>(GetSealevel);
PlanetCenter=new Roo<Vector3D>(GetPlanetCenter);
Status="Initialized";
}
double LastElevation=0;
Vector3D LastVelocity=new Vector3D(0,0,0);
Vector3D Acceleration=new Vector3D(0,0,0);
public void RunSystemUpdate(double SecondsSinceLastUpdate){
Status="Updating System Data";
double elevation=Elevation;
LastElevation=GenMethods.TryGetBlockData<double>(Controller,"LastElevation",double.Parse,elevation);
if(!(GenMethods.HasBlockData(Controller,"LastVelocity")&&Vector3D.TryParse(GenMethods.GetBlockData(Controller,"LastVelocity"),out LastVelocity)))
LastVelocity=Velocity;
Acceleration=(Velocity-LastVelocity)/SecondsSinceLastUpdate;
GenMethods.SetBlockData(Controller,"LastElevation",Math.Round(Elevation,2).ToString());
GenMethods.SetBlockData(Controller,"LastVelocity",GenMethods.Round(Velocity,2).ToString());
SecondsSinceLastRun+=SecondsSinceLastUpdate;
Status="Ready to Run";
}
public void RunSystemOperations(){
Status="Running Operations";
UpdateFrequency=100;
if(true){
Write("Thruster Systems");
UpdateFrequency=Math.Min(UpdateFrequency,ManageThrusters());
}
else
ResetThrusters();
if(true){
Write("Gyroscope Systems");
UpdateFrequency=Math.Min(UpdateFrequency,ManageGyroscopes());
}
else
Gyroscope.GyroOverride=false;
if(Airlocks.Count>0){
Write("Airlock Systems");
foreach(var airlock in Airlocks)
airlock.Update(SecondsSinceLastRun);
UpdateFrequency=Math.Min(UpdateFrequency,10);
}
if(Parachutes.Count>0){
Write("Parachute System");
if(Gravity.Length()>0&&Elevation<500){
foreach(var parachute in Parachutes){
if(parachute.AutoDeploy&¶chute.Status==DoorStatus.Open){
parachute.AutoDeploy=false;
}
}
}
}
if(Connector!=null){
if(Connector.Status==MyShipConnectorStatus.Connected){
Connector.Enabled=false;
}
else if(!Connector.Enabled){
Connector.Enabled=true;
}
else{
Connector.Connect();
}
}
SecondsSinceLastRun=0;
Status="Completed Operations";
}
public int ManageGyroscopes(){
int attention=10;
float gyroCount=0;
foreach(IMyGyro Gyro in AllGyroscopes){
if(Gyro.IsWorking)
gyroCount+=Gyro.GyroPower/100.0f;
}
float angularMomentum=(float)(Controller.GetShipVelocities().AngularVelocity.Length());
float multx=(float)Math.Max(0.1f,Math.Min(1,1.5f/(ShipMass/gyroCount/1000000)))/(Math.Max(1,angularMomentum/1.5f));
Vector3 dampenVector=DampenGyro();
bool controlled=false;
Vector3 moveVector=new Vector3(0,0,0);
if(Controller.IsUnderControl){
moveVector=MoveGyro(Controller);
controlled=true;
}
else {
foreach(var altController in AltControllers){
if(altController.IsUnderControl){
moveVector=MoveGyro(altController);
controlled=true;
if(moveVector.Length()>0.2)
break;
}
}
}
if(!controlled&&false){
//AutoGyro(anoguas);
if(moveVector.Length()>0)
attention=Math.Min(attention,10);
}
Vector3 levelVector=new Vector3(0,0,0);
if(Gravity.Length()>0){
float angle=1;
angle*=Landed()?10:1;
angle*=controlled?5:1;
levelVector=LevelGyro(angle);
}
if(levelVector.Length()>1)
attention=Math.Min(attention,1);
// Calculate movement vector
var input=dampenVector;
input+=levelVector;
if(moveVector.X!=0)
input.X=moveVector.X;
if(moveVector.Y!=0)
input.Y=moveVector.Y;
if(moveVector.Z!=0)
input.Z=moveVector.Z;
SetGyroscopes(input*multx);
return attention;
}
Vector3 MoveGyro(IMyShipController controller){
Vector3 output=new Vector3(0,0,0);
output.X+=Math.Min(Math.Max(controller.RotationIndicator.X/100,-1),1);
output.Y+=Math.Min(Math.Max(controller.RotationIndicator.Y/100,-1),1);
output.Z+=controller.RollIndicator;
return output;
}
Vector3 DampenGyro(){
Vector3D angularVelocity=Controller.GetShipVelocities().AngularVelocity;
Vector3D relativeAngularVelocity=GenMethods.GlobalToLocal(angularVelocity,Controller);
return (new Vector3((float)relativeAngularVelocity.X,(float)relativeAngularVelocity.Y,(float)relativeAngularVelocity.Z))*.99f;
}
Vector3 LevelGyro(float TolerantAngle=1){
Vector3 output=new Vector3(0,0,0);
Vector3D gravityDirection=Gravity;
gravityDirection.Normalize();
double verticalDifference=GenMethods.GetAngle(gravityDirection,ForwardVector)-GenMethods.GetAngle(gravityDirection,BackwardVector);
if(GenMethods.GetAngle(gravityDirection,ForwardVector)<90&&Math.Abs(verticalDifference)>TolerantAngle)
output.X-=10*((float)Math.Min(Math.Abs(verticalDifference/90)+10,1));
if(GenMethods.GetAngle(gravityDirection,ForwardVector)>90&&Math.Abs(verticalDifference)>TolerantAngle&&GenMethods.GetAngle(gravityDirection,ForwardVector)<120)
output.X+=10*((float)Math.Min(Math.Abs(verticalDifference/90)+10,1));
double horizontalDifference=GenMethods.GetAngle(gravityDirection,LeftVector)-GenMethods.GetAngle(gravityDirection,RightVector);
if(GenMethods.GetAngle(gravityDirection,ForwardVector)<90&&Math.Abs(horizontalDifference)>TolerantAngle)
output.Y-=5*((float)Math.Min(Math.Abs((90-horizontalDifference)/90)+10,1));
if(Math.Abs(horizontalDifference)>TolerantAngle){
if(horizontalDifference<0)
output.Z+=10*((float)Math.Min(Math.Abs(horizontalDifference/90)+10,1));
else
output.Z-=10*((float)Math.Min(Math.Abs(horizontalDifference/90)+10,1));
}
return output;
}
Vector3 AutoGyro(Vector3D TargetDirection){
Vector3 output=new Vector3(0,0,0);
return output;
}
void SetGyroscopes(Vector3 Input){
Gyroscope.GyroOverride=true;
Vector3 global=Vector3D.TransformNormal(Input,Controller.WorldMatrix);
Vector3 output=Vector3D.TransformNormal(global,MatrixD.Invert(Gyroscope.WorldMatrix));
output.Normalize();
output*=Input.Length();
Gyroscope.Pitch=output.X;
Gyroscope.Yaw=output.Y;
Gyroscope.Roll=output.Z;
}
public int ManageThrusters(){
int attention=10;
bool dampeners=Controller.DampenersOverride;
var dampenVector=new Vector3(0,0,0);
dampenVector=DampenThrust();
if(!dampeners){
if(GenMethods.GetAngle(Velocity,ForwardVector)>15){
dampenVector.X=0;
dampenVector.Y=0;
}
dampenVector.Z=0;
}
var hoverVector=new Vector3(0,0,0);
bool descentOverride=Velocity.Length()>=20&&GenMethods.GetAngle(Velocity,Gravity)<5&&Elevation>1000;
if(!descentOverride)
descentOverride=Parachutes.Count>0&&Parachutes[0].Atmosphere>0.1f&&Parachutes[0].Status==DoorStatus.Open;
if(Gravity.Length()>0&&!descentOverride){
if(!Landed())
hoverVector=HoverThrust();
else if(GenMethods.TryGetBlockData<bool>(Controller,"LandingHoverOverride",bool.Parse,false)){
if(Velocity.Length()>0.5)
hoverVector=HoverThrust();
else if(Velocity.Length()<0.1)
GenMethods.SetBlockData(Controller,"LandingHoverOverride",false.ToString());
}
else if(Velocity.Length()>5){
Vector3D gravityDirection=Gravity;
gravityDirection.Normalize();
Vector3D accelerationDirection=Acceleration;
accelerationDirection.Normalize();
if(GenMethods.GetAngle(gravityDirection,accelerationDirection)<5&&Acceleration.Length()>Gravity.Length()/2){
hoverVector=HoverThrust();
GenMethods.SetBlockData(Controller,"LandingHoverOverride",true.ToString());
}
}
}
bool controlled=false;
VectorLock moveInput=new VectorLock{Move=new Vector3(0,0,0),Lock=new Vector3I(0,0,0)};
if(Controller.IsUnderControl){
moveInput=MoveThrust(Controller);
controlled=true;
}
else {
foreach(var altController in AltControllers){
if(altController.IsUnderControl){
moveInput=MoveThrust(altController);
controlled=true;
if(moveInput.Move.Length()>0.2)
break;
}
}
}
var moveVector=new Vector3(0,0,0);
var lockVector=new Vector3I(0,0,0);
if(controlled){
moveVector=moveInput.Move;
lockVector=moveInput.Lock;
}
else if(false){
//input=AutoThrust();
if(moveVector.Length()>0)
attention=Math.Min(attention,1);
}
// Calculate movement vector
var input=dampenVector;
if(lockVector.Length()>0){
if(lockVector.X!=0)
input.X=0;
if(lockVector.Y!=0)
input.Y=0;
if(lockVector.Z!=0)
input.Z=0;
}
input+=hoverVector;
if(moveVector.X!=0)
input.X=moveVector.X;
if(moveVector.Y!=0)
input.Y=moveVector.Y;
if(moveVector.Z!=0)
input.Z=moveVector.Z;
if(!input.Equals(moveVector))
attention=Math.Min(attention,10);
SetThrusters(input);
return attention;
}
struct VectorLock{
public Vector3 Move;
public Vector3I Lock;
}
VectorLock MoveThrust(IMyShipController controller){
Vector3 output=new Vector3(0,0,0);
Vector3I thrustLock=new Vector3I(0,0,0);
Vector3 input=controller.MoveIndicator;
float multxElevation=(float)(GetDeviationMultx(true)*0.95f);
float multxFree=(float)(GetDeviationMultx(false)*0.95f);
float effectiveSpeedLimitElevation=GetEffectiveSpeedLimit(true);
float effectiveSpeedLimitFree=GetEffectiveSpeedLimit(false);
float timeMultx=0.1f;
bool descentOverride=Velocity.Length()>=99&&GenMethods.GetAngle(Velocity,Gravity)<5;
if(Math.Abs(input.X)>0.2f){
if(input.X<0){
bool considerElevation=GenMethods.GetAngle(RightVector,Gravity)<85;
float effectiveSpeedLimit=considerElevation?effectiveSpeedLimitElevation:effectiveSpeedLimitFree;
float multx=considerElevation?multxElevation:multxFree;
float difference=(float)(effectiveSpeedLimit-(Velocity+RightAcc*timeMultx-DampenVelocity).Length());
float differenceMultx=(difference>5)?1:1/(5-difference);
if(difference>0||descentOverride)
output.X-=RightThrust*multx*differenceMultx*(float)ShipMass;
else
thrustLock.X=1;
}
else{
bool considerElevation=GenMethods.GetAngle(LeftVector,Gravity)<85;
float effectiveSpeedLimit=considerElevation?effectiveSpeedLimitElevation:effectiveSpeedLimitFree;
float multx=considerElevation?multxElevation:multxFree;
float difference=(float)(effectiveSpeedLimit-(Velocity+LeftAcc*timeMultx-DampenVelocity).Length());
float differenceMultx=(difference>5)?1:1/(5-difference);
if(difference>0||descentOverride)
output.X+=LeftThrust*multx*differenceMultx*(float)ShipMass;
else
thrustLock.X=1;
}
}
if(Math.Abs(input.Y)>0.2f){
if(input.Y>0){
bool considerElevation=GenMethods.GetAngle(UpVector,Gravity)<85;
float effectiveSpeedLimit=considerElevation?effectiveSpeedLimitElevation:effectiveSpeedLimitFree;
float multx=considerElevation?multxElevation:multxFree;
float difference=(float)(effectiveSpeedLimit-(Velocity+UpAcc*timeMultx-DampenVelocity).Length());
float differenceMultx=(difference>5)?1:1/(5-difference);
if(difference>0||descentOverride)
output.Y+=UpThrust*multx*differenceMultx*(float)ShipMass;
else
thrustLock.Y=1;
}
else{
bool considerElevation=GenMethods.GetAngle(DownVector,Gravity)<85;
float effectiveSpeedLimit=considerElevation?effectiveSpeedLimitElevation:effectiveSpeedLimitFree;
float multx=considerElevation?multxElevation:multxFree;
float difference=(float)(effectiveSpeedLimit-(Velocity+DownAcc*timeMultx-DampenVelocity).Length());
float differenceMultx=(difference>5)?1:1/(5-difference);
if(difference>0||descentOverride)
output.Y-=DownThrust*multx*differenceMultx*(float)ShipMass;
else
thrustLock.Y=1;
}
}
if(Math.Abs(input.Z)>0.2f){
if(input.Z<0){
bool considerElevation=GenMethods.GetAngle(ForwardVector,Gravity)<85;
float effectiveSpeedLimit=considerElevation?effectiveSpeedLimitElevation:effectiveSpeedLimitFree;
float multx=considerElevation?multxElevation:multxFree;
float difference=(float)(effectiveSpeedLimit-(Velocity+ForwardAcc*timeMultx-DampenVelocity).Length());
float differenceMultx=(difference>5)?1:1/(5-difference);
if(difference>0||descentOverride)
output.Z+=ForwardThrust*multx*differenceMultx*(float)ShipMass;
else
thrustLock.Z=1;
}
else{
bool considerElevation=GenMethods.GetAngle(BackwardVector,Gravity)<85;
float effectiveSpeedLimit=considerElevation?effectiveSpeedLimitElevation:effectiveSpeedLimitFree;
float multx=considerElevation?multxElevation:multxFree;
float difference=(float)(effectiveSpeedLimit-(Velocity+BackwardAcc*timeMultx-DampenVelocity).Length());
float differenceMultx=(difference>5)?1:1/(5-difference);
if(difference>0||descentOverride)
output.Z-=BackwardThrust*multx*differenceMultx*(float)ShipMass;
else
thrustLock.Z=1;
}
}
return new VectorLock{Move=output,Lock=thrustLock};
}
Vector3 DampenThrust(){
Vector3 output=new Vector3(0,0,0);
Vector3D relative=Relative(Velocity-DampenVelocity);
float dampMultx=(float) Math.Max(0.75f,(100-Math.Pow(ShipCount,2))/100f);
// relative is in m/s. ShipMass is kg. Looking for Force (kg-ms/s^2). We will assume that we want to stop within 1 second.
output.X-=(float)(relative.X*ShipMass*dampMultx);
output.Y-=(float)(relative.Y*ShipMass*dampMultx);
output.Z+=(float)(relative.Z*ShipMass*dampMultx);
return output;
}
Vector3 HoverThrust(){
Vector3 output=new Vector3(0,0,0);
if(Gravity.Length()>0){
Vector3D relativeGravity=GenMethods.GlobalToLocal(Gravity,Controller);
relativeGravity.Normalize();
// relative is a directional vector. MassAccomodation is Force (kg-ms/s^2)
output.X-=(float)relativeGravity.X*MassAccomodation;
output.Y-=(float)relativeGravity.Y*MassAccomodation;
output.Z+=(float)relativeGravity.Z*MassAccomodation;
}
return output;
}
Vector3 AutoThrust(Vector3D TargetPosition){
return AutoThrust(TargetPosition,(TargetPosition-Position).Length());
}
Vector3 AutoThrust(Vector3D TargetPosition,double TargetDistance){
Vector3 output=new Vector3(0,0,0);
Vector3D relativeTargetPosition=GenMethods.GlobalToLocalPosition(TargetPosition-Position,Controller);
float effectiveSpeedLimit=GetEffectiveSpeedLimit();
Vector3D relative=Relative(Velocity-DampenVelocity);
Vector3D relativeGravity=GenMethods.GlobalToLocal(Gravity,Controller);
relativeGravity.Normalize();
relativeGravity*=Gravity.Length();