forked from mattsemar/dsp-bulldozer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBulldozerPlugin.cs
More file actions
632 lines (557 loc) · 23.5 KB
/
BulldozerPlugin.cs
File metadata and controls
632 lines (557 loc) · 23.5 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
using System;
using System.Collections;
using System.Collections.Generic;
using BepInEx;
using Bulldozer.SelectiveDecoration;
using HarmonyLib;
using UnityEngine;
using static Bulldozer.Log;
using static PlatformSystem;
using Resources = Bulldozer.Properties.Resources;
namespace Bulldozer
{
[BepInPlugin(PluginGuid, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)]
[BepInProcess("DSPGAME.exe")]
public class BulldozerPlugin : BaseUnityPlugin
{
public const string PluginGuid = "semarware.dysonsphereprogram.bulldozer";
private static int _soilToDeduct;
public static BulldozerPlugin instance;
private ReformIndexInfoProvider _reformIndexInfoProvider;
private bool _flattenRequested;
private Harmony _harmony;
private UIElements _ui;
// Awake is called once when both the game and the plugin are loaded
private void Awake()
{
logger = Logger;
GuideMarker.logger = Logger;
instance = this;
_harmony = new Harmony(PluginGuid);
_harmony.PatchAll(typeof(BulldozerPlugin));
_harmony.PatchAll(typeof(WreckingBall));
_harmony.PatchAll(typeof(PluginConfigWindow));
PluginConfig.InitConfig(Config);
Debug("Bulldozer Plugin Loaded");
#if DEBUG
Debug("Debug build enabled");
#endif
}
private void Update()
{
if (!GameMain.isRunning
|| DSPGame.IsMenuDemo
|| GameMain.localPlanet == null
|| GameMain.localPlanet.factory == null
|| GameMain.localPlanet.factory.platformSystem == null)
{
return;
}
var platformSystem = GameMain.localPlanet.factory.platformSystem;
if (_reformIndexInfoProvider == null)
{
_reformIndexInfoProvider = new ReformIndexInfoProvider(platformSystem);
}
_reformIndexInfoProvider.DoInitWork(GameMain.localPlanet);
if (_ui != null && _ui.IsShowing())
{
if (PluginConfig.NeedReformIndexProvider())
{
_ui.ReadyForAction = _reformIndexInfoProvider is { Initted: true };
_ui.initPercent = _reformIndexInfoProvider.InitPercentComplete();
}
else
{
_ui.ReadyForAction = true;
}
}
WreckingBall.DoWorkItems(GameMain.mainPlayer?.factory);
DoPaveUpdate();
if (_ui != null && _ui.countText != null)
_ui.countText.text = $"{WreckingBall.RemainingTaskCount()}";
}
private void LateUpdate()
{
if (GameMain.sandboxToolsEnabled && UIRoot.instance.uiGame.buildMenu.currentCategory == 9)
UIRoot.instance.uiGame.buildMenu.reformAllButton.gameObject.SetActive(false);
}
private void OnDestroy()
{
// For ScriptEngine hot-reloading
WreckingBall.Stop();
if (_ui != null)
{
_ui.Unload();
Destroy(_ui);
_ui = null;
}
_reformIndexInfoProvider?.PlanetChanged(null);
PluginConfigWindow.NeedReinit = true;
_harmony.UnpatchSelf();
}
public void OnGUI()
{
if (PluginConfigWindow.visible)
{
PluginConfigWindow.OnGUI();
}
}
private void DoPaveUpdate()
{
if (_flattenRequested)
{
Logger.LogDebug("repaint requested");
SetFlattenRequestedFlag(false);
try
{
if (GameMain.mainPlayer.planetData.UpdateDirtyMeshes())
GameMain.mainPlayer.factory.RenderLocalPlanetHeightmap();
Decorate();
LogAndPopupMessage("Bulldozer done adding foundation");
}
catch (Exception e)
{
Logger.LogWarning($"exception painting {e}");
LogAndPopupMessage("Failure while painting. Check logs");
}
}
}
private void Decorate()
{
var platformSystem = GameMain.mainPlayer?.factory?.platformSystem;
var actionBuild = GameMain.mainPlayer?.controller.actionBuild;
if (platformSystem == null || actionBuild == null)
{
return;
}
if (!PluginConfig.guideLinesOnly.Value)
{
var foundationUsedUp = PlanetPainter.PaintPlanet(platformSystem, _reformIndexInfoProvider);
if (foundationUsedUp)
{
return;
}
}
if (_reformIndexInfoProvider is not { Initted: true } || _reformIndexInfoProvider.platformSystem != GameMain.localPlanet?.factory?.platformSystem)
{
if (_reformIndexInfoProvider.platformSystem != GameMain.localPlanet?.factory?.platformSystem)
{
_reformIndexInfoProvider.PlanetChanged(GameMain.localPlanet);
}
LogAndPopupMessage("not initted");
return;
}
SelectiveDecorationBuilder.Build(_reformIndexInfoProvider)
// .Flatten()
.Decorate();
}
private void InvokePavePlanet()
{
if (PluginConfig.alterVeinState.Value)
{
InvokePaveWithVeinAlteration();
}
else
{
InvokePavePlanetNoBury();
}
}
private void InvokePavePlanetNoBury()
{
var actionBuild = GameMain.mainPlayer?.controller.actionBuild;
var platformSystem = GameMain.mainPlayer?.factory?.platformSystem;
var factory = GameMain.localPlanet.factory;
if (actionBuild == null || platformSystem == null || factory == null)
{
LogAndPopupMessage("invalid state");
return;
}
if (GameMain.localPlanet == null || GameMain.localPlanet.type == EPlanetType.Gas)
{
LogAndPopupMessage("Bulldozer doesn't work on gas giants");
return;
}
if (PluginConfig.removeVegetation.Value)
{
for (var id = 0; id < factory.vegePool.Length; ++id)
{
if (factory.vegePool[id].protoId == 9999)
{
continue;
}
if (PluginConfig.IsLatConstrained())
{
var lat = GeoUtil.GetLatitudeDegForPosition(factory.vegePool[id].pos);
if (PluginConfig.LatitudeOutOfBounds(lat))
continue;
}
factory.RemoveVegeWithComponents(id);
}
}
else
{
PlanetAlterer.UpdateVegeHeight(factory);
}
GameMain.gpuiManager.SyncAllGPUBuffer();
int levelCount = 0;
int firstLatLeveled = -1;
int firstLongLeveled = -1;
int firstIndex = -1;
if (!PluginConfig.guideLinesOnly.Value)
for (var index = 0; index < GameMain.localPlanet.modData.Length << 1; ++index)
{
if (PluginConfig.IsLatConstrained())
{
var latLonForModIndex = _reformIndexInfoProvider.GetForModIndex(index);
if (latLonForModIndex.Equals(LatLon.Empty))
{
LogNTimes("No coord mapped to data index for {0}", 15, index);
continue;
}
if (PluginConfig.LatitudeOutOfBounds(latLonForModIndex.Lat))
{
continue;
}
if (firstLatLeveled < 0)
{
firstLatLeveled = (int)latLonForModIndex.Lat;
firstLongLeveled = (int)latLonForModIndex.Long;
firstIndex = index;
}
}
levelCount++;
GameMain.localPlanet.AddHeightMapModLevel(index, 3);
}
Debug(
$"leveled {levelCount} points for {PluginConfig.minLatitude.Value} {PluginConfig.maxLatitude.Value}. First ({firstLatLeveled}, {firstLongLeveled}) ndx: {firstIndex}");
var outOfSoilPile = false;
if (_soilToDeduct != 0 && PluginConfig.soilPileConsumption.Value != OperationMode.FullCheat)
{
// currently we don't have an easy way to see how much soil pile would've been deducted
outOfSoilPile = GameMain.mainPlayer.sandCount - _soilToDeduct <= 0;
GameMain.mainPlayer.SetSandCount(Math.Max(GameMain.mainPlayer.sandCount - _soilToDeduct, 0));
_soilToDeduct = 0;
}
if (GameMain.localPlanet.UpdateDirtyMeshes())
{
GameMain.localPlanet.factory.RenderLocalPlanetHeightmap();
}
factory.planet.landPercentDirty = true;
if (!outOfSoilPile || PluginConfig.soilPileConsumption.Value != OperationMode.Honest)
{
LogAndPopupMessage("Adding foundation");
platformSystem.EnsureReformData();
Decorate();
}
else
{
LogAndPopupMessage("not adding foundation failed to level everything");
}
LogAndPopupMessage("Bulldozer done adding foundation");
}
private void InvokePaveWithVeinAlteration()
{
LogAndPopupMessage("Altering veins");
PlanetAlterer.RaiseLowerVeins();
}
private void SetFlattenRequestedFlag(bool value)
{
Logger.LogDebug($"setting flatten requested to {value}");
_flattenRequested = value;
}
[HarmonyPostfix, HarmonyPatch(typeof(GameScenarioLogic), "NotifyOnUnlockTech")]
public static void GameScenarioLogic_NotifyOnUnlockTech_Postfix(int techId)
{
if (instance._ui == null || instance._ui.TechUnlockedState)
{
return;
}
TechProto techProto = LDB.techs.Select(techId);
if (techProto.Level == 3 && techProto.Name.Contains("宇宙探索"))
{
instance._ui.TechUnlockedState = true;
}
logger.LogDebug($"tech proto not matched {JsonUtility.ToJson(techProto)}");
}
[HarmonyPostfix, HarmonyPatch(typeof(UIBuildMenu), nameof(UIBuildMenu.OnCategoryButtonClick))]
public static void UIBuildMenu_OnCategoryButtonClick_Postfix(UIBuildMenu __instance)
{
var uiBuildMenu = __instance;
if (logger == null || instance == null)
{
Console.WriteLine(Resources.BulldozerPlugin_Not_Initialized, logger, instance);
return;
}
if (uiBuildMenu.currentCategory != 9)
{
if (instance._ui != null)
{
instance._ui.Hide();
}
return;
}
var inittedThisTime = false;
if (instance._ui == null)
{
instance.InitUi(uiBuildMenu);
inittedThisTime = true;
}
else
{
instance._ui.TechUnlockedState = instance.CheckResearchedTech() || PluginConfig.disableTechRequirement.Value;
if (instance._reformIndexInfoProvider != null && instance._ui != null)
{
if (!instance._reformIndexInfoProvider.Initted && PluginConfig.NeedReformIndexProvider())
{
instance._ui.ReadyForAction = false;
instance._ui.initPercent = instance._reformIndexInfoProvider.InitPercentComplete();
}
else
{
instance._ui.ReadyForAction = true;
}
}
}
instance._ui.Show(inittedThisTime);
}
private void InitUi(UIBuildMenu uiBuildMenu)
{
GameObject environmentModificationContainer = GameObject.Find("UI Root/Overlay Canvas/In Game/Function Panel/Build Menu/child-group");
var containerRect = environmentModificationContainer.GetComponent<RectTransform>();
var foundationButton = GameObject.Find("UI Root/Overlay Canvas/In Game/Function Panel/Build Menu/child-group/button-1");
var reformAllButton = GameObject.Find("UI Root/Overlay Canvas/In Game/Function Panel/Build Menu/reform-group/button-reform-all");
_ui = containerRect.gameObject.AddComponent<UIElements>();
UIElements.logger = logger;
if (containerRect == null || foundationButton == null)
{
return;
}
_ui.AddBulldozeComponents(containerRect, uiBuildMenu, foundationButton, reformAllButton, bt =>
{
StartCoroutine(InvokeAction(1, () =>
{
GameMain.mainPlayer.SetHandItems(0, 0);
GameMain.mainPlayer.controller.actionBuild.reformTool._Close();
}));
if (WreckingBall.IsRunning())
{
WreckingBall.Stop();
LogAndPopupMessage("Stopping...");
_ui.countText.text = "0";
}
else
{
var popupMessage = ConstructPopupMessage(GameMain.localPlanet);
var boxTitle = PluginConfig.IsLatConstrained() ? "Bulldoze selected latitudes" : "Bulldoze planet";
UIMessageBox.Show(boxTitle, popupMessage.Translate(),
"Ok", "Cancel", 0, InvokePluginCommands, () => { LogAndPopupMessage("Canceled"); });
}
});
_ui.TechUnlockedState = CheckResearchedTech() || PluginConfig.disableTechRequirement.Value;
if (PluginConfig.NeedReformIndexProvider())
{
_ui.ReadyForAction = _reformIndexInfoProvider is { Initted: true };
_ui.initPercent = _reformIndexInfoProvider?.InitPercentComplete() ?? 0;
}
else
{
_ui.ReadyForAction = true;
}
}
private string ConstructPopupMessage(PlanetData localPlanet)
{
if (localPlanet == null)
{
return "No local planet to bulldoze found.";
}
var popupMessage = "Please confirm the following actions: ";
if (PluginConfig.IsLatConstrained())
{
popupMessage += $"\r\n\t[For Selected Latitude Range {PluginConfig.GetLatRangeString()}]";
}
if (PluginConfig.destroyFactoryAssemblers.Value)
{
var machinesMsg = PluginConfig.skipDestroyingStations.Value ? "(assemblers, belts, but not stations)" : "(assemblers, belts, stations, etc)";
if (PluginConfig.IsLatConstrained())
{
popupMessage += $"\nDestroy factory machines {machinesMsg}";
popupMessage += "\nNote: this can be much slower than tearing down the entire factory";
}
else
{
popupMessage += $"\nDestroy all factory machines {machinesMsg}";
}
var countBuildGhosts = WreckingBall.CountBuildGhosts(GameMain.mainPlayer.factory);
if (countBuildGhosts > 0)
{
popupMessage += $". Including {countBuildGhosts} not yet built machines";
}
if (PluginConfig.deleteFactoryTrash.Value)
{
popupMessage += "\nDelete all littered factory items (existing litter should not be affected)";
}
if (!PluginConfig.deleteFactoryTrash.Value && Utils.IsOtherAssemblyLoaded("PersonalLogistics"))
{
popupMessage += "\nNote: Personal Logistics is also installed. Be aware that by default\r\n" +
" it will try and send littered items to your logistics stations.\r\n";
}
}
else if (PluginConfig.alterVeinState.Value)
{
if (PluginConfig.IsLatConstrained())
{
popupMessage += $"\nAttempt to {PluginConfig.GetCurrentVeinsRaiseState()} veins in Selected Latitudes";
}
else
{
popupMessage += $"\nAttempt to {PluginConfig.GetCurrentVeinsRaiseState()} all veins on planet.";
}
}
else
{
if (PluginConfig.IsLatConstrained())
{
popupMessage += "\nAdd foundation to locations in Selected Latitudes";
}
else if (PluginConfig.guideLinesOnly.Value)
{
popupMessage += "\nAdd foundation needed to paint guidelines";
}
else
{
popupMessage += "\nAdd foundation to all locations on planet";
}
if (PluginConfig.removeVegetation.Value)
{
if (PluginConfig.IsLatConstrained())
popupMessage += "\r\nRemove all plants trees and rocks in the Selected Latitudes";
else
popupMessage += "\r\nRemove all plants trees and rocks";
}
else
{
popupMessage += "\r\nSkip removing plants trees and rocks".Translate();
}
if (PluginConfig.addGuideLines.Value)
{
var planetPainter = SelectiveDecorationBuilder.Build(_reformIndexInfoProvider);
popupMessage += "\n" + planetPainter.BuildActionSummary();
}
if (PluginConfig.soilPileConsumption.Value != OperationMode.FullCheat || PluginConfig.foundationConsumption.Value != OperationMode.FullCheat)
{
var (foundationNeeded, soilPile) = GridExplorer.CountNeededResources(GameMain.localPlanet.factory.platformSystem, _reformIndexInfoProvider);
if (PluginConfig.soilPileConsumption.Value != OperationMode.FullCheat && soilPile != 0)
{
var verb = soilPile < 0 ? "Gain" : "Consume";
popupMessage += $"\n{verb} {Math.Abs(soilPile)} soil pile. (Current amount: {GameMain.mainPlayer.sandCount})";
if (soilPile > GameMain.mainPlayer.sandCount)
{
if (PluginConfig.soilPileConsumption.Value == OperationMode.Honest)
{
popupMessage +=
". Be aware that this process will halt after your soil pile is consumed.";
}
else
{
popupMessage += ". All of your soil pile will be consumed but the process will continue.";
}
}
_soilToDeduct = soilPile;
}
if (PluginConfig.foundationConsumption.Value != OperationMode.FullCheat)
{
popupMessage += $"\nConsume {foundationNeeded} foundation\n";
var (message, allRemoved, remainingToRemove) = StorageSystemManager.BuildRemovalMessage(REFORM_ID, foundationNeeded);
popupMessage += message;
if (!allRemoved)
{
if (OperationMode.HalfCheat == PluginConfig.foundationConsumption.Value)
popupMessage += $"\nProcess will continue after all available foundation ({foundationNeeded - remainingToRemove}) is used up.";
else
popupMessage += $"\nProcess will halt after all available foundation ({foundationNeeded - remainingToRemove}) is used up.";
}
}
}
}
return popupMessage;
}
private bool CheckResearchedTech()
{
TechProto requiredTech = null;
foreach (TechProto techProto in new List<TechProto>(LDB.techs.dataArray))
{
if (techProto.Name.Contains("宇宙探索") && techProto.Level == 3)
{
requiredTech = techProto;
}
}
if (requiredTech == null)
{
logger.LogWarning("did not find universe exploration tech item, assuming unlocked");
return true;
}
return GameMain.history.techStates[requiredTech.ID].unlocked;
}
private IEnumerator InvokeAction(int delay, Action action)
{
logger.LogDebug("pre yield");
if (delay > 0)
{
yield return new WaitForSeconds(delay);
}
else if (delay == -2)
{
yield return new WaitForFixedUpdate();
}
else
{
yield return new WaitForEndOfFrame();
}
logger.LogDebug("Performing action");
action();
}
private void InvokePluginCommands()
{
try
{
if (PluginConfig.destroyFactoryAssemblers.Value)
{
WreckingBall.Init(GameMain.mainPlayer.factory, GameMain.mainPlayer);
}
else
{
InvokePavePlanet();
}
}
catch (Exception e)
{
logger.LogWarning($"InvokePlugin failed {e}");
}
}
[HarmonyPostfix]
[HarmonyPatch(typeof(GameData), "NewGame")]
static void EnterGame()
{
Debug("Starting new game");
if (instance != null && instance._reformIndexInfoProvider != null)
instance._reformIndexInfoProvider.PlanetChanged(null);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(GameSave), "LoadCurrentGame")]
static void LoadCurrentGame(bool __result, string saveName)
{
if (instance != null && instance._reformIndexInfoProvider != null)
instance._reformIndexInfoProvider.PlanetChanged(null);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(GameMain), nameof(GameMain.End))]
public static void OnGameEnd()
{
if (instance != null && instance._ui != null)
{
instance._ui.Hide();
instance._reformIndexInfoProvider?.PlanetChanged(null);
}
}
}
}