-
Notifications
You must be signed in to change notification settings - Fork 0
/
script1.cs
2895 lines (2387 loc) · 88.2 KB
/
script1.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
// Isy's Solar Alignment Script
// ============================
// Version: 4.1.3
// Date: 2018-11-24
// =======================================================================================
// --- Configuration ---
// =======================================================================================
// --- Essential Configuration ---
// =======================================================================================
// Name of the group with all the solar related rotors (not needed in gyro mode)
string rotorGroupName = "Solar Rotors";
// By enabling gyro mode, the script will no longer use rotors but all gyroscopes on the grid instead.
// This mode only makes sense when used on a SHIP in SPACE. Gyro mode deactivates the following
// features: night mode, rotate to sunrise, time calculation and triggering external timer blocks.
bool useGyroMode = false;
// Name of the reference group for gyro mode. Put your main cockpit, flight seat or remote control in this group!
string referenceGroupName = "Solar Reference";
// --- Rotate to sunrise ---
// =======================================================================================
// Rotate the panels towards the sunrise during the night? (Possible values: true | false, default: true)
// The angle is figured out automatically based on the first lock of the day.
// If you want to set the angles yourself, set manualAngle to true and adjust the angles to your likings.
bool rotateToSunrise = true;
bool manualAngle = false;
int manualAngleVertical = 0;
int manualAngleHorizontal = 0;
// --- Reactor fallback ---
// =======================================================================================
// With this option, you can enable your reactors as a safety fallback, if not enough power is available
// to power all your machines or if the battery charge gets low. By default, all reactors on the same grid
// will be used. If you only want to use specific ones, put their names or group in the list.
// Example: string[] fallbackReactors = { "Small Reactor 1", "Base reactor group", "Large Reactor" };
bool useReactorFallback = false;
string[] fallbackReactors = { };
// Activation on low battery?
// The reactors will be active until 'turnOffAtPercent' of the max battery charge after it was turned on at 'turnOnAtPercent'.
bool activateOnLowBattery = true;
double turnOnAtPercent = 10;
double turnOffAtPercent = 15;
// Activate on overload?
// If the combined output of batteries and solar panels is more than 'overloadPercentage' of their max output, the reactors will be turned on.
bool activateOnOverload = true;
double overloadPercentage = 90;
// --- Base Light Management ---
// =======================================================================================
// Enable base light management? (Possible values: true | false, default: false)
// Lights will be turned on/off based on daytime.
bool baseLightManagement = false;
// Simple mode: toggle lights based on max. solar output (percentage). Time based toggle will be deactivated.
bool simpleMode = false;
int simpleThreshold = 50;
// Define the times when your lights should be turned on or off. If simple mode is active, this does nothing.
int lightOffHour = 8;
int lightOnHour = 18;
// To only toggle specific lights, declare groups for them.
// Example: string[] baseLightGroups = { "Interior Lights", "Spotlights", "Hangar Lights" };
string[] baseLightGroups = { };
// --- LCD panels ---
// =======================================================================================
// Add the following keyword to any LCD panel to show the script's informations.
// Edit the LCD's custom data to change the information that is shown there.
// When using the keyword on corner LCDs, put one of these keywords in their custom data:
// time, battery, oxygen
string lcdKeyword = "!SAS";
// --- Terminal statistics ---
// =======================================================================================
// The script can display informations in the names of the used blocks. The shown information is a percentage of
// the current efficiency (solar panels and oxygen farms) or the fill level (batteries and tanks).
// You can enable or disable single statistics or disable all using the master switch below.
bool enableTerminalStatistics = true;
bool showSolarStats = true;
bool showBatteryStats = true;
bool showOxygenFarmStats = true;
bool showOxygenTankStats = true;
// --- External timer blocks ---
// =======================================================================================
// Trigger external timer blocks at specific events? (action "Start" will be applied which takes the delay into account)
// Events can be: "sunrise", "sunset", a time like "15:00" or a number for every X seconds
// Every event needs a timer block name in the exact same order as the events.
// Calling the same timer block with multiple events requires it's name multiple times in the timers list!
// Example:
// string[] events = { "sunrise", "sunset", "15:00", "30" };
// string[] timers = { "Timer 1", "Timer 1", "Timer 2", "Timer 3" };
// This will trigger "Timer 1" at sunrise and sunset, "Timer 2" at 15:00 and "Timer 3" every 30 seconds.
bool triggerTimerBlock = false;
string[] events = { };
string[] timers = { };
// --- Settings for enthusiasts ---
// =======================================================================================
// Change percentage of the last locked output where the script should realign for a new best output (default: 2, gyro: 5)
double realginPercentageRotor = 2;
double realignPercentageGyro = 5;
// Percentage of the max detected output where the script starts night mode (default: 10)
double nightPercentage = 10;
// Percentage of the max detected output where the script detects night for time calculation (default: 50)
double nightTimePercentage = 50;
// Rotor speeds (speeds are automatically scaled between these values based on the output)
const float rotorMinSpeed = 0.1f;
const float rotorMaxSpeed = 1.0f;
// Rotor options
float rotorTorqueLarge = 33600000f;
float rotorTorqueSmall = 448000f;
bool setInertiaTensor = true;
bool setRotorLockWhenStopped = false;
// Min gyro RPM, max gyro RPM and gyro power for gyro mode
const double minGyroRPM = 0.1;
const double maxGyroRPM = 1;
const float gyroPower = 1f;
// Debugging
string debugLcd = "LCD Solar Alignment Debugging";
bool showPerformance = true;
bool showBlockCounts = true;
// =======================================================================================
// --- End of Configuration ---
// Don't change anything beyond this point!
// =======================================================================================
// Output variables
double rotorOutput = 0;
double outputBestPanel = 0;
double maxOutputAP = 0;
double maxOutputAPLast = 0;
double maxDetectedOutputAP = 0;
double currentOutputAP = 0;
// Lists
List<IMyMotorStator> rotors = new List<IMyMotorStator>();
List<IMyMotorStator> vRotors = new List<IMyMotorStator>();
List<IMyMotorStator> hRotors = new List<IMyMotorStator>();
List<IMyGyro> gyros = new List<IMyGyro>();
List<IMyTextPanel> lcds = new List<IMyTextPanel>();
List<IMyTextPanel> cornerLcds = new List<IMyTextPanel>();
List<IMyInteriorLight> lights = new List<IMyInteriorLight>();
List<IMyReflectorLight> spotlights = new List<IMyReflectorLight>();
List<IMyReactor> reactors = new List<IMyReactor>();
// Rotor variables
List<IMySolarPanel> solarPanels = new List<IMySolarPanel>();
int solarPanelsCount = 0;
bool nightModeActive = false;
bool sunrisePosReached = false;
int nightModeTimer = 30;
int realignTimer = 90;
bool rotateAllInit = true;
List<string> defaultCustomDataRotor = new List<string> {
"output=0",
"outputLast=0",
"outputLocked=0",
"outputMax=0",
"outputMaxAngle=0",
"outputMaxDayBefore=0",
"outputBestPanel=0",
"direction=1",
"directionChanged=0",
"directionTimer=0",
"allowRotation=1",
"rotationDone=1",
"timeSinceRotation=0",
"firstLockOfDay=0",
"sunriseAngle=0"
};
// Gyro variables
List<IMyShipController> gyroReference = new List<IMyShipController>();
double outputLockedPitch = 0;
double outputLockedYaw = 0;
double outputLockedRoll = 0;
double directionPitch = 1;
double directionYaw = 1;
double directionRoll = 1;
bool directionChangedPitch = false;
bool directionChangedYaw = false;
bool directionChangedRoll = false;
double directionTimerPitch = 0;
double directionTimerYaw = 0;
double directionTimerRoll = 0;
bool allowPitch = true;
bool allowYaw = true;
bool allowRoll = true;
double timeSincePitch = 0;
double timeSinceYaw = 0;
double timeSinceRoll = 0;
// Battery variables
List<IMyBatteryBlock> batteries = new List<IMyBatteryBlock>();
double batInput = 0;
double batInputMax = 0;
double batOutput = 0;
double batOutputMax = 0;
double batCharge = 0;
double batChargeMax = 0;
// Oxygen farm and tank variables
List<IMyOxygenFarm> farms = new List<IMyOxygenFarm>();
List<IMyGasTank> tanks = new List<IMyGasTank>();
double farmEfficiency = 0;
double tankCapacity = 0;
double tankFillLevel = 0;
int farmCount = 0;
// String variables for showing the information
string maxOutputAPStr = "0 kW";
string maxDetectedOutputAPStr = "0 kW";
string currentOutputAPStr = "0 kW";
string batInputStr = "0 kW";
string batInputMaxStr = "0 kW";
string batOutputStr = "0 kW";
string batOutputMaxStr = "0 kW";
string batChargeStr = "0 kW";
string batChargeMaxStr = "0 kW";
string tankCapacityStr = "0 L";
string tankFillLevelStr = "0 L";
// Information strings
string currentOperation = "Checking setup...";
string currentOperationInfo;
string[] workingIndicator = { "/", "-", "\\", "|" };
int workingCounter = 0;
// Variables for time measuring
int dayTimer = 0;
int safetyTimer = 270;
const int dayLengthDefault = 7200;
int dayLength = dayLengthDefault;
const int sunSetDefault = dayLengthDefault / 2;
int sunSet = sunSetDefault;
// LCD variables
List<string> defaultCustomDataLCD = new List<string> {
"showCurrentOperation=true",
"showSolarStats=true",
"showBatteryStats=true",
"showOxygenStats=true",
"showLocationTime=true"
};
// Reactor fallback
bool enableReactors = false;
string lastActivation = "";
// Error handling
string error, warning;
int errorCount = 0;
int warningCount = 0;
// Command line parameters
string action = "align";
int actionTimer = 3;
bool pause = false;
string rotateMode = "both";
bool pauseAfterRotate = false;
double rotateHorizontalAngle = 0;
double rotateVerticalAngle = 0;
// Script timing variables
int ticksSinceLastRun = 0;
int ticksPerScriptStep = 15;
int execCounter = 1;
bool firstRun = true;
bool init = true;
bool refreshLCDs = true;
// Method names
string[] methodName = {
"",
"Get Output",
"Time Calculation",
"Rotation Logic",
"Reactor Fallback"
};
public Program()
{
// Load variables out of the programmable block's custom data field
Load();
// Settings for nerds recalculation
realginPercentageRotor = (realginPercentageRotor % 100) / 100;
realignPercentageGyro = (realignPercentageGyro % 100) / 100;
nightPercentage = (nightPercentage % 100) / 100;
nightTimePercentage = (nightTimePercentage % 100) / 100;
// Set UpdateFrequency for starting the programmable block over and over again
Runtime.UpdateFrequency = UpdateFrequency.Update1;
}
void Main(string parameter)
{
try {
CreatePerformanceText("", true);
// Store the parameter
if (parameter != "") {
action = parameter.ToLower();
execCounter = 3;
}
// Stop all rotors and create initial information
if (firstRun) {
GetBlocks();
StopAll(false);
RemoveTerminalStatistics();
firstRun = false;
}
// Script timing
if (ticksSinceLastRun < ticksPerScriptStep) {
ticksSinceLastRun++;
return;
} else {
// Get all connected inventory blocks
if (init) {
GetBlocks();
init = false;
return;
}
if (refreshLCDs) {
WriteLCD();
WriteCornerLCD();
WriteDebugLCD();
refreshLCDs = false;
return;
}
workingCounter = workingCounter >= 3 ? 0 : workingCounter + 1;
ticksSinceLastRun = 0;
refreshLCDs = true;
init = true;
}
// Get output
if (execCounter == 1 && error == null) {
// Get the output of all measured blocks
GetOutput();
}
// Time calculation
if (execCounter == 2 && !useGyroMode && error == null) {
// Time Calculation
TimeCalculation();
// Switch the lights if base light management is activated
if (baseLightManagement) LightManagement();
// Trigger a timer block if triggerTimerBlock is true
if (triggerTimerBlock) TriggerExternalTimerBlock();
}
// Rotation logic
if (execCounter == 3 && error == null) {
// Either execute argument or use main rotation logic
if (!ExecuteArgument(action)) {
if (useGyroMode) {
RotationLogicGyro();
} else {
RotationLogic();
}
}
}
// Reactor fallback
if (execCounter == 4 && error == null) {
// Reactor fallback
if (useReactorFallback) ReactorFallback();
// Update variables for the next run
foreach (var rotor in rotors) {
double outputLast = ReadCustomData(rotor, "output");
WriteCustomData(rotor, "outputLast", outputLast);
}
maxOutputAPLast = maxOutputAP;
// Save variables into the programmable block's custom data field
Save();
}
// Write the information to various channels
Echo(CreateInformation(true));
CreatePerformanceText(methodName[execCounter]);
// Update the script execution counter
if (execCounter >= 4) {
// Reset the counter
execCounter = 1;
// Reset errors and warnings if none were counted
if (errorCount == 0) error = null;
if (warningCount == 0) warning = null;
errorCount = 0;
warningCount = 0;
} else {
execCounter++;
}
} catch (Exception e) {
StopAll();
string info = e + " \n\n";
info += "The error occured while executing the following script step:\n" + methodName[execCounter] + " (ID: " + execCounter + ")";
WriteLCD(info);
throw new Exception(info);
}
}
void GetBlocks()
{
// Get base grid of the PB
if (baseGrid == null) {
GetBaseGrid(Me.CubeGrid);
}
// LCDs
GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(lcds, l => l.CustomName.Contains(lcdKeyword) && !l.BlockDefinition.SubtypeId.Contains("Corner"));
// Corner LCDs
GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(cornerLcds, l => l.CustomName.Contains(lcdKeyword) && l.BlockDefinition.SubtypeId.Contains("Corner"));
// Rotor Mode
if (!useGyroMode) {
// Get rotors
var rotorGroup = GridTerminalSystem.GetBlockGroupWithName(rotorGroupName);
// If present, copy rotors into rotors list, else throw message
if (rotorGroup != null) {
rotorGroup.GetBlocksOfType<IMyMotorStator>(rotors);
// Create error if no rotor was in the group
if (rotors.Count == 0) {
CreateError("There are no rotors in the rotor group:\n'" + rotorGroupName + "'");
return;
}
} else {
CreateError("Rotor group not found:\n'" + rotorGroupName + "'");
return;
}
HashSet<IMyCubeGrid> grids = new HashSet<IMyCubeGrid>();
// Get unique grids and prepare the rotors
foreach (var rotor in rotors) {
if (!rotor.IsFunctional) CreateWarning("'" + rotor.CustomName + "' is broken!\nRepair it to use it for aligning!");
if (!rotor.Enabled) CreateWarning("'" + rotor.CustomName + "' is turned off!\nTurn it on to use it for aligning!");
if (!rotor.IsAttached) CreateWarning("'" + rotor.CustomName + "' has no rotor head!\nAdd one to use it for aligning!");
grids.Add(rotor.CubeGrid);
// Set basic stats for every rotor
if (rotor.CubeGrid.GridSize == 0.5) {
rotor.Torque = rotorTorqueSmall;
} else {
rotor.Torque = rotorTorqueLarge;
}
// Give warning, if the owner is different
if (rotor.GetOwnerFactionTag() != Me.GetOwnerFactionTag()) {
CreateWarning("'" + rotor.CustomName + "' has a different owner / faction!\nAll blocks should have the same owner / faction!");
}
}
// Find vertical and horizontal rotors and add them to their respective list
vRotors.Clear();
hRotors.Clear();
foreach (var rotor in rotors) {
if (grids.Contains(rotor.TopGrid)) {
vRotors.Add(rotor);
} else {
hRotors.Add(rotor);
// Set inertia tensor for horizontal rotors that are not on the main grid and if active in the config
if (rotor.CubeGrid != baseGrid && setInertiaTensor) {
try {
rotor.SetValueBool("ShareInertiaTensor", true);
} catch (Exception) {
// Ignore if it fails on DS
}
}
}
}
// Check, if a U-Shape is used and rebuild the list with only one of the connected rotors
List<IMyMotorStator> hRotorsTemp = new List<IMyMotorStator>();
hRotorsTemp.AddRange(hRotors);
hRotors.Clear();
bool addRotor;
foreach (var rotorTemp in hRotorsTemp) {
addRotor = true;
foreach (var rotor in hRotors) {
if (rotor.TopGrid == rotorTemp.TopGrid) {
rotorTemp.RotorLock = false;
rotorTemp.TargetVelocityRPM = 0f;
rotorTemp.Torque = 0f;
rotorTemp.BrakingTorque = 0f;
addRotor = false;
break;
}
}
if (addRotor) hRotors.Add(rotorTemp);
}
// Get solar panels and oxygen farms
solarPanels.Clear();
farms.Clear();
// Cycle through all hRotors and check if they have solar panels or oxygen farms and sum up their output
foreach (var hRotor in hRotors) {
rotorOutput = 0;
outputBestPanel = 0;
// Find all grids that are on top of this rotor
GetConnectedGrids(hRotor.TopGrid, true);
// Get all solar panels on these grids
var rotorSolarPanels = new List<IMySolarPanel>();
GridTerminalSystem.GetBlocksOfType<IMySolarPanel>(rotorSolarPanels, s => connectedGrids.Contains(s.CubeGrid) && s.IsWorking);
// Get all oxygen farms on these grids
var rotorOxygenFarms = new List<IMyOxygenFarm>();
GridTerminalSystem.GetBlocksOfType<IMyOxygenFarm>(rotorOxygenFarms, o => connectedGrids.Contains(o.CubeGrid) && o.IsWorking);
// Sum up the solar panels' output
foreach (var solarPanel in rotorSolarPanels) {
solarPanels.Add(solarPanel);
rotorOutput += solarPanel.MaxOutput;
if (solarPanel.MaxOutput > outputBestPanel) outputBestPanel = solarPanel.MaxOutput;
}
// Sum up the oxygen farms' output
foreach (var oxygenFarm in rotorOxygenFarms) {
farms.Add(oxygenFarm);
rotorOutput += oxygenFarm.GetOutput();
if (oxygenFarm.GetOutput() > outputBestPanel) outputBestPanel = oxygenFarm.GetOutput();
}
// Print a warning if a rotor has neither a solar panel nor an oxygen farm
if (rotorSolarPanels.Count == 0 && rotorOxygenFarms.Count == 0) {
CreateWarning("'" + hRotor.CustomName + "' can't see the sun!\nAdd a solar panel or oxygen farm to it!");
}
// Write the output in the custom data field
WriteCustomData(hRotor, "output", rotorOutput);
WriteCustomData(hRotor, "outputBestPanel", outputBestPanel);
// If it's higher than the max detected output, write it, too and also remember the rotor's current angle
if (rotorOutput > ReadCustomData(hRotor, "outputMax")) {
WriteCustomData(hRotor, "outputMax", rotorOutput);
WriteCustomData(hRotor, "outputMaxAngle", GetAngle(hRotor));
}
}
// Read and store the combined output of all hRotors that are on top of vRotors
foreach (var vRotor in vRotors) {
double output = 0;
outputBestPanel = double.MaxValue;
foreach (var hRotor in hRotors) {
if (hRotor.CubeGrid == vRotor.TopGrid) {
output += ReadCustomData(hRotor, "output");
if (ReadCustomData(hRotor, "outputBestPanel") < outputBestPanel) outputBestPanel = ReadCustomData(hRotor, "outputBestPanel");
}
}
// Write the output in the custom data field
WriteCustomData(vRotor, "output", output);
WriteCustomData(vRotor, "outputBestPanel", outputBestPanel);
// If it's higher than the max detected output, write it, too and also remember the rotor's current angle
if (output > ReadCustomData(vRotor, "outputMax")) {
WriteCustomData(vRotor, "outputMax", output);
WriteCustomData(vRotor, "outputMaxAngle", GetAngle(vRotor));
}
}
}
// Get grids that are connected via rotors or pistons to the base grid
GetConnectedGrids(baseGrid, true);
// Gyro Mode
if (useGyroMode) {
// Create error if the grid is stationary
if (Me.CubeGrid.IsStatic) {
CreateError("The grid is stationary!\nConvert it to a ship in the Info tab!");
return;
}
// Get reference group
var referenceGroup = GridTerminalSystem.GetBlockGroupWithName(referenceGroupName);
if (referenceGroup != null) {
referenceGroup.GetBlocksOfType<IMyShipController>(gyroReference);
if (gyroReference.Count == 0) {
CreateError("There are no cockpits, flight seats or remote controls in the reference group:\n'" + referenceGroupName + "'");
return;
}
} else {
CreateError("Reference group not found!\nPut your main cockpit, flight seat or remote control in a group called '" + referenceGroupName + "'!");
return;
}
// Get gyroscopes
GridTerminalSystem.GetBlocksOfType<IMyGyro>(gyros, g => g.CubeGrid == baseGrid && g.IsWorking);
// Create error if no gyroscopes were found
if (gyros.Count == 0) {
CreateError("No gyroscopes found!\nAre they enabled and completely built?");
return;
}
// Get solar panels and oxygen farms
GridTerminalSystem.GetBlocksOfType<IMySolarPanel>(solarPanels, s => connectedGrids.Contains(s.CubeGrid) && s.IsWorking);
GridTerminalSystem.GetBlocksOfType<IMyOxygenFarm>(farms, o => connectedGrids.Contains(o.CubeGrid) && o.IsWorking);
}
// If solar panels or oxygen farm count changed, reset maxOutput of all rotors
if (solarPanelsCount != solarPanels.Count || farmCount != farms.Count) {
foreach (var rotor in rotors) {
WriteCustomData(rotor, "outputMax", 0);
}
maxDetectedOutputAP = 0;
// Update solar panels and oxygen farms count
solarPanelsCount = solarPanels.Count;
farmCount = farms.Count;
CreateError("Amount of solar panels or oxygen farms changed!\nRestarting..");
return;
}
// Show error if no solar panels or oxygen farms were found
if (solarPanels.Count == 0 && farms.Count == 0) {
CreateError("No solar panels or oxygen farms found!\nHow should I see the sun now?");
return;
}
// Batteries
batteries.Clear();
GridTerminalSystem.GetBlocksOfType<IMyBatteryBlock>(batteries, b => connectedGrids.Contains(b.CubeGrid) && b.IsWorking);
// Show warning if no battery was found
if (batteries.Count == 0) {
CreateWarning("No batteries found!\nDon't you want to store your Power?");
}
// Oxygen tanks
tanks.Clear();
GridTerminalSystem.GetBlocksOfType<IMyGasTank>(tanks, t => !t.BlockDefinition.SubtypeId.Contains("Hydrogen") && connectedGrids.Contains(t.CubeGrid) && t.IsWorking);
// Reactors
if (useReactorFallback) {
reactors.Clear();
// Cycle through all the items in regularLcds to find groups or LCDs
foreach (var item in fallbackReactors) {
// If the item is a group, get the reactors and join the list with reactors list
var reactorGroup = GridTerminalSystem.GetBlockGroupWithName(item);
if (reactorGroup != null) {
var tempReactors = new List<IMyReactor>();
reactorGroup.GetBlocksOfType<IMyReactor>(tempReactors);
reactors.AddRange(tempReactors);
// Else try adding a single reactor
} else {
IMyReactor reactor = GridTerminalSystem.GetBlockWithName(item) as IMyReactor;
if (reactors != null) {
reactors.Add(reactor);
} else {
CreateWarning("Reactor not found:\n'" + reactor + "'\nUsing all reactors on the grid!");
}
}
}
// If the list is still empty, add all reactors on the grid
if (reactors.Count == 0) {
GridTerminalSystem.GetBlocksOfType<IMyReactor>(reactors, r => connectedGrids.Contains(r.CubeGrid) && r.IsFunctional);
}
}
// Lights
if (baseLightManagement) {
lights.Clear();
spotlights.Clear();
// If set, fill the list only with the group's lights
if (baseLightGroups.Length > 0) {
var tempLights = new List<IMyInteriorLight>();
var tempSpotlights = new List<IMyReflectorLight>();
foreach (var group in baseLightGroups) {
var lightGroup = GridTerminalSystem.GetBlockGroupWithName(group);
if (lightGroup != null) {
lightGroup.GetBlocksOfType<IMyInteriorLight>(tempLights);
lights.AddRange(tempLights);
lightGroup.GetBlocksOfType<IMyReflectorLight>(tempSpotlights);
spotlights.AddRange(tempSpotlights);
} else {
CreateWarning("Light group not found:\n'" + group + "'");
}
}
// Else search for all interior lights and spotlights and fill the groups
} else {
GridTerminalSystem.GetBlocksOfType<IMyInteriorLight>(lights, l => connectedGrids.Contains(l.CubeGrid));
GridTerminalSystem.GetBlocksOfType<IMyReflectorLight>(spotlights, l => connectedGrids.Contains(l.CubeGrid));
}
}
}
bool ExecuteArgument(string arg)
{
bool validArgument = true;
// Pause the alignment when set via argument
if (arg == "pause") {
StopAll();
if (pause) {
action = "align";
pause = false;
return false;
} else {
action = "paused";
pause = true;
}
currentOperation = "Automatic alignment paused.\n";
currentOperation += "Run 'pause' again to continue..";
// After stopping all rotors, only show the pause message in further runs (so that users can rotate manually)
} else if (arg == "paused") {
currentOperation = "Automatic alignment paused.\n";
currentOperation += "Run 'pause' again to continue..";
// Force a realign to the current best output
} else if (arg == "realign" && !useGyroMode) {
Realign();
currentOperation = "Forced realign by user.\n";
currentOperation += "Searching highest output for " + realignTimer + " more seconds.";
if (realignTimer == 0) {
action = "";
realignTimer = 90;
} else {
realignTimer -= 1;
}
// Reset the time calculation when set via argument
} else if (arg == "reset" && !useGyroMode) {
dayTimer = 0;
safetyTimer = 270;
sunSet = sunSetDefault;
dayLength = dayLengthDefault;
currentOperation = "Calculated time resetted.\n";
currentOperation += "Continuing in " + actionTimer + " seconds.";
if (actionTimer == 0) {
action = "";
actionTimer = 3;
} else {
actionTimer -= 1;
}
// Rotate to a specific angle when set via argument
} else if (arg.Contains("rotate") && !useGyroMode) {
String[] parameters = arg.Split(' ');
bool couldParse = false;
rotateMode = "both";
pauseAfterRotate = false;
if (parameters[0].Contains("pause")) pauseAfterRotate = true;
// If 2 parameters were specified, check if it's vertical or horizontal mode
if (parameters.Length == 2) {
// Should only the horizontals be rotated?
if (parameters[1].Contains("h")) {
couldParse = Double.TryParse(parameters[1].Replace("h", ""), out rotateHorizontalAngle);
rotateMode = "horizontalOnly";
// Should only the verticals be rotated?
} else if (parameters[1].Contains("v")) {
couldParse = Double.TryParse(parameters[1].Replace("v", ""), out rotateVerticalAngle);
rotateMode = "verticalOnly";
}
if (couldParse) {
currentOperation = "Checking rotation parameters...";
action = "rotNormal";
} else {
StopAll();
CreateWarning("Wrong format!\n\nShould be (e.g. 90 degrees):\nrotate h90 OR\nrotate v90");
}
// If 3 parameters were specified, check whether horizontal or vertical should be moved first
} else if (parameters.Length == 3) {
string plannedAction = "rotNormal";
// Should the verticals be rotated first?
if (parameters[1].Contains("v")) {
couldParse = Double.TryParse(parameters[1].Replace("v", ""), out rotateVerticalAngle);
if (couldParse) couldParse = Double.TryParse(parameters[2].Replace("h", ""), out rotateHorizontalAngle);
plannedAction = "rotVH1";
// Else try parsing normally
} else {
couldParse = Double.TryParse(parameters[1].Replace("h", ""), out rotateHorizontalAngle);
if (couldParse) couldParse = Double.TryParse(parameters[2].Replace("v", ""), out rotateVerticalAngle);
}
if (couldParse) {
currentOperation = "Checking rotation parameters...";
action = plannedAction;
} else {
StopAll();
CreateWarning("Wrong format!\n\nShould be (e.g. 90 degrees):\nrotate h90 v90 OR\nrotate v90 h90");
}
} else {
StopAll();
CreateWarning("Not enough parameters!\n\nShould be 2 or 3:\nrotate h90 OR\nrotate h90 v90");
}
// Normal rotation
} else if (arg == "rotNormal") {
currentOperation = "Rotating to user defined values...";
bool rotationDone = RotateAll(rotateMode, rotateHorizontalAngle, rotateVerticalAngle);
if (rotationDone && pauseAfterRotate) {
action = "paused";
} else if (rotationDone && !pauseAfterRotate) {
action = "resume";
}
// Vertical first rotation stage 1
} else if (arg == "rotVH1") {
currentOperation = "Rotating to user defined values...";
bool rotationDone = RotateAll("verticalOnly", rotateHorizontalAngle, rotateVerticalAngle);
if (rotationDone) action = "rotVH2";
// Vertical first rotation stage 2
} else if (arg == "rotVH2") {
currentOperation = "Rotating to user defined values...";
bool rotationDone = RotateAll("horizontalOnly", rotateHorizontalAngle, rotateVerticalAngle);
if (rotationDone && pauseAfterRotate) {
action = "paused";
} else if (rotationDone && !pauseAfterRotate) {
action = "resume";
}
} else {
validArgument = false;
}
return validArgument;
}
double ReadCustomData(IMyTerminalBlock block, string field)
{
CheckCustomData(block);
var customData = block.CustomData.Split('\n').ToList();
// Find entry
int index = customData.FindIndex(i => i.Contains(field + "="));
// Return value of entry if index was found
if (index > -1) {
return Convert.ToDouble(customData[index].Replace(field + "=", ""));
}
return 0;
}
void WriteCustomData(IMyTerminalBlock block, string field, double value)
{
CheckCustomData(block);
var customData = block.CustomData.Split('\n').ToList();
// Find entry
int index = customData.FindIndex(i => i.Contains(field + "="));
// Write new entry if index was found
if (index > -1) {
customData[index] = field + "=" + value;
block.CustomData = String.Join("\n", customData);
}
}
void CheckCustomData(IMyTerminalBlock block)
{
var customData = block.CustomData.Split('\n').ToList();
// Create new default customData if a too short one is found
if (customData.Count != defaultCustomDataRotor.Count) {
block.CustomData = String.Join("\n", defaultCustomDataRotor);
}
}
bool ReadCustomDataLCD(IMyTextPanel lcd, string field)
{
CheckCustomDataLCD(lcd);
var customData = lcd.CustomData.Split('\n').ToList();
// Find entry
int index = customData.FindIndex(i => i.Contains(field + "="));
// Return value of entry if index was found
if (index > -1) {
try {
return Convert.ToBoolean(customData[index].Replace(field + "=", ""));
} catch {
return true;
}
}
return true;
}
void CheckCustomDataLCD(IMyTextPanel lcd)
{
var customData = lcd.CustomData.Split('\n').ToList();
// Create new default customData if a too short one is found
if (customData.Count != defaultCustomDataLCD.Count) {
lcd.CustomData = String.Join("\n", defaultCustomDataLCD);
lcd.FontSize = 0.5f;
}
}
void GetOutput()
{
// Solar panels
maxOutputAP = 0;
currentOutputAP = 0;
foreach (var solarPanel in solarPanels) {
maxOutputAP += solarPanel.MaxOutput;
currentOutputAP += solarPanel.CurrentOutput;
// Terminal solar stats
if (showSolarStats && enableTerminalStatistics) {
double maxPanelOutput = 0;
double.TryParse(solarPanel.CustomData, out maxPanelOutput);
if (maxPanelOutput < solarPanel.MaxOutput) {
maxPanelOutput = solarPanel.MaxOutput;
solarPanel.CustomData = maxPanelOutput.ToString();
}
AddStatusToName(solarPanel, true, "", solarPanel.MaxOutput, maxPanelOutput);