-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathSubworldSystem.cs
More file actions
1731 lines (1465 loc) · 48.4 KB
/
SubworldSystem.cs
File metadata and controls
1731 lines (1465 loc) · 48.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Terraria;
using Terraria.Audio;
using Terraria.Chat;
using Terraria.GameContent;
using Terraria.GameContent.Bestiary;
using Terraria.GameContent.Creative;
using Terraria.GameContent.Events;
using Terraria.Graphics.Capture;
using Terraria.IO;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.ModLoader.IO;
using Terraria.Net;
using Terraria.Net.Sockets;
using Terraria.Social;
using Terraria.Utilities;
using Terraria.WorldBuilding;
namespace SubworldLibrary
{
internal class SubserverSocket : ISocket
{
private int id;
internal static RemoteAddress address;
public SubserverSocket(int id)
{
this.id = id;
}
void ISocket.AsyncReceive(byte[] data, int offset, int size, SocketReceiveCallback callback, object state) { }
void ISocket.AsyncSend(byte[] data, int offset, int size, SocketSendCallback callback, object state)
{
lock (SubworldSystem.queue)
{
SubworldSystem.queue[SubworldSystem.totalData] = (byte)id;
Buffer.BlockCopy(data, offset, SubworldSystem.queue, SubworldSystem.totalData + 1, size);
SubworldSystem.totalData += size + 1;
}
}
void ISocket.Close() { }
void ISocket.Connect(RemoteAddress address) { }
RemoteAddress ISocket.GetRemoteAddress() => address;
bool ISocket.IsConnected() => Netplay.Clients[id].IsActive;
bool ISocket.IsDataAvailable() => false;
void ISocket.SendQueuedPackets() { }
bool ISocket.StartListening(SocketConnectionAccepted callback) => false;
void ISocket.StopListening() { }
}
public class SubworldSystem : ModSystem
{
internal static List<Subworld> subworlds;
internal static Subworld current;
internal static Subworld cache;
private static WorldFileData main;
private static int suppressAutoShutdown;
internal static TagCompound copiedData;
internal static int[] playerLocations;
internal static int[] pendingMoves;
internal static HashSet<ISocket> deniedSockets;
internal static NamedPipeClientStream pipeIn;
internal static NamedPipeClientStream pipeOut;
internal static byte[] queue;
internal static int totalData;
public override void OnModLoad()
{
subworlds = new List<Subworld>();
playerLocations = new int[256];
Array.Fill(playerLocations, -1);
pendingMoves = new int[256];
Array.Fill(pendingMoves, -1);
deniedSockets = new HashSet<ISocket>();
WorldFile.OnWorldLoad += ReadCachedData;
Player.Hooks.OnEnterWorld += OnEnterWorld;
Netplay.OnDisconnect += OnDisconnect;
suppressAutoShutdown = -1;
}
public override void Unload()
{
WorldFile.OnWorldLoad -= ReadCachedData;
Player.Hooks.OnEnterWorld -= OnEnterWorld;
Netplay.OnDisconnect -= OnDisconnect;
}
private static void ReadCachedData()
{
if (copiedData == null || current != null || cache != null)
{
return;
}
ReadCopiedMainWorldData();
}
private static void OnEnterWorld(Player player)
{
if (Main.netMode == 1)
{
cache?.OnUnload();
current?.OnLoad();
}
cache = current;
}
private static void OnDisconnect()
{
if (current != null || cache != null)
{
Main.menuMode = 14;
}
current = null;
cache = null;
}
public override void SaveWorldData(TagCompound tag)
{
// cached world data is saved in ExitWorldCallBack
}
public override void LoadWorldData(TagCompound tag)
{
if (!tag.TryGet("mod", out string mod) || !tag.TryGet("name", out string name) || !tag.TryGet("data", out TagCompound data))
{
return;
}
if (!ModContent.TryFind(mod, name, out Subworld subworld))
{
return;
}
copiedData = data;
}
/// <summary>
/// Hides the Return button.
/// <br/>Its value is reset before <see cref="Subworld.OnEnter"/> is called, and after <see cref="Subworld.OnExit"/> is called.
/// </summary>
public static bool noReturn;
/// <summary>
/// Hides the Underworld background.
/// <br/>Its value is reset before <see cref="Subworld.OnEnter"/> is called, and after <see cref="Subworld.OnExit"/> is called.
/// </summary>
public static bool hideUnderworld;
/// <summary>
/// The current subworld.
/// </summary>
public static Subworld Current => current;
/// <summary>
/// Returns true if the current subworld's ID matches the specified ID.
/// <code>SubworldSystem.IsActive("MyMod/MySubworld")</code>
/// </summary>
public static bool IsActive(string id) => current?.FullName == id;
/// <summary>
/// Returns true if the specified subworld is active.
/// </summary>
public static bool IsActive<T>() where T : Subworld => current?.GetType() == typeof(T);
/// <summary>
/// Returns true if not in the main world.
/// </summary>
public static bool AnyActive() => current != null;
/// <summary>
/// Returns true if the current subworld is from the specified mod.
/// </summary>
public static bool AnyActive(Mod mod) => current?.Mod == mod;
/// <summary>
/// Returns true if the current subworld is from the specified mod.
/// </summary>
public static bool AnyActive<T>() where T : Mod => current?.Mod == ModContent.GetInstance<T>();
/// <summary>
/// The current subworld's file path.
/// </summary>
public static string CurrentPath => Path.Combine(main.IsCloudSave ? Main.CloudWorldPath : Main.WorldPath, main.UniqueId.ToString(), current.FileName + ".wld");
/// <summary>
/// Tries to enter the subworld with the specified ID.
/// <code>SubworldSystem.Enter("MyMod/MySubworld")</code>
/// </summary>
public static bool Enter(string id)
{
if (current != cache)
{
return false;
}
for (int i = 0; i < subworlds.Count; i++)
{
if (subworlds[i].FullName == id)
{
BeginEntering(i);
return true;
}
}
return false;
}
/// <summary>
/// Enters the specified subworld.
/// </summary>
public static bool Enter<T>() where T : Subworld
{
if (current != cache)
{
return false;
}
for (int i = 0; i < subworlds.Count; i++)
{
if (subworlds[i].GetType() == typeof(T))
{
BeginEntering(i);
return true;
}
}
return false;
}
/// <summary>
/// Exits the current subworld.
/// </summary>
public static void Exit()
{
if (current != null && current == cache)
{
BeginEntering(current.ReturnDestination);
}
}
private static void BeginEntering(int index)
{
if (Main.netMode == 2)
{
return;
}
if (index == int.MinValue)
{
current = null;
Main.menuMode = 10;
Main.gameMenu = true;
Task.Factory.StartNew(ExitWorldCallBack, null);
return;
}
if (Main.netMode == 0)
{
if (current == null && index >= 0)
{
main = Main.ActiveWorldFileData;
}
current = index < 0 ? null : subworlds[index];
Main.menuMode = 10;
Main.gameMenu = true;
Task.Factory.StartNew(ExitWorldCallBack, index);
return;
}
ModPacket packet = ModContent.GetInstance<SubworldLibrary>().GetPacket();
packet.Write(index < 0 ? ushort.MaxValue : (ushort)index);
packet.Send();
}
/// <summary>
/// Tries to send the specified player to the subworld with the specified ID.
/// </summary>
public static void MovePlayerToSubworld(string id, int player)
{
if (Main.netMode == 1 || (Main.netMode == 2 && current != null))
{
return;
}
for (int i = 0; i < subworlds.Count; i++)
{
if (subworlds[i].FullName == id)
{
if (Main.netMode == 0)
{
BeginEntering(i);
return;
}
MovePlayerToSubserver(player, (ushort)i);
return;
}
}
}
/// <summary>
/// Sends the specified player to the specified subworld.
/// </summary>
public static void MovePlayerToSubworld<T>(int player) where T : Subworld
{
if (Main.netMode == 1 || (Main.netMode == 2 && current != null))
{
return;
}
for (int i = 0; i < subworlds.Count; i++)
{
if (subworlds[i].GetType() == typeof(T))
{
if (Main.netMode == 0)
{
BeginEntering(i);
return;
}
MovePlayerToSubserver(player, (ushort)i);
return;
}
}
}
/// <summary>
/// Sends the specified player to the main world.
/// </summary>
public static void MovePlayerToMainWorld(int player)
{
if (Main.netMode == 1 || (Main.netMode == 2 && current != null))
{
return;
}
if (Main.netMode == 0)
{
BeginEntering(-1);
return;
}
MovePlayerToSubserver(player, ushort.MaxValue);
}
internal static void MovePlayerToSubserver(int player, ushort id)
{
if (pendingMoves[player] >= 0)
{
return;
}
pendingMoves[player] = id;
ModPacket packet = ModContent.GetInstance<SubworldLibrary>().GetPacket();
packet.Write(id);
packet.Send(player);
if (playerLocations[player] >= 0)
{
subworlds[playerLocations[player]].link?.Send(GetDisconnectPacket(player, ModContent.GetInstance<SubworldLibrary>().NetID));
}
if (id != ushort.MaxValue)
{
// this respects the vanilla call order
Main.player[player].active = false;
NetMessage.SendData(14, -1, player, null, player, 0);
ChatHelper.BroadcastChatMessage(NetworkText.FromKey("Mods.SubworldLibrary.Move", Netplay.Clients[player].Name, subworlds[id].DisplayName), new Color(255, 240, 20), player);
Player.Hooks.PlayerDisconnect(player);
}
// stop sending packets to the client while they're moving
NetMessage.buffer[player].broadcast = false;
if (id < ushort.MaxValue)
{
StartSubserver(id);
}
}
internal static void FinishMove(int player)
{
// send packets to the client again
NetMessage.buffer[player].broadcast = true;
RemoteClient client = Netplay.Clients[player];
int id = pendingMoves[player];
if (id == ushort.MaxValue)
{
if (Main.autoShutdown && client.Socket.GetRemoteAddress().IsLocalHost())
{
// this is reverted in the CheckBytes injection
Main.autoShutdown = false;
suppressAutoShutdown = player;
}
playerLocations[player] = -1;
deniedSockets.Remove(client.Socket);
client.State = 1;
client.ResetSections();
// prompt the client to reconnect
client.Socket.AsyncSend(new byte[] { 5, 0, 3, (byte)player, 0 }, 0, 5, (state) => { });
pendingMoves[player] = -1;
return;
}
// prompt the client to reconnect, done before setting their location so the packet can go through
SubserverLink link = subworlds[id].link;
if (link != null && link.Connected)
{
client.Socket.AsyncSend(new byte[] { 5, 0, 3, (byte)player, 0 }, 0, 5, (state) => { });
}
// set the client's location. DenyRead and DenySend are now in effect
playerLocations[player] = id;
deniedSockets.Add(client.Socket);
pendingMoves[player] = -1;
}
private static void SyncDisconnect(int player)
{
if (playerLocations[player] >= 0)
{
subworlds[playerLocations[player]].link?.Send(GetDisconnectPacket(player, ModContent.GetInstance<SubworldLibrary>().NetID));
playerLocations[player] = -1;
}
deniedSockets.Remove(Netplay.Clients[player].Socket);
}
private static byte[] GetDisconnectPacket(int player, int id)
{
// client, (ushort) size, packet id, (byte/ushort) sublib net id twice (read a second time by sublib to sync a leaving client)
if (ModNet.NetModCount < 256)
{
return new byte[] { (byte)player, 5, 0, 250, (byte)id, (byte)id };
}
else
{
return new byte[] { (byte)player, 7, 0, 250, (byte)id, (byte)(id >> 8), (byte)id, (byte)(id >> 8) };
}
}
private static void AllowAutoShutdown(int i)
{
if (i == suppressAutoShutdown && Netplay.Clients[i].State == 10)
{
suppressAutoShutdown = -1;
Main.autoShutdown = true;
}
}
/// <summary>
/// Starts a subserver for the subworld with the specified ID, if one is not running already.
/// </summary>
public static void StartSubserver(int id)
{
Subworld subworld = subworlds[id];
if (subworld.link != null)
{
return;
}
string name = subworld.FileName;
string args = "tModLoader.dll -server -showserverconsole ";
args += Main.ActiveWorldFileData.IsCloudSave ? "-cloudworld \"" : "-world \"";
args += Main.worldPathName + "\" -subworld \"" + name + "\"";
if (Program.LaunchParameters.TryGetValue("-modpath", out string modpath))
{
args += " -modpath \"" + modpath + "\"";
}
if (Program.LaunchParameters.TryGetValue("-modpack", out string modpack))
{
args += " -modpack \"" + modpack + "\"";
}
if (Program.LaunchParameters.TryGetValue("-steamworkshopfolder", out string steamworkshopfolder))
{
args += " -steamworkshopfolder \"" + steamworkshopfolder + "\"";
}
if (Program.LaunchParameters.TryGetValue("-tmlsavedirectory", out string tmlsavedirectory))
{
args += " -tmlsavedirectory \"" + tmlsavedirectory + "\"";
}
if (Program.LaunchParameters.TryGetValue("-savedirectory", out string savedirectory))
{
args += " -savedirectory \"" + savedirectory + "\"";
}
if (Program.LaunchParameters.TryGetValue("-config", out string config))
{
args += " -config \"" + config + "\"";
}
if (Program.LaunchParameters.TryGetValue("-forcepriority", out string forcepriority))
{
args += " -forcepriority " + forcepriority;
}
if (Netplay.SpamCheck)
{
args += " -secure";
}
Process p = new Process();
p.StartInfo.FileName = Process.GetCurrentProcess().MainModule!.FileName;
p.StartInfo.Arguments = args;
p.StartInfo.UseShellExecute = true;
p.EnableRaisingEvents = true;
p.Exited += (_, _) => { StopSubserver(id); }; // ensures the main server recognizes a subserver as stopped even if it crashes before the pipes can connect
p.Start();
copiedData = new TagCompound();
CopyMainWorldData();
subworld.link = new SubserverLink(name, copiedData);
copiedData = null;
new Thread(subworld.link.ConnectAndRead)
{
Name = "Subserver Packets",
IsBackground = true
}.Start(id);
new Thread(subworld.link.ConnectAndSend)
{
Name = "Subserver Relay",
IsBackground = true
}.Start(id);
}
/// <summary>
/// Stops a subserver for the subworld with the specified ID, if one is running.
/// </summary>
public static void StopSubserver(int id)
{
Subworld subworld = subworlds[id];
if (subworld.link == null)
{
return;
}
subworld.link.Close();
subworld.link = null;
for (int i = 0; i < 256; i++)
{
if (playerLocations[i] == id)
{
playerLocations[i] = -1;
deniedSockets.Remove(Netplay.Clients[i].Socket);
pendingMoves[i] = ushort.MaxValue;
ModPacket packet = ModContent.GetInstance<SubworldLibrary>().GetPacket();
packet.Write(ushort.MaxValue);
packet.Send(i);
NetMessage.buffer[i].broadcast = false;
}
}
}
/// <summary>
/// Tries to get the index of the subworld with the specified ID.
/// <br/> Typically used for <see cref="Subworld.ReturnDestination"/>.
/// <br/> Returns <see cref="int.MinValue"/> if the subworld couldn't be found.
/// <code>public override int ReturnDestination => SubworldSystem.GetIndex("MyMod/MySubworld");</code>
/// </summary>
public static int GetIndex(string id)
{
for (int i = 0; i < subworlds.Count; i++)
{
if (subworlds[i].FullName == id)
{
return i;
}
}
return int.MinValue;
}
/// <summary>
/// Gets the index of the specified subworld.
/// <br/> Typically used for <see cref="Subworld.ReturnDestination"/>.
/// </summary>
public static int GetIndex<T>() where T : Subworld
{
for (int i = 0; i < subworlds.Count; i++)
{
if (subworlds[i].GetType() == typeof(T))
{
return i;
}
}
return int.MinValue;
}
private static byte[] GetPacketHeader(int size, int mod)
{
byte[] packet = new byte[size];
packet[0] = 255; // invalid client under normal circumstances, message 255 from client 255 is treated as a packet from the other server
packet[1] = (byte)(size - 1);
packet[2] = (byte)((size - 1) >> 8);
packet[3] = 255;
packet[4] = (byte)mod;
if (ModNet.NetModCount >= 256)
{
packet[5] = (byte)(mod >> 8);
}
return packet;
}
/// <summary>
/// Sends a packet from the specified mod directly to a subserver.
/// <br/> Use <see cref="GetIndex"/> to get the subserver's ID.
/// </summary>
public static void SendToSubserver(int subserver, Mod mod, byte[] data)
{
int header = ModNet.NetModCount < 256 ? 5 : 6;
byte[] packet = GetPacketHeader(data.Length + header, mod.NetID);
Buffer.BlockCopy(data, 0, packet, header, data.Length);
subworlds[subserver].link?.Send(packet);
}
/// <summary>
/// Sends a packet from the specified mod directly to all subservers.
/// </summary>
public static void SendToAllSubservers(Mod mod, byte[] data)
{
int header = ModNet.NetModCount < 256 ? 5 : 6;
byte[] packet = GetPacketHeader(data.Length + header, mod.NetID);
Buffer.BlockCopy(data, 0, packet, header, data.Length);
for (int i = 0; i < subworlds.Count; i++)
{
subworlds[i].link?.Send(packet);
}
}
/// <summary>
/// Sends a packet from the specified mod directly to all subservers added by that mod.
/// </summary>
public static void SendToAllSubserversFromMod(Mod mod, byte[] data)
{
int header = ModNet.NetModCount < 256 ? 5 : 6;
byte[] packet = GetPacketHeader(data.Length + header, mod.NetID);
Buffer.BlockCopy(data, 0, packet, header, data.Length);
for (int i = 0; i < subworlds.Count; i++)
{
Subworld subworld = subworlds[i];
if (subworld.Mod == mod)
{
subworld.link?.Send(packet);
}
}
}
/// <summary>
/// Sends a packet from the specified mod directly to the main server.
/// </summary>
public static void SendToMainServer(Mod mod, byte[] data)
{
int header = ModNet.NetModCount < 256 ? 5 : 6;
byte[] packet = GetPacketHeader(data.Length + header, mod.NetID);
Buffer.BlockCopy(data, 0, packet, header, data.Length);
lock (queue)
{
Buffer.BlockCopy(packet, 0, queue, totalData, packet.Length);
totalData += packet.Length;
}
}
/// <summary>
/// Can only be called in <see cref="Subworld.CopyMainWorldData"/> or <see cref="Subworld.OnExit"/>!
/// <br/>Stores data to be transferred between worlds under the specified key, if that key is not already in use.
/// <br/>Naming the key after the variable pointing to the data is highly recommended to avoid redundant copying. This can be done automatically with nameof().
/// <br/>Keys starting with '!' cannot be changed once copied, and don't need to be copied back to the main world.
/// <code>SubworldSystem.CopyWorldData(nameof(DownedSystem.downedBoss), DownedSystem.downedBoss);</code>
/// </summary>
public static void CopyWorldData(string key, object data)
{
if (data != null && (key[0] != '!' || !copiedData.ContainsKey(key)))
{
copiedData[key] = data;
}
}
/// <summary>
/// Can only be called in <see cref="Subworld.ReadCopiedMainWorldData"/> or <see cref="Subworld.ReadCopiedSubworldData"/>!
/// <br/>Reads data copied from another world stored under the specified key.
/// <br/>Keys starting with '!' don't need to be copied back to the main world. (SubworldSystem.Current == null)
/// <code>DownedSystem.downedBoss = SubworldSystem.ReadCopiedWorldData<bool>(nameof(DownedSystem.downedBoss));</code>
/// </summary>
public static T ReadCopiedWorldData<T>(string key) => copiedData.Get<T>(key);
private static bool ChangeAudio()
{
if (current != null)
{
return current.ChangeAudio();
}
if (cache != null)
{
return cache.ChangeAudio();
}
return false;
}
private static bool ManualAudioUpdates()
{
if (current != null)
{
return current.ManualAudioUpdates;
}
if (cache != null)
{
return cache.ManualAudioUpdates;
}
return false;
}
private static void CopyMainWorldData()
{
copiedData["!mainId"] = (Main.netMode != 2 || current != null) ? main.UniqueId.ToByteArray() : Main.ActiveWorldFileData.UniqueId.ToByteArray();
copiedData["!seed"] = Main.ActiveWorldFileData.SeedText;
copiedData["!gameMode"] = Main.ActiveWorldFileData.GameMode;
copiedData["!hardMode"] = Main.hardMode;
// it's called reflection because the code is ugly like you
using (MemoryStream stream = new MemoryStream())
{
using BinaryWriter writer = new BinaryWriter(stream);
FieldInfo field = typeof(NPCKillsTracker).GetField("_killCountsByNpcId", BindingFlags.NonPublic | BindingFlags.Instance);
Dictionary<string, int> kills = (Dictionary<string, int>)field.GetValue(Main.BestiaryTracker.Kills);
writer.Write(kills.Count);
foreach (KeyValuePair<string, int> item in kills)
{
writer.Write(item.Key);
writer.Write(item.Value);
}
field = typeof(NPCWasNearPlayerTracker).GetField("_wasNearPlayer", BindingFlags.NonPublic | BindingFlags.Instance);
HashSet<string> sights = (HashSet<string>)field.GetValue(Main.BestiaryTracker.Sights);
writer.Write(sights.Count);
foreach (string item in sights)
{
writer.Write(item);
}
field = typeof(NPCWasChatWithTracker).GetField("_chattedWithPlayer", BindingFlags.NonPublic | BindingFlags.Instance);
HashSet<string> chats = (HashSet<string>)field.GetValue(Main.BestiaryTracker.Chats);
writer.Write(chats.Count);
foreach (string item in chats)
{
writer.Write(item);
}
copiedData["bestiary"] = stream.GetBuffer();
}
using (MemoryStream stream = new MemoryStream())
{
using BinaryWriter writer = new BinaryWriter(stream);
FieldInfo field = typeof(CreativePowerManager).GetField("_powersById", BindingFlags.NonPublic | BindingFlags.Instance);
foreach (KeyValuePair<ushort, ICreativePower> item in (Dictionary<ushort, ICreativePower>)field.GetValue(CreativePowerManager.Instance))
{
if (item.Value is IPersistentPerWorldContent power)
{
writer.Write((ushort)(item.Key + 1));
power.Save(writer);
}
}
writer.Write((ushort)0);
copiedData["powers"] = stream.GetBuffer();
}
copiedData[nameof(Main.drunkWorld)] = Main.drunkWorld;
copiedData[nameof(Main.getGoodWorld)] = Main.getGoodWorld;
copiedData[nameof(Main.tenthAnniversaryWorld)] = Main.tenthAnniversaryWorld;
copiedData[nameof(Main.dontStarveWorld)] = Main.dontStarveWorld;
copiedData[nameof(Main.notTheBeesWorld)] = Main.notTheBeesWorld;
copiedData[nameof(Main.remixWorld)] = Main.remixWorld;
copiedData[nameof(Main.noTrapsWorld)] = Main.noTrapsWorld;
copiedData[nameof(Main.zenithWorld)] = Main.zenithWorld;
CopyDowned();
foreach (ICopyWorldData data in ModContent.GetContent<ICopyWorldData>())
{
data.CopyMainWorldData();
}
}
private static void ReadCopiedMainWorldData()
{
if (current != null)
{
main.UniqueId = new Guid(copiedData.Get<byte[]>("!mainId"));
Main.ActiveWorldFileData.SetSeed(copiedData.Get<string>("!seed"));
Main.GameMode = copiedData.Get<int>("!gameMode");
Main.hardMode = copiedData.Get<bool>("!hardMode");
}
// i'm sorry that was mean
using (MemoryStream stream = new MemoryStream(copiedData.Get<byte[]>("bestiary")))
{
using BinaryReader reader = new BinaryReader(stream);
FieldInfo field = typeof(NPCKillsTracker).GetField("_killCountsByNpcId", BindingFlags.NonPublic | BindingFlags.Instance);
Dictionary<string, int> kills = (Dictionary<string, int>)field.GetValue(Main.BestiaryTracker.Kills);
int count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
kills[reader.ReadString()] = reader.ReadInt32();
}
field = typeof(NPCWasNearPlayerTracker).GetField("_wasNearPlayer", BindingFlags.NonPublic | BindingFlags.Instance);
HashSet<string> sights = (HashSet<string>)field.GetValue(Main.BestiaryTracker.Sights);
count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
sights.Add(reader.ReadString());
}
field = typeof(NPCWasChatWithTracker).GetField("_chattedWithPlayer", BindingFlags.NonPublic | BindingFlags.Instance);
HashSet<string> chats = (HashSet<string>)field.GetValue(Main.BestiaryTracker.Chats);
count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
chats.Add(reader.ReadString());
}
}
using (MemoryStream stream = new MemoryStream(copiedData.Get<byte[]>("powers")))
{
using BinaryReader reader = new BinaryReader(stream);
FieldInfo field = typeof(CreativePowerManager).GetField("_powersById", BindingFlags.NonPublic | BindingFlags.Instance);
Dictionary<ushort, ICreativePower> powers = (Dictionary<ushort, ICreativePower>)field.GetValue(CreativePowerManager.Instance);
ushort id;
while ((id = reader.ReadUInt16()) > 0)
{
((IPersistentPerWorldContent)powers[(ushort)(id - 1)]).Load(reader, 0);
}
}
Main.drunkWorld = copiedData.Get<bool>(nameof(Main.drunkWorld));
Main.getGoodWorld = copiedData.Get<bool>(nameof(Main.getGoodWorld));
Main.tenthAnniversaryWorld = copiedData.Get<bool>(nameof(Main.tenthAnniversaryWorld));
Main.dontStarveWorld = copiedData.Get<bool>(nameof(Main.dontStarveWorld));
Main.notTheBeesWorld = copiedData.Get<bool>(nameof(Main.notTheBeesWorld));
Main.remixWorld = copiedData.Get<bool>(nameof(Main.remixWorld));
Main.noTrapsWorld = copiedData.Get<bool>(nameof(Main.noTrapsWorld));
Main.zenithWorld = copiedData.Get<bool>(nameof(Main.zenithWorld));
ReadCopiedDowned();
foreach (ICopyWorldData data in ModContent.GetContent<ICopyWorldData>())
{
data.ReadCopiedMainWorldData();
}
}
private static void CopyDowned()
{
copiedData[nameof(NPC.downedSlimeKing)] = NPC.downedSlimeKing;
copiedData[nameof(NPC.downedBoss1)] = NPC.downedBoss1;
copiedData[nameof(NPC.downedBoss2)] = NPC.downedBoss2;
copiedData[nameof(NPC.downedBoss3)] = NPC.downedBoss3;
copiedData[nameof(NPC.downedQueenBee)] = NPC.downedQueenBee;
copiedData[nameof(NPC.downedDeerclops)] = NPC.downedDeerclops;
copiedData[nameof(NPC.downedQueenSlime)] = NPC.downedQueenSlime;
copiedData[nameof(NPC.downedMechBoss1)] = NPC.downedMechBoss1;
copiedData[nameof(NPC.downedMechBoss2)] = NPC.downedMechBoss2;
copiedData[nameof(NPC.downedMechBoss3)] = NPC.downedMechBoss3;
copiedData[nameof(NPC.downedMechBossAny)] = NPC.downedMechBossAny;
copiedData[nameof(NPC.downedPlantBoss)] = NPC.downedPlantBoss;
copiedData[nameof(NPC.downedGolemBoss)] = NPC.downedGolemBoss;
copiedData[nameof(NPC.downedFishron)] = NPC.downedFishron;
copiedData[nameof(NPC.downedEmpressOfLight)] = NPC.downedEmpressOfLight;
copiedData[nameof(NPC.downedAncientCultist)] = NPC.downedAncientCultist;
copiedData[nameof(NPC.downedTowerSolar)] = NPC.downedTowerSolar;
copiedData[nameof(NPC.downedTowerVortex)] = NPC.downedTowerVortex;
copiedData[nameof(NPC.downedTowerNebula)] = NPC.downedTowerNebula;
copiedData[nameof(NPC.downedTowerStardust)] = NPC.downedTowerStardust;
copiedData[nameof(NPC.downedMoonlord)] = NPC.downedMoonlord;
copiedData[nameof(NPC.downedGoblins)] = NPC.downedGoblins;
copiedData[nameof(NPC.downedClown)] = NPC.downedClown;
copiedData[nameof(NPC.downedFrost)] = NPC.downedFrost;
copiedData[nameof(NPC.downedPirates)] = NPC.downedPirates;
copiedData[nameof(NPC.downedMartians)] = NPC.downedMartians;
copiedData[nameof(NPC.downedHalloweenTree)] = NPC.downedHalloweenTree;
copiedData[nameof(NPC.downedHalloweenKing)] = NPC.downedHalloweenKing;
copiedData[nameof(NPC.downedChristmasTree)] = NPC.downedChristmasTree;
copiedData[nameof(NPC.downedChristmasSantank)] = NPC.downedChristmasSantank;
copiedData[nameof(NPC.downedChristmasIceQueen)] = NPC.downedChristmasIceQueen;
copiedData[nameof(DD2Event.DownedInvasionT1)] = DD2Event.DownedInvasionT1;
copiedData[nameof(DD2Event.DownedInvasionT2)] = DD2Event.DownedInvasionT2;
copiedData[nameof(DD2Event.DownedInvasionT3)] = DD2Event.DownedInvasionT3;
}
private static void ReadCopiedDowned()
{
NPC.downedSlimeKing = copiedData.Get<bool>(nameof(NPC.downedSlimeKing));
NPC.downedBoss1 = copiedData.Get<bool>(nameof(NPC.downedBoss1));
NPC.downedBoss2 = copiedData.Get<bool>(nameof(NPC.downedBoss2));
NPC.downedBoss3 = copiedData.Get<bool>(nameof(NPC.downedBoss3));
NPC.downedQueenBee = copiedData.Get<bool>(nameof(NPC.downedQueenBee));
NPC.downedDeerclops = copiedData.Get<bool>(nameof(NPC.downedDeerclops));
NPC.downedQueenSlime = copiedData.Get<bool>(nameof(NPC.downedQueenSlime));
NPC.downedMechBoss1 = copiedData.Get<bool>(nameof(NPC.downedMechBoss1));
NPC.downedMechBoss2 = copiedData.Get<bool>(nameof(NPC.downedMechBoss2));
NPC.downedMechBoss3 = copiedData.Get<bool>(nameof(NPC.downedMechBoss3));
NPC.downedMechBossAny = copiedData.Get<bool>(nameof(NPC.downedMechBossAny));
NPC.downedPlantBoss = copiedData.Get<bool>(nameof(NPC.downedPlantBoss));
NPC.downedGolemBoss = copiedData.Get<bool>(nameof(NPC.downedGolemBoss));
NPC.downedFishron = copiedData.Get<bool>(nameof(NPC.downedFishron));
NPC.downedEmpressOfLight = copiedData.Get<bool>(nameof(NPC.downedEmpressOfLight));
NPC.downedAncientCultist = copiedData.Get<bool>(nameof(NPC.downedAncientCultist));
NPC.downedTowerSolar = copiedData.Get<bool>(nameof(NPC.downedTowerSolar));
NPC.downedTowerVortex = copiedData.Get<bool>(nameof(NPC.downedTowerVortex));
NPC.downedTowerNebula = copiedData.Get<bool>(nameof(NPC.downedTowerNebula));
NPC.downedTowerStardust = copiedData.Get<bool>(nameof(NPC.downedTowerStardust));
NPC.downedMoonlord = copiedData.Get<bool>(nameof(NPC.downedMoonlord));
NPC.downedGoblins = copiedData.Get<bool>(nameof(NPC.downedGoblins));
NPC.downedClown = copiedData.Get<bool>(nameof(NPC.downedClown));
NPC.downedFrost = copiedData.Get<bool>(nameof(NPC.downedFrost));
NPC.downedPirates = copiedData.Get<bool>(nameof(NPC.downedPirates));
NPC.downedMartians = copiedData.Get<bool>(nameof(NPC.downedMartians));
NPC.downedHalloweenTree = copiedData.Get<bool>(nameof(NPC.downedHalloweenTree));
NPC.downedHalloweenKing = copiedData.Get<bool>(nameof(NPC.downedHalloweenKing));