-
Notifications
You must be signed in to change notification settings - Fork 394
/
DebugConsole.cs
4001 lines (3627 loc) · 188 KB
/
DebugConsole.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
using Barotrauma.ClientSource.Settings;
using Barotrauma.Extensions;
using Barotrauma.IO;
using Barotrauma.Items.Components;
using Barotrauma.MapCreatures.Behavior;
using Barotrauma.Networking;
using Barotrauma.Steam;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using static Barotrauma.FabricationRecipe;
namespace Barotrauma
{
static partial class DebugConsole
{
public partial class Command
{
/// <summary>
/// Executed when a client uses the command. If not set, the command is relayed to the server as-is.
/// </summary>
public Action<string[]> OnClientExecute;
public bool RelayToServer = true;
public void ClientExecute(string[] args)
{
bool allowCheats = GameMain.NetworkMember == null && (GameMain.GameSession?.GameMode is TestGameMode || Screen.Selected is { IsEditor: true });
if (!allowCheats && !CheatsEnabled && IsCheat)
{
NewMessage("You need to enable cheats using the command \"enablecheats\" before you can use the command \"" + Names[0] + "\".", Color.Red);
NewMessage("Enabling cheats will disable achievements during this play session.", Color.Red);
return;
}
if (OnClientExecute != null)
{
OnClientExecute(args);
}
else
{
OnExecute(args);
}
}
}
private static bool isOpen;
public static bool IsOpen
{
get => isOpen;
set => isOpen = value;
}
public static bool Paused = false;
private static GUITextBlock activeQuestionText;
private static GUIFrame frame;
private static GUIListBox listBox;
private static GUITextBox textBox;
#if DEBUG
private const int maxLength = 100000;
#else
private const int maxLength = 1000;
#endif
public static GUITextBox TextBox => textBox;
private static readonly ChatManager chatManager = new ChatManager(true, 64);
public static void Init()
{
OpenAL.Alc.SetErrorReasonCallback((string msg) => NewMessage(msg, Color.Orange));
frame = new GUIFrame(new RectTransform(new Vector2(0.5f, 0.45f), GUI.Canvas) { MinSize = new Point(400, 300), AbsoluteOffset = new Point(10, 10) },
color: new Color(0.4f, 0.4f, 0.4f, 0.8f));
var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), frame.RectTransform, Anchor.Center)) { RelativeSpacing = 0.01f };
var toggleText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), paddedFrame.RectTransform, Anchor.TopLeft), TextManager.Get("DebugConsoleHelpText"), Color.GreenYellow, GUIStyle.SmallFont, Alignment.CenterLeft, style: null);
var closeButton = new GUIButton(new RectTransform(new Vector2(0.025f, 1.0f), toggleText.RectTransform, Anchor.TopRight), "X", style: null)
{
Color = Color.DarkRed,
HoverColor = Color.Red,
TextColor = Color.White,
OutlineColor = Color.Red
};
closeButton.OnClicked += (btn, userdata) =>
{
isOpen = false;
GUI.ForceMouseOn(null);
textBox.Deselect();
return true;
};
listBox = new GUIListBox(new RectTransform(new Point(paddedFrame.Rect.Width, paddedFrame.Rect.Height - 60), paddedFrame.RectTransform, Anchor.Center)
{
IsFixedSize = false
}, color: Color.Black * 0.9f) { ScrollBarVisible = true };
textBox = new GUITextBox(new RectTransform(new Point(paddedFrame.Rect.Width, 30), paddedFrame.RectTransform, Anchor.BottomLeft)
{
IsFixedSize = false
});
textBox.MaxTextLength = maxLength;
textBox.OnKeyHit += (sender, key) =>
{
if (key != Keys.Tab && key != Keys.LeftShift)
{
ResetAutoComplete();
}
};
ChatManager.RegisterKeys(textBox, chatManager);
}
public static void AddToGUIUpdateList()
{
if (isOpen)
{
frame.AddToGUIUpdateList(order: 1);
}
}
public static void Update(float deltaTime)
{
while (queuedMessages.TryDequeue(out var newMsg))
{
AddMessage(newMsg);
if (GameSettings.CurrentConfig.SaveDebugConsoleLogs || GameSettings.CurrentConfig.VerboseLogging)
{
unsavedMessages.Add(newMsg);
if (unsavedMessages.Count >= messagesPerFile)
{
SaveLogs();
unsavedMessages.Clear();
}
}
}
if (!IsOpen && GUI.KeyboardDispatcher.Subscriber == null)
{
foreach (var (key, command) in DebugConsoleMapping.Instance.Bindings)
{
if (key.IsHit())
{
ExecuteCommand(command);
}
}
}
activeQuestionText?.SetAsLastChild();
if (PlayerInput.KeyHit(Keys.F3) && !PlayerInput.KeyDown(Keys.LeftControl) && !PlayerInput.KeyDown(Keys.RightControl))
{
Toggle();
}
else if (isOpen && PlayerInput.KeyHit(Keys.Escape))
{
isOpen = false;
GUI.ForceMouseOn(null);
textBox.Deselect();
SoundPlayer.PlayUISound(GUISoundType.Select);
}
if (isOpen)
{
frame.UpdateManually(deltaTime);
Character.DisableControls = true;
if (PlayerInput.KeyHit(Keys.Tab) && !textBox.IsIMEActive)
{
int increment = PlayerInput.KeyDown(Keys.LeftShift) ? -1 : 1;
textBox.Text = AutoComplete(textBox.Text, increment: string.IsNullOrEmpty(currentAutoCompletedCommand) ? 0 : increment );
}
if (PlayerInput.KeyDown(Keys.LeftControl) || PlayerInput.KeyDown(Keys.RightControl))
{
if ((PlayerInput.KeyDown(Keys.C) || PlayerInput.KeyDown(Keys.D) || PlayerInput.KeyDown(Keys.Z)) && activeQuestionCallback != null)
{
activeQuestionCallback = null;
activeQuestionText = null;
NewMessage(PlayerInput.KeyDown(Keys.C) ? "^C" : PlayerInput.KeyDown(Keys.D) ? "^D" : "^Z", Color.White, true);
}
}
if (PlayerInput.KeyHit(Keys.Enter))
{
chatManager.Store(textBox.Text);
ExecuteCommand(textBox.Text);
textBox.Text = "";
}
}
}
public static void Toggle()
{
isOpen = !isOpen;
if (isOpen)
{
textBox.Select(ignoreSelectSound: true);
AddToGUIUpdateList();
}
else
{
GUI.ForceMouseOn(null);
textBox.Deselect();
}
SoundPlayer.PlayUISound(GUISoundType.Select);
}
private static bool IsCommandPermitted(Identifier command, GameClient client)
{
switch (command.Value.ToLowerInvariant())
{
case "kick":
return client.HasPermission(ClientPermissions.Kick);
case "ban":
case "banip":
case "banaddress":
return client.HasPermission(ClientPermissions.Ban);
case "unban":
case "unbanip":
return client.HasPermission(ClientPermissions.Unban);
case "netstats":
case "help":
case "dumpids":
case "admin":
case "entitylist":
case "togglehud":
case "toggleupperhud":
case "togglecharacternames":
case "fpscounter":
case "showperf":
case "dumptofile":
case "findentityids":
case "setfreecamspeed":
case "togglevoicechatfilters":
case "bindkey":
case "savebinds":
case "unbindkey":
case "wikiimage_character":
case "wikiimage_sub":
case "eosStat":
case "eosUnlink":
case "eosLoginEpicViaSteam":
return true;
default:
return client.HasConsoleCommandPermission(command);
}
}
public static void DequeueMessages()
{
while (queuedMessages.TryDequeue(out var newMsg))
{
if (listBox == null)
{
//don't attempt to add to the listbox if it hasn't been created yet
Messages.Add(newMsg);
}
else
{
AddMessage(newMsg);
}
if (GameSettings.CurrentConfig.SaveDebugConsoleLogs || GameSettings.CurrentConfig.VerboseLogging)
{
unsavedMessages.Add(newMsg);
}
}
}
private static void AddMessage(ColoredText msg)
{
//listbox not created yet, don't attempt to add
if (listBox == null) return;
if (listBox.Content.CountChildren > MaxMessages)
{
listBox.RemoveChild(listBox.Content.Children.First());
}
Messages.Add(msg);
if (Messages.Count > MaxMessages)
{
Messages.RemoveRange(0, Messages.Count - MaxMessages);
}
try
{
if (msg.IsError)
{
var textContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), listBox.Content.RectTransform), style: "InnerFrame", color: Color.White)
{
CanBeFocused = true,
OnSecondaryClicked = (component, data) =>
{
GUIContextMenu.CreateContextMenu(new ContextMenuOption("editor.copytoclipboard", true, () => { Clipboard.SetText(msg.Text); }));
return true;
}
};
var textBlock = new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width - 5, 0), textContainer.RectTransform, Anchor.TopLeft) { AbsoluteOffset = new Point(2, 2) },
RichString.Rich(msg.Text), textAlignment: Alignment.TopLeft, font: GUIStyle.SmallFont, wrap: true)
{
CanBeFocused = false,
TextColor = msg.Color
};
textContainer.RectTransform.NonScaledSize = new Point(textContainer.RectTransform.NonScaledSize.X, textBlock.RectTransform.NonScaledSize.Y + 5);
textBlock.SetTextPos();
}
else
{
var textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), listBox.Content.RectTransform),
RichString.Rich(msg.Text), font: GUIStyle.SmallFont, wrap: true)
{
CanBeFocused = false,
TextColor = msg.Color
};
}
listBox.UpdateScrollBarSize();
listBox.BarScroll = 1.0f;
}
catch (Exception e)
{
ThrowError("Failed to add a message to the debug console.", e);
}
chatManager.Clear();
}
static partial void ShowHelpMessage(Command command)
{
if (listBox.Content.CountChildren > MaxMessages)
{
listBox.RemoveChild(listBox.Content.Children.First());
}
var textContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), listBox.Content.RectTransform),
style: "InnerFrame", color: Color.White * 0.6f)
{
CanBeFocused = false
};
var textBlock = new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width - 170, 0), textContainer.RectTransform, Anchor.TopRight) { AbsoluteOffset = new Point(20, 0) },
command.Help, textAlignment: Alignment.TopLeft, font: GUIStyle.SmallFont, wrap: true)
{
CanBeFocused = false,
TextColor = Color.White
};
textContainer.RectTransform.NonScaledSize = new Point(textContainer.RectTransform.NonScaledSize.X, textBlock.RectTransform.NonScaledSize.Y + 5);
textBlock.SetTextPos();
new GUITextBlock(new RectTransform(new Point(150, textContainer.Rect.Height), textContainer.RectTransform),
command.Names[0].Value, textAlignment: Alignment.TopLeft);
listBox.UpdateScrollBarSize();
listBox.BarScroll = 1.0f;
chatManager.Clear();
}
private static void AssignOnClientExecute(string names, Action<string[]> onClientExecute)
{
Command command = commands.Find(c => c.Names.Intersect(names.Split('|').ToIdentifiers()).Any());
if (command == null)
{
throw new Exception("AssignOnClientExecute failed. Command matching the name(s) \"" + names + "\" not found.");
}
else
{
command.OnClientExecute = onClientExecute;
command.RelayToServer = false;
}
}
private static void AssignRelayToServer(string names, bool relay)
{
Command command = commands.Find(c => c.Names.Intersect(names.Split('|').ToIdentifiers()).Any());
if (command == null)
{
DebugConsole.Log("Could not assign to relay to server: " + names);
return;
}
command.RelayToServer = relay;
}
private static void InitProjectSpecific()
{
commands.Add(new Command("eosStat", "Query and display all logged in EOS users. Normally this is at most two users, but in a developer environment it could be more.", args =>
{
if (!EosInterface.Core.IsInitialized)
{
NewMessage("EOS not initialized");
return;
}
var loggedInUsers = EosInterface.IdQueries.GetLoggedInPuids();
if (!loggedInUsers.Any())
{
NewMessage("EOS user not logged in");
return;
}
NewMessage("Logged in EOS users:");
foreach (var puid in loggedInUsers)
{
TaskPool.Add(
$"eosStat -> {puid}",
EosInterface.IdQueries.GetSelfExternalAccountIds(puid),
t =>
{
if (!t.TryGetResult(out Result<ImmutableArray<AccountId>, EosInterface.IdQueries.GetSelfExternalIdError> result)) { return; }
NewMessage($" - {puid}");
if (result.TryUnwrapSuccess(out var ids))
{
foreach (var id in ids)
{
NewMessage($" - {id}");
if (id is EpicAccountId eaid)
{
async Task gameOwnershipTokenTest()
{
var tokenOption = await EosInterface.Ownership.GetGameOwnershipToken(eaid);
var verified = await tokenOption.Bind(t => t.Verify());
NewMessage($"Ownership token verify result: {verified}");
}
_ = gameOwnershipTokenTest(); // Fire and forget!
EosInterface.Login.TestEosSessionTimeoutRecovery(puid);
}
}
}
else
{
NewMessage($" - Failed to get external IDs linked to {puid}: {result}");
}
});
}
}));
AssignRelayToServer("eosStat", false);
commands.Add(new Command("eosUnlink", "Unlink the primary logged in external account ID from its corresponding EOS Product User ID and close the game. This is meant to be used to test the EOS consent flow.", args =>
{
var userId = EosInterface.IdQueries.GetLoggedInPuids().FirstOrDefault();
NewMessage($"Unlinking external account from PUID {userId}");
GameSettings.SetCurrentConfig(GameSettings.CurrentConfig with { CrossplayChoice = Eos.EosSteamPrimaryLogin.CrossplayChoice.Unknown });
GameSettings.SaveCurrentConfig();
TaskPool.Add("unlinkTask", EosInterface.Login.UnlinkExternalAccount(userId), _ =>
{
GameMain.Instance.Exit();
});
}));
AssignRelayToServer("eosUnlink", false);
commands.Add(new Command("eosLoginEpicViaSteam", "Log into an Epic account via a link to the currently logged in Steam account",
args =>
{
TaskPool.Add("eosLoginEpicViaSteam",
Eos.EosEpicSecondaryLogin.LoginToLinkedEpicAccount(),
TaskPool.IgnoredCallback);
}));
AssignRelayToServer("eosLoginEpicViaSteam", false);
commands.Add(new Command("resetgameanalyticsconsent", "Reset whether you've given your consent for the game to send statistics to GameAnalytics. After executing the command, the game should ask for your consent again on relaunch.", args =>
{
GameAnalyticsManager.ResetConsent();
}));
AssignRelayToServer("resetgameanalyticsconsent", false);
commands.Add(new Command("copyitemnames", "", (string[] args) =>
{
StringBuilder sb = new StringBuilder();
foreach (ItemPrefab mp in ItemPrefab.Prefabs)
{
sb.AppendLine(mp.Name.Value);
}
Clipboard.SetText(sb.ToString());
}));
commands.Add(new Command("autohull", "", (string[] args) =>
{
if (Screen.Selected != GameMain.SubEditorScreen) return;
if (MapEntity.MapEntityList.Any(e => e is Hull || e is Gap))
{
ShowQuestionPrompt("This submarine already has hulls and/or gaps. This command will delete them. Do you want to continue? Y/N",
(option) =>
{
ShowQuestionPrompt("The automatic hull generation may not work correctly if your submarine uses curved walls. Do you want to continue? Y/N",
(option2) =>
{
if (option2.ToLowerInvariant() == "y") { GameMain.SubEditorScreen.AutoHull(); }
});
});
}
else
{
ShowQuestionPrompt("The automatic hull generation may not work correctly if your submarine uses curved walls. Do you want to continue? Y/N",
(option) => { if (option.ToLowerInvariant() == "y") GameMain.SubEditorScreen.AutoHull(); });
}
}));
commands.Add(new Command("enablecheats", "enablecheats: Enables cheat commands and disables achievements during this play session.", (string[] args) =>
{
CheatsEnabled = true;
AchievementManager.CheatsEnabled = true;
if (GameMain.GameSession?.Campaign is CampaignMode campaign)
{
campaign.CheatsEnabled = true;
}
NewMessage("Enabled cheat commands.", Color.Red);
NewMessage("Achievements have been disabled during this play session.", Color.Red);
}));
AssignRelayToServer("enablecheats", true);
commands.Add(new Command("mainmenu|menu", "mainmenu/menu: Go to the main menu.", (string[] args) =>
{
GameMain.GameSession = null;
List<Character> characters = new List<Character>(Character.CharacterList);
foreach (Character c in characters)
{
c.Remove();
}
GameMain.MainMenuScreen.Select();
}));
commands.Add(new Command("game", "gamescreen/game: Go to the \"in-game\" view.", (string[] args) =>
{
if (Screen.Selected == GameMain.SubEditorScreen)
{
NewMessage("WARNING: Switching directly from the submarine editor to the game view may cause bugs and crashes. Use with caution.", Color.Orange);
Entity.Spawner ??= new EntitySpawner();
}
GameMain.GameScreen.Select();
}));
commands.Add(new Command("editsubs|subeditor", "editsubs/subeditor: Switch to the Submarine Editor to create or edit submarines.", (string[] args) =>
{
if (args.Length > 0)
{
var subInfo = new SubmarineInfo(string.Join(" ", args));
Submarine.MainSub = Submarine.Load(subInfo, true);
}
GameMain.SubEditorScreen.Select(enableAutoSave: Screen.Selected != GameMain.GameScreen);
Entity.Spawner?.Remove();
Entity.Spawner = null;
}, isCheat: true));
commands.Add(new Command("editparticles|particleeditor", "editparticles/particleeditor: Switch to the Particle Editor to edit particle effects.", (string[] args) =>
{
GameMain.ParticleEditorScreen.Select();
}));
commands.Add(new Command("editlevels|leveleditor", "editlevels/leveleditor: Switch to the Level Editor to edit levels.", (string[] args) =>
{
GameMain.LevelEditorScreen.Select();
}));
commands.Add(new Command("editsprites|spriteeditor", "editsprites/spriteeditor: Switch to the Sprite Editor to edit the source rects and origins of sprites.", (string[] args) =>
{
GameMain.SpriteEditorScreen.Select();
}));
commands.Add(new Command("editevents|eventeditor", "editevents/eventeditor: Switch to the Event Editor to edit scripted events.", (string[] args) =>
{
GameMain.EventEditorScreen.Select();
}));
commands.Add(new Command("editcharacters|charactereditor", "editcharacters/charactereditor: Switch to the Character Editor to edit/create the ragdolls and animations of characters.", (string[] args) =>
{
if (Screen.Selected == GameMain.GameScreen)
{
NewMessage("WARNING: Switching between the character editor and the game view may cause odd behaviour or bugs. Use with caution.", Color.Orange);
}
GameMain.CharacterEditorScreen.Select();
}));
commands.Add(new Command("quickstart", "Starts a singleplayer sandbox", (string[] args) =>
{
if (Screen.Selected != GameMain.MainMenuScreen)
{
ThrowError("This command can only be executed from the main menu.");
return;
}
Identifier subName = (args.Length > 0 ? args[0] : "").ToIdentifier();
if (subName.IsEmpty)
{
ThrowError("No submarine specified.");
return;
}
float difficulty = 40;
if (args.Length > 1)
{
float.TryParse(args[1], out difficulty);
}
LevelGenerationParams levelGenerationParams = null;
if (args.Length > 2)
{
string levelGenerationIdentifier = args[2];
levelGenerationParams = LevelGenerationParams.LevelParams.FirstOrDefault(p => p.Identifier == levelGenerationIdentifier);
}
if (SubmarineInfo.SavedSubmarines.None(s => s.Name == subName))
{
ThrowError($"Cannot find a sub that matches the name \"{subName}\".");
return;
}
GameMain.MainMenuScreen.QuickStart(fixedSeed: false, subName, difficulty, levelGenerationParams);
}, getValidArgs: () => new[] { SubmarineInfo.SavedSubmarines.Select(s => s.Name).Distinct().OrderBy(s => s).ToArray() }));
commands.Add(new Command("steamnetdebug", "steamnetdebug: Toggles Steamworks networking debug logging.", (string[] args) =>
{
SteamManager.SetSteamworksNetworkingDebugLog(!SteamManager.NetworkingDebugLog);
}));
commands.Add(new Command("readycheck", "Commence a ready check in multiplayer.", (string[] args) =>
{
NewMessage("Ready checks can only be commenced in multiplayer.", Color.Red);
}));
commands.Add(new Command("setsalary", "setsalary [0-100] [character/default]: Sets the salary of a certain character or the default salary to a percentage.", (string[] args) =>
{
ThrowError("This command can only be used in multiplayer campaign.");
}, isCheat: true, getValidArgs: () =>
{
return new[]
{
new[]{ "0", "100" },
Enumerable.Union(
new string[] { "default" },
Character.CharacterList.Select(c => c.Name).Distinct().OrderBy(n => n)).ToArray(),
};
}));
commands.Add(new Command("bindkey", "bindkey [key] [command]: Binds a key to a command.", (string[] args) =>
{
if (args.Length < 2)
{
ThrowError("No key or command specified.");
return;
}
string keyString = args[0];
string command = args[1];
KeyOrMouse key = Enum.TryParse<Keys>(keyString, ignoreCase: true, out var outKey)
? outKey
: Enum.TryParse<MouseButton>(keyString, ignoreCase: true, out var outMouseButton)
? outMouseButton
: (KeyOrMouse)MouseButton.None;
if (key.Key == Keys.None && key.MouseButton == MouseButton.None)
{
ThrowError($"Invalid key {keyString}.");
return;
}
DebugConsoleMapping.Instance.Set(key, command);
NewMessage($"\"{command}\" bound to {key}.", GUIStyle.Green);
if (GameSettings.CurrentConfig.KeyMap.Bindings.FirstOrDefault(bind => bind.Value.Key != Keys.None && bind.Value.Key == key) is { } existingBind && existingBind.Value != null)
{
AddWarning($"\"{key}\" has already been bound to {existingBind.Key}. The keybind will perform both actions when pressed.");
}
}, isCheat: false, getValidArgs: () => new[] { Enum.GetNames(typeof(Keys)), new[] { "\"\"" } }));
commands.Add(new Command("unbindkey", "unbindkey [key]: Unbinds a command.", (string[] args) =>
{
if (args.Length < 1)
{
ThrowError("No key specified.");
return;
}
string keyString = args[0];
KeyOrMouse key = Enum.TryParse<Keys>(keyString, ignoreCase: true, out var outKey)
? outKey
: Enum.TryParse<MouseButton>(keyString, ignoreCase: true, out var outMouseButton)
? outMouseButton
: (KeyOrMouse)MouseButton.None;
if (key.Key == Keys.None && key.MouseButton == MouseButton.None)
{
ThrowError($"Invalid key {keyString}.");
return;
}
DebugConsoleMapping.Instance.Remove(key);
NewMessage("Keybind unbound.", GUIStyle.Green);
return;
}, isCheat: false, getValidArgs: () => new[] { DebugConsoleMapping.Instance.Bindings.Keys.Select(keys => keys.ToString()).Distinct().OrderBy(k => k).ToArray() }));
commands.Add(new Command("savebinds", "savebinds: Writes current keybinds into the config file.", (string[] args) =>
{
ShowQuestionPrompt($"Some keybinds may render the game unusable, are you sure you want to make these keybinds persistent? ({DebugConsoleMapping.Instance.Bindings.Count} keybind(s) assigned) Y/N",
(option2) =>
{
if (option2.ToIdentifier() != "y")
{
NewMessage("Aborted.", GUIStyle.Red);
return;
}
GameSettings.SaveCurrentConfig();
});
}, isCheat: false));
commands.Add(new Command("togglegrid", "Toggle visual snap grid in sub editor.", (string[] args) =>
{
SubEditorScreen.ShouldDrawGrid = !SubEditorScreen.ShouldDrawGrid;
NewMessage(SubEditorScreen.ShouldDrawGrid ? "Enabled submarine grid." : "Disabled submarine grid.", GUIStyle.Green);
}));
commands.Add(new Command("spreadsheetexport", "Export items in format recognized by the spreadsheet importer.", (string[] args) =>
{
SpreadsheetExport.Export();
}));
commands.Add(new Command("wikiimage_character", "Save an image of the currently controlled character with a transparent background.", (string[] args) =>
{
if (Character.Controlled == null) { return; }
try
{
WikiImage.Create(Character.Controlled);
}
catch (Exception e)
{
DebugConsole.ThrowError("The command 'wikiimage_character' failed.", e);
}
}));
commands.Add(new Command("wikiimage_sub", "Save an image of the main submarine with a transparent background.", (string[] args) =>
{
if (Submarine.MainSub == null) { return; }
try
{
MapEntity.SelectedList.Clear();
MapEntity.ClearHighlightedEntities();
WikiImage.Create(Submarine.MainSub);
}
catch (Exception e)
{
DebugConsole.ThrowError("The command 'wikiimage_sub' failed.", e);
}
}));
AssignRelayToServer("kick", false);
AssignRelayToServer("kickid", false);
AssignRelayToServer("ban", false);
AssignRelayToServer("banid", false);
AssignRelayToServer("dumpids", false);
AssignRelayToServer("dumptofile", false);
AssignRelayToServer("findentityids", false);
AssignRelayToServer("campaigninfo", false);
AssignRelayToServer("help", false);
AssignRelayToServer("verboselogging", false);
AssignRelayToServer("freecam", false);
AssignRelayToServer("steamnetdebug", false);
AssignRelayToServer("quickstart", false);
AssignRelayToServer("togglegrid", false);
AssignRelayToServer("bindkey", false);
AssignRelayToServer("unbindkey", false);
AssignRelayToServer("savebinds", false);
AssignRelayToServer("spreadsheetexport", false);
#if DEBUG
AssignRelayToServer("listspamfilters", false);
AssignRelayToServer("crash", false);
AssignRelayToServer("showballastflorasprite", false);
AssignRelayToServer("simulatedlatency", false);
AssignRelayToServer("simulatedloss", false);
AssignRelayToServer("simulatedduplicateschance", false);
AssignRelayToServer("simulatedlongloadingtime", false);
AssignRelayToServer("storeinfo", false);
AssignRelayToServer("sendrawpacket", false);
#endif
commands.Add(new Command("clientlist", "", (string[] args) => { }));
AssignRelayToServer("clientlist", true);
commands.Add(new Command("say", "", (string[] args) => { }));
AssignRelayToServer("say", true);
commands.Add(new Command("msg", "", (string[] args) => { }));
AssignRelayToServer("msg", true);
commands.Add(new Command("setmaxplayers|maxplayers", "", (string[] args) => { }));
AssignRelayToServer("setmaxplayers", true);
commands.Add(new Command("setpassword|password", "", (string[] args) => { }));
AssignRelayToServer("setpassword", true);
commands.Add(new Command("traitorlist", "", (string[] args) => { }));
AssignRelayToServer("traitorlist", true);
AssignRelayToServer("money", true);
AssignRelayToServer("showmoney", true);
AssignRelayToServer("setskill", true);
AssignRelayToServer("setsalary", true);
AssignRelayToServer("readycheck", true);
commands.Add(new Command("debugjobassignment", "", (string[] args) => { }));
AssignRelayToServer("debugjobassignment", true);
AssignRelayToServer("givetalent", true);
AssignRelayToServer("unlocktalents", true);
AssignRelayToServer("giveexperience", true);
AssignOnExecute("control", (string[] args) =>
{
if (args.Length < 1) { return; }
if (GameMain.NetworkMember != null)
{
GameMain.Client?.SendConsoleCommand("control " + string.Join(' ', args[0]));
return;
}
var character = FindMatchingCharacter(args, true);
if (character != null)
{
Character.Controlled = character;
}
});
AssignRelayToServer("control", true);
commands.Add(new Command("shake", "", (string[] args) =>
{
GameMain.GameScreen.Cam.Shake = 10.0f;
}));
AssignOnExecute("explosion", (string[] args) =>
{
Vector2 explosionPos = Screen.Selected.Cam.ScreenToWorld(PlayerInput.MousePosition);
float range = 500, force = 10, damage = 50, structureDamage = 20, itemDamage = 100, empStrength = 0.0f, ballastFloraStrength = 50f;
if (args.Length > 0) float.TryParse(args[0], out range);
if (args.Length > 1) float.TryParse(args[1], out force);
if (args.Length > 2) float.TryParse(args[2], out damage);
if (args.Length > 3) float.TryParse(args[3], out structureDamage);
if (args.Length > 4) float.TryParse(args[4], out itemDamage);
if (args.Length > 5) float.TryParse(args[5], out empStrength);
if (args.Length > 6) float.TryParse(args[6], out ballastFloraStrength);
new Explosion(range, force, damage, structureDamage, itemDamage, empStrength, ballastFloraStrength).Explode(explosionPos, null);
});
AssignOnExecute("teleportcharacter|teleport", (string[] args) =>
{
Vector2 cursorWorldPos = GameMain.GameScreen.Cam.ScreenToWorld(PlayerInput.MousePosition);
TeleportCharacter(cursorWorldPos, Character.Controlled, args);
});
AssignOnExecute("spawn|spawncharacter", (string[] args) =>
{
SpawnCharacter(args, GameMain.GameScreen.Cam.ScreenToWorld(PlayerInput.MousePosition), out string errorMsg);
if (!string.IsNullOrWhiteSpace(errorMsg))
{
ThrowError(errorMsg);
}
});
AssignOnExecute("los", (string[] args) =>
{
if (args.None() || !bool.TryParse(args[0], out bool state))
{
state = !GameMain.LightManager.LosEnabled;
}
GameMain.LightManager.LosEnabled = state;
NewMessage("Line of sight effect " + (GameMain.LightManager.LosEnabled ? "enabled" : "disabled"), Color.Yellow);
});
AssignRelayToServer("los", false);
AssignOnExecute("lighting|lights", (string[] args) =>
{
if (args.None() || !bool.TryParse(args[0], out bool state))
{
state = !GameMain.LightManager.LightingEnabled;
}
GameMain.LightManager.LightingEnabled = state;
NewMessage("Lighting " + (GameMain.LightManager.LightingEnabled ? "enabled" : "disabled"), Color.Yellow);
});
AssignRelayToServer("lighting|lights", false);
AssignOnExecute("ambientlight", (string[] args) =>
{
bool add = string.Equals(args.LastOrDefault(), "add");
string colorString = string.Join(",", add ? args.SkipLast(1) : args);
if (colorString.Equals("restore", StringComparison.OrdinalIgnoreCase))
{
foreach (Hull hull in Hull.HullList)
{
if (hull.OriginalAmbientLight != null)
{
hull.AmbientLight = hull.OriginalAmbientLight.Value;
hull.OriginalAmbientLight = null;
}
}
NewMessage("Restored all hull ambient lights", Color.Yellow);
return;
}
Color color = XMLExtensions.ParseColor(colorString);
if (Level.Loaded != null)
{
Level.Loaded.GenerationParams.AmbientLightColor = color;
}
else
{
GameMain.LightManager.AmbientLight = add ? GameMain.LightManager.AmbientLight.Add(color) : color;
}
foreach (Hull hull in Hull.HullList)
{
hull.OriginalAmbientLight ??= hull.AmbientLight;
hull.AmbientLight = add ? hull.AmbientLight.Add(color) : color;
}
if (add)
{
NewMessage($"Set ambient light color to {color}.", Color.Yellow);
}
else
{
NewMessage($"Increased ambient light by {color}.", Color.Yellow);
}
});
AssignRelayToServer("ambientlight", false);
commands.Add(new Command("multiplylights", "Multiplies the colors of all the static lights in the sub with the given Vector4 value (for example, 1,1,1,0.5).", (string[] args) =>
{
if (Screen.Selected != GameMain.SubEditorScreen || args.Length < 1)
{
ThrowError("The multiplylights command can only be used in the submarine editor.");
}
if (args.Length < 1) return;
//join args in case there's spaces between the components
Vector4 value = XMLExtensions.ParseVector4(string.Join("", args));
foreach (Item item in Item.ItemList)
{
if (item.ParentInventory != null || item.body != null) continue;
var lightComponent = item.GetComponent<LightComponent>();
if (lightComponent != null) lightComponent.LightColor =
new Color(
(lightComponent.LightColor.R / 255.0f) * value.X,
(lightComponent.LightColor.G / 255.0f) * value.Y,
(lightComponent.LightColor.B / 255.0f) * value.Z,
(lightComponent.LightColor.A / 255.0f) * value.W);
}
}, isCheat: false));
commands.Add(new Command("color|colour", "Change color (as bytes from 0 to 255) of the selected item/structure instances. Applied only in the subeditor.", (string[] args) =>
{
if (Screen.Selected == GameMain.SubEditorScreen)
{
if (!MapEntity.SelectedAny)
{
ThrowError("You have to select item(s)/structure(s) first!");
}
else
{
if (args.Length < 3)
{
ThrowError("Not enough arguments provided! At least three required.");
return;
}
if (!byte.TryParse(args[0], out byte r))
{
ThrowError($"Failed to parse value for RED from {args[0]}");
}
if (!byte.TryParse(args[1], out byte g))
{
ThrowError($"Failed to parse value for GREEN from {args[1]}");
}
if (!byte.TryParse(args[2], out byte b))
{
ThrowError($"Failed to parse value for BLUE from {args[2]}");
}
Color color = new Color(r, g, b);
if (args.Length > 3)
{
if (!byte.TryParse(args[3], out byte a))
{
ThrowError($"Failed to parse value for ALPHA from {args[3]}");
}
else
{
color.A = a;
}
}
foreach (var mapEntity in MapEntity.SelectedList)
{