forked from 9E4ECDDE/MultiplayerDynamicBonesMod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.cs
2437 lines (2164 loc) · 152 KB
/
Main.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 ExternalDynamicBoneEditor.IPCSupport;
using HarmonyLib;
using MelonLoader;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using UnhollowerBaseLib;
using UnhollowerBaseLib.Runtime;
using UnhollowerRuntimeLib.XrefScans;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using VRC;
using VRC.Core;
using ConsoleColor = System.ConsoleColor;
using IntPtr = System.IntPtr;
using UIExpansionKit.API;
using System.Reflection.Emit;
namespace DBMod
{
internal class NDB : MelonMod
{
public NDB()
{ LoadCheck.SFC(); }
public const string VERSION_STR = "1042";
private static class NDBConfig
{
public static float distanceToDisable;
public static float colliderSizeLimit;
public static int dynamicBoneUpdateRate;
public static bool dynamicBoneUpdateRateAdjSettings;
public static bool distanceDisable;
public static bool enabledByDefault;
public static bool disallowInsideColliders;
public static bool destroyInsideColliders;
public static bool onlyForMyBones;
public static bool onlyForMeAndFriends;
public static bool disallowDesktoppers;
public static bool enableBoundsCheck;
public static float visiblityUpdateRate;
public static bool onlyHandColliders;
public static bool keybindsEnabled;
public static bool onlyOptimize;
public static int updateMode;
//public static bool hasShownCompatibilityIssueMessage;
//public static HashSet<string> avatarsToWhichNotApply;
public static Dictionary<string, bool> avatarsToWhichNotApply;
public static bool enableEditor;
public static bool breastsOnly;
//public static bool enableUserPanelButton;
//public static int userPanelButtonX;
//public static int userPanelButtonY;
public static HashSet<string> bonesToExclude;
public static HashSet<string> collidersToExclude;
public static HashSet<string> bonesToAlwaysExclude;
public static bool excludeSpecificBones;
public static bool interactSelf;
public static bool othersInteractSelf;
public static int logLevel;
public static int debugLog;
public static Dictionary<string, int> avatarsToAdjustDBRadius;
public static Dictionary<string, bool> avatarsToAddColliders;
public static int boneRadiusDivisor;
public static float endBoneRadius;
public static bool addAutoCollidersAll;
public static bool adjustRadiusExcludeZero;
public static bool adjustRadiusForAllZeroBones;
public static bool disableAllBones;
public static bool moarBones;
public static bool moarBonesPrefLimit;
public static bool moarBonesNotLocal;
public static HashSet<string> bonesToInclude;
public static HashSet<string> collidersToInclude;
public static bool includeSpecificBones;
}
struct OriginalBoneInformation
{
public float updateRate;
public float distanceToDisable;
public List<DynamicBoneCollider> colliders;
public DynamicBone referenceToOriginal;
public bool distantDisable;
public float Elasticity;
public float Stiffness;
public float Damping;
public float Inert;
public float Radius;
public bool Enabled;
}
private static NDB _Instance;
public Dictionary<string, System.Tuple<GameObject, bool, DynamicBone[], DynamicBoneCollider[], bool, System.Tuple<string, string, float>>> avatarsInScene;
private Dictionary<string, List<OriginalBoneInformation>> originalSettings;
public Dictionary<string, System.Tuple<Renderer, DynamicBone[]>> avatarRenderers;
private GameObject localPlayer;
private Dictionary<string, DynamicBone> localPlayerDBbyRootName;
private Transform toggleButton;
private bool enabled = true;
private float nextUpdateVisibility = 0;
private float nextEditorUpdate = 0;
private const float visiblityUpdateRate = 1f;
private (MethodBase, MethodBase) reloadDynamicBoneParamInternalFuncs;
//private static AvatarInstantiatedDelegate onAvatarInstantiatedDelegate;
//private static HarmonyInstance harmonyInstance;
private static MethodInfo onJoinedRoomPatch;
private static MethodInfo onAvatarInstantiatedPatch;
public static bool HookLIC = false;
public static HashSet<string> bonesExcluded = new HashSet<string>();
public static HashSet<string> collidersExcluded = new HashSet<string>();
public static HashSet<string> bonesIncluded = new HashSet<string>();
public static HashSet<string> collidersIncluded = new HashSet<string>();
public static Dictionary<string, Transform> specificButtonList = new Dictionary<string, Transform>();
public static Dictionary<string, Transform> otherAvatarButtonList = new Dictionary<string, Transform>();
public string AvatarsToWhichNotApplyPath = "UserData/MDB/AvatarsToWhichNotApply.txt";
public string BonesToExcludePath = "UserData/MDB/BonesToExclude.txt";
public string CollidersToExcludePath = "UserData/MDB/CollidersToExclude.txt";
public string BonesToAlwaysExcludePath = "UserData/MDB/BonesToAlwaysExclude.txt";
public string AvatarsToAdjustDBRadiusPath = "UserData/MDB/AvatarsToAdjustDBRadius.txt";
public string AvatarsToAddCollidersPath = "UserData/MDB/AvatarsToAddColliders.txt";
public string BonesToIncludePath = "UserData/MDB/BonesToInclude.txt";
public string CollidersToIncludePath = "UserData/MDB/CollidersToInclude.txt";
public static int moarbonesCount;
public bool firstrun = true;
public static string ExtraLogPath;
//private static void Hook(IntPtr target, IntPtr detour)
//{
// Imports.Hook(target, detour);
//}
//private delegate void AvatarInstantiatedDelegate(IntPtr @this, IntPtr avatarPtr, IntPtr avatarDescriptorPtr, bool loaded);
[DllImport("User32.dll", CharSet = CharSet.Unicode)]
static extern int MessageBox(IntPtr nWnd, string text, string title, uint type);
public unsafe override void OnApplicationStart()
{
_Instance = this;
RegisterModPrefs();
InitFileLists();
OnPreferencesSaved();
firstrun = false;
if (NDBConfig.updateMode == 2)
{
new Thread(new ThreadStart(CheckForUpdates)).Start();
}
else LogDebugInt(1, ConsoleColor.DarkGreen, $"Not checking for updates");
if (DateTime.Today.Month == 4 && DateTime.Today.Day == 1)
{
new Thread(new ThreadStart(MoarBoneCheck)).Start();
}
enabled = NDBConfig.enabledByDefault;
//HookCallbackFunctions();
//to forcefully disable the limit
PlayerPrefs.SetInt("VRC_LIMIT_DYNAMIC_BONE_USAGE", 0);
MethodBase[] methods = XrefScanner.XrefScan(typeof(DynamicBone).GetMethod("OnValidate"))
.Where(r => r.Type == XrefType.Method)
.Select(xref => xref.TryResolve())
.Where(m => m != null)
.OrderBy(m => m.GetMethodBody().GetILAsByteArray().Length).ToArray();
reloadDynamicBoneParamInternalFuncs = (methods[0], methods[1]);
//Obsolete?
//if (!NDBConfig.hasShownCompatibilityIssueMessage && MelonHandler.Mods.Any(m => m.Info.Name.ToLowerInvariant().Contains("emmvrc")))
//{
// MessageBox(IntPtr.Zero, "Looks like you are using the 'emmVRC' mod. Please disable all emmVRC dynamic bones functionality in emmVRC settings to avoid compatibility issues with Multiplayer Dynamic Bones.\nThis is a onetime notification, you will not be prompted again.", "Multiplayer Dynamic Bones mod", 0x40 | 0x1000 | 0x010000);
// MelonPreferences.SetEntryValue<bool>("NDB", "HasShownCompatibilityIssueMessage", true);
//}
ExpansionKitApi.GetExpandedMenu(ExpandedMenu.UserQuickMenu).AddSimpleButton("MDB Avatar Config", () => AvatarMenu(QuickMenu.prop_QuickMenu_0.field_Private_Player_0, false));
ExpansionKitApi.GetExpandedMenu(ExpandedMenu.AvatarMenu).AddSimpleButton("MDB Avatar Config", () => AvatarMenu(localPlayer.transform.root.GetComponentInChildren<VRC.Player>(), true));
if (MelonPreferences.GetEntryValue<int>("NDB", "QuickMenuButton") == 0) //Quick Menu Button - 1:Settings Menu(default), 2:Just Toggle, 0:Off
{
LogDebug(ConsoleColor.White, $"Quick Menu button is disabled - 'QuickMenuButton' pref is set to 0");
}
else if (MelonPreferences.GetEntryValue<int>("NDB", "QuickMenuButton") == 2)
{
ExpansionKitApi.GetExpandedMenu(ExpandedMenu.QuickMenu).AddSimpleButton($"Press to {((enabled) ? "disable" : "enable")} Dynamic Bones mod", () => ToggleState(), (button) => toggleButton = button.transform);
}
else ExpansionKitApi.GetExpandedMenu(ExpandedMenu.QuickMenu).AddSimpleButton("MDB Settings", () => SettingsMenuMain());
}
private void AvatarMenu(Player selectedPlayer, bool useBigMenu)
{
string avatarName = selectedPlayer.prop_ApiAvatar_0.name;
string aviID = selectedPlayer.prop_VRCPlayer_0.prop_VRCAvatarManager_0.prop_ApiAvatar_0.id;
string avatarHash = avatarName.Substring(0, Math.Min(avatarName.Length, 20)) + ":" + String.Format("{0:X}", aviID.GetHashCode()).Substring(4);
NDB.otherAvatarButtonList.Clear();
ICustomShowableLayoutedMenu otherAvatarMenu = null;
otherAvatarMenu = useBigMenu ? ExpansionKitApi.CreateCustomFullMenuPopup(LayoutDescription.WideSlimList) : ExpansionKitApi.CreateCustomQuickMenuPage(LayoutDescriptionCustom.QuickMenu1Column11Row);
otherAvatarMenu.AddSimpleButton("MDB Avatar Config - Close", () => otherAvatarMenu.Hide());
otherAvatarMenu.AddLabel($"Include/Exclude a Specific Avatar");
otherAvatarMenu.AddLabel($"Excluded avatars wont be multiplayered\nIncluded avatars will bypass filtering, ie: 'Only Friends'");
string AvatarExcludeText() // True - Exluded, False - Included
{
return $"Avatar is currently: {(NDBConfig.avatarsToWhichNotApply.ContainsKey(avatarHash) ? (NDBConfig.avatarsToWhichNotApply[avatarHash] ? "Excluded from MDB" : "Included & Bypassing filters") : "N/A")}";
}
otherAvatarMenu.AddSimpleButton(AvatarExcludeText(), () =>
{
if (NDBConfig.avatarsToWhichNotApply.ContainsKey(avatarHash))
{
if (NDBConfig.avatarsToWhichNotApply[avatarHash]) // If enabled
{
NDBConfig.avatarsToWhichNotApply[avatarHash] = false; //Change to Disable
}
else NDBConfig.avatarsToWhichNotApply.Remove(avatarHash); //Change to N/A
}
else NDBConfig.avatarsToWhichNotApply.Add(avatarHash, true); //Change to Enable
NDB.otherAvatarButtonList["SpecificAvatar"].GetComponentInChildren<Text>().text = AvatarExcludeText();
if (enabled) { RestoreOriginalColliderList(); AddAllCollidersToAllPlayers(); }
//SaveListFiles();
}, (button) => NDB.otherAvatarButtonList["SpecificAvatar"] = button.transform);
otherAvatarMenu.AddLabel($"Include/Exclude Specific Bones or Colliders\nExlude:{(NDBConfig.excludeSpecificBones ? "Enabled" : "DISABLED")}, Include:{(NDBConfig.includeSpecificBones ? "Enabled" : "DISABLED")} <-- In Mod Settings");
otherAvatarMenu.AddLabel($"Excluded objects wont be multiplayered\nIncluded will bypass filtering, ie: 'Only Hand Colliders'");
otherAvatarMenu.AddSimpleButton("Bones", (() => ShowBoneSpecificMenu(selectedPlayer, useBigMenu)));
otherAvatarMenu.AddSimpleButton("Colliders", (() => ShowColliderSpecificMenu(selectedPlayer, useBigMenu)));
//
otherAvatarMenu.AddLabel(CurrentText(), (button) => NDB.otherAvatarButtonList["Current"] = button.transform);
string CurrentText()
{
return $"Adjust avatar's DB radius based on a Multiplier or replace entirely - Currently: {(NDBConfig.avatarsToAdjustDBRadius.ContainsKey(avatarHash) ? (NDBConfig.avatarsToAdjustDBRadius[avatarHash] == -2 ? "Excluded" : (NDBConfig.avatarsToAdjustDBRadius[avatarHash] == 0 ? $"Replacing" : $"Multiplied by {(float)NDBConfig.avatarsToAdjustDBRadius[avatarHash] / 10f}")) : "N/A")}";
}
otherAvatarMenu.AddSimpleButton($"Multiply/Replace/Zero Radius Exclude - Menu", (() =>
{
otherAvatarMenu.Hide();
MultiReplaceRadiusMenu(selectedPlayer, useBigMenu, avatarName, aviID, avatarHash);
}));
otherAvatarMenu.AddLabel($"Auto add hand colliders to this avatar\n{(NDBConfig.addAutoCollidersAll ? "-Currently ENABLED for all avatars in Mod Settings-" : "-This can be enabled for all avatars in Mod Settings-")}");
string HandCollidersText()
{
return $"Hand Colliders: {(NDBConfig.avatarsToAddColliders.ContainsKey(avatarHash) ? (NDBConfig.avatarsToAddColliders[avatarHash] ? "Enabled for this Avatar" : "Disabled for this Avatar") : "N/A")}";
}
otherAvatarMenu.AddSimpleButton(HandCollidersText(), () =>
{
if (NDBConfig.avatarsToAddColliders.ContainsKey(avatarHash))
{
if (NDBConfig.avatarsToAddColliders[avatarHash]) // If enabled
{
NDBConfig.avatarsToAddColliders[avatarHash] = false; //Change to Disable
}
else NDBConfig.avatarsToAddColliders.Remove(avatarHash); //Change to N/A
}
else NDBConfig.avatarsToAddColliders.Add(avatarHash, true); //Change to Enable
NDB.otherAvatarButtonList["HandColliders"].GetComponentInChildren<Text>().text = HandCollidersText();
//MelonPreferences.SetEntryValue<string>("NDB", "AvatarsToAddColliders", string.Join("; ", NDBConfig.avatarsToAddColliders.Select(p => string.Format("{0}, {1}", p.Key, p.Value))));
//SaveListFiles();
try { VRCPlayer.Method_Public_Static_Void_APIUser_0(selectedPlayer.prop_APIUser_0); } //Reload Avatar - Thanks loukylor - https://github.com/loukylor/VRC-Mods/blob/main/ReloadAvatars/ReloadAvatarsMod.cs
catch { } // Ignore
}, (button) => NDB.otherAvatarButtonList["HandColliders"] = button.transform);
if (useBigMenu) otherAvatarMenu.AddSimpleButton("Close", () => otherAvatarMenu.Hide());
otherAvatarMenu.Show();
}
private void MultiReplaceRadiusMenu(Player selectedPlayer, bool useBigMenu, string avatarName, string aviID, string avatarHash)
{
ICustomShowableLayoutedMenu mrrMenu = null;
mrrMenu = useBigMenu ? ExpansionKitApi.CreateCustomFullMenuPopup(LayoutDescription.WideSlimList) : ExpansionKitApi.CreateCustomQuickMenuPage(LayoutDescriptionCustom.QuickMenu1Column11Row);
mrrMenu.AddLabel("Adjust avatar's DB radius based on a Multiplier or replace entirely");
mrrMenu.AddLabel(CurrentText(), (button) => NDB.otherAvatarButtonList["Current"] = button.transform);
//
string CurrentText()
{
return $"Currently: {(NDBConfig.avatarsToAdjustDBRadius.ContainsKey(avatarHash) ? (NDBConfig.avatarsToAdjustDBRadius[avatarHash] == -2 ? "Excluded" : (NDBConfig.avatarsToAdjustDBRadius[avatarHash] == 0 ? $"Replacing" : $"Multiplied by {(float)NDBConfig.avatarsToAdjustDBRadius[avatarHash] / 10f}")) : "N/A")}";
}
void RadiusButtonEnd()
{
NDB.otherAvatarButtonList["Current"].GetComponentInChildren<Text>().text = CurrentText();
//SaveListFiles();
if (enabled) { RestoreOriginalColliderList(); AddAllCollidersToAllPlayers(); }
}
mrrMenu.AddSimpleButton($"Multiplier+", (() =>
{
if (!NDBConfig.avatarsToAdjustDBRadius.ContainsKey(avatarHash)) NDBConfig.avatarsToAdjustDBRadius.Add(avatarHash, 11);
else if (NDBConfig.avatarsToAdjustDBRadius[avatarHash] == 0) NDBConfig.avatarsToAdjustDBRadius[avatarHash] = 11; //If currently replacing switch to x1+1
else NDBConfig.avatarsToAdjustDBRadius[avatarHash] += 1;
RadiusButtonEnd();
}));
mrrMenu.AddSimpleButton($"Multiplier-", (() =>
{
if (!NDBConfig.avatarsToAdjustDBRadius.ContainsKey(avatarHash)) NDBConfig.avatarsToAdjustDBRadius.Add(avatarHash, 9);
else if (NDBConfig.avatarsToAdjustDBRadius[avatarHash] >= 2) NDBConfig.avatarsToAdjustDBRadius[avatarHash] -= 1; //Avoid 0
else if (NDBConfig.avatarsToAdjustDBRadius[avatarHash] == 0) NDBConfig.avatarsToAdjustDBRadius[avatarHash] = 9; //If currently replacing switch to x1-1
RadiusButtonEnd();
}));
mrrMenu.AddSimpleButton($"Replace DB Radius", (() =>
{
if (!NDBConfig.avatarsToAdjustDBRadius.ContainsKey(avatarHash)) NDBConfig.avatarsToAdjustDBRadius.Add(avatarHash, 0);
else NDBConfig.avatarsToAdjustDBRadius[avatarHash] = 0;
RadiusButtonEnd();
}));
//if (NDBConfig.adjustRadiusForAllZeroBones)
//{
mrrMenu.AddSimpleButton("Exclude from Adjusting All Zero Radius Bones", () =>
{
if (!NDBConfig.avatarsToAdjustDBRadius.ContainsKey(avatarHash)) NDBConfig.avatarsToAdjustDBRadius.Add(avatarHash, -2);
else NDBConfig.avatarsToAdjustDBRadius[avatarHash] = -2;
RadiusButtonEnd();
});
mrrMenu.AddLabel("^Exclude the selected avatar from being adjusted by 'Replace DB radius: Adjust All Zero Radius Bones' in Mod Settings");
//}
mrrMenu.AddSimpleButton("Remove Multiplier/Replace/Exclude", () =>
{
if (NDBConfig.avatarsToAdjustDBRadius.ContainsKey(avatarHash))
{
NDBConfig.avatarsToAdjustDBRadius.Remove(avatarHash);
RadiusButtonEnd();
}
});
mrrMenu.AddSimpleButton("<--Back", () => { mrrMenu.Hide(); AvatarMenu(selectedPlayer, useBigMenu); });
mrrMenu.AddSimpleButton("--Close--", () => { mrrMenu.Hide(); });
mrrMenu.Show();
}
private void SettingsMenuMain()
{
var settingsMenu = ExpansionKitApi.CreateCustomQuickMenuPage(LayoutDescriptionCustom.QuickMenu3Column);
settingsMenu.AddLabel("\n\n MDB Settings");
settingsMenu.AddSimpleButton($"Press to {((enabled) ? "disable" : "enable")} Dynamic Bones mod", () =>
{
ToggleState();
settingsMenu.Hide(); settingsMenu = null; SettingsMenuMain();
});
settingsMenu.AddSimpleButton("Page 2", () =>
{
settingsMenu.Hide();
SettingsMenuTwo();
});//End Row 1
string[,] settings ={ {"OnlyMe", "Only I can interact with other bones\n"},
{"OnlyFriends", "Only friends and I can interact w/ eachother"},
{"OnlyHandColliders", "Only enable colliders in hands\n"},//End Row 2
{"OptimizeOnly", "Optimize bones, don't enable interaction"},
{"DisallowDesktoppers", "Desktopers's colliders and bones won't be multiplayer'd"},
{"OnlyDynamicBonesOnBreasts", "Only the breast bones will be multiplayer'd\n"},//End Row 3
{"EnableJustIfVisible", "Enable dynamic bones only if they are in view"},
{"DistanceDisable", "Disable bones if beyond a distance"},
{"MoarBones", "~MoarBones~"}};//End Row 4
for (int i = 0; i < settings.GetLength(0); i++)
{
if (settings[i, 0] == "") { settingsMenu.AddLabel(settings[i, 1]); continue; } //If desc is blank, then skip
string settingsName = settings[i, 0];
settingsMenu.AddToggleButton(settings[i, 1], (action) =>
{
MelonPreferences.SetEntryValue<bool>("NDB", settingsName, action); MelonPreferences.Save();
if (enabled) { RestoreOriginalColliderList(); AddAllCollidersToAllPlayers(); }
}
, () => MelonPreferences.GetEntryValue<bool>("NDB", settingsName));
}
settingsMenu.Show();
}
private void SettingsMenuTwo()
{
var settingsMenu = ExpansionKitApi.CreateCustomQuickMenuPage(LayoutDescriptionCustom.QuickMenu3Column);
settingsMenu.AddLabel("\n\n MDB Settings");
settingsMenu.AddSimpleButton($"Press to {((enabled) ? "disable" : "enable")} Dynamic Bones mod", () =>
{
ToggleState();
settingsMenu.Hide(); settingsMenu = null; SettingsMenuMain();
});
settingsMenu.AddSimpleButton("Page 1", () =>
{
settingsMenu.Hide();
SettingsMenuMain();
});//End Row 1
string[,] settings ={
{ "DestroyInsideCollider", "Destroy inside colliders\n"},
{ "DisallowInsideColliders", "Disallow inside colliders from being multiplayered"},
{ "ExcludeSpecificBones", "Exclude Specific Objects per avatar"},//End Row 1
{ "AddAutoCollidersAll","AutoAdd Hand Colliders to All (Require Avi Reload)" },
{ "DisableAllBones", "Disable All Bones"},
{ "IncludeSpecificBones", "Include Specific Objects per avatar"},//End Row 2
{ "InteractSelf", "Add your own colliders to yourself"},
{ "OthersInteractSelf", "Add others colliders to themselves"},
{ "", "<--\nThese can cause buggy interaction"}
};
for (int i = 0; i < settings.GetLength(0); i++)
{
if (settings[i, 0] == "") { settingsMenu.AddLabel(settings[i, 1]); continue; } //If desc is blank, then skip
string settingsName = settings[i, 0];
settingsMenu.AddToggleButton(settings[i, 1], (action) =>
{
MelonPreferences.SetEntryValue<bool>("NDB", settingsName, action); MelonPreferences.Save();
if (enabled) { RestoreOriginalColliderList(); AddAllCollidersToAllPlayers(); }
}
, () => MelonPreferences.GetEntryValue<bool>("NDB", settingsName));
}
settingsMenu.Show();
}
private void ShowBoneSpecificMenu(Player selectedPlayer, bool useBigMenu)
{
if (selectedPlayer is null) return;
NDB.specificButtonList.Clear(); //Clear list of buttons
DynamicBone[] boneList = avatarsInScene[selectedPlayer._vrcplayer.prop_String_0].Item3;
ICustomShowableLayoutedMenu boneSpecificMenu = null;
boneSpecificMenu = useBigMenu ? ExpansionKitApi.CreateCustomFullMenuPopup(LayoutDescription.WideSlimList) : ExpansionKitApi.CreateCustomQuickMenuPage(LayoutDescriptionCustom.QuickMenu1Column);
//string playerName = selectedPlayer.field_Private_APIUser_0.displayName;
string avatarName = selectedPlayer.prop_ApiAvatar_0.name;
string aviID = selectedPlayer.prop_VRCPlayer_0.prop_VRCAvatarManager_0.prop_ApiAvatar_0.id;
boneSpecificMenu.AddLabel($"Specificly Exclude/Include multiplayering bones on avatar:\n{avatarName}");
boneSpecificMenu.AddSimpleButton("<--Back", () => { boneSpecificMenu.Hide(); AvatarMenu(selectedPlayer, useBigMenu); });
foreach (var bone in boneList)
{
if (bone.m_Root is null || bone.m_Root.Equals(null)) continue;
try
{
string hashBone = avatarName.Substring(0, Math.Min(avatarName.Length, 20)) + ":" + String.Format("{0:X}", aviID.GetHashCode()).Substring(4) + ":db:" + bone.m_Root.name;
if (NDB.specificButtonList.ContainsKey(hashBone)) continue; //For the instance where a bone may have more than one db/dbc
NDB.specificButtonList.Add(hashBone, null);
string boneName = bone.m_Root.name; //To stop an NRE if the player leaves or switches when menu is open
boneSpecificMenu.AddSimpleButton($"{(NDBConfig.bonesToExclude.Contains(hashBone) ? "Excluded - " : (NDBConfig.bonesToInclude.Contains(hashBone) ? "Included - " : "N/A - "))} {boneName}", () =>
{
ToggleBoneSpecific(hashBone, boneName);
}, (button) => NDB.specificButtonList[hashBone] = button.transform);
}
catch (System.Exception ex) { LogDebug(ConsoleColor.DarkRed, $"Error in BoneList\n" + ex.ToString()); }
}
boneSpecificMenu.AddSimpleButton("Reload MDB/Apply Changes", () =>
{
if (enabled) //This is lazy
{ RestoreOriginalColliderList(); AddAllCollidersToAllPlayers(); }
else ToggleState();
});
boneSpecificMenu.AddSimpleButton("Debug: Print excluded to console", () => PrintBonesSpecific());
boneSpecificMenu.AddSimpleButton("Close", () => { boneSpecificMenu.Hide(); });
boneSpecificMenu.Show();
}
private void ToggleBoneSpecific(string hashBone, string boneName)
{
if (!NDBConfig.bonesToExclude.Contains(hashBone) && !NDBConfig.bonesToInclude.Contains(hashBone))
{
NDBConfig.bonesToExclude.Add(hashBone);
NDB.specificButtonList[hashBone].GetComponentInChildren<Text>().text = $"Excluded - {boneName}";
}
else if (NDBConfig.bonesToExclude.Contains(hashBone))
{
NDBConfig.bonesToExclude.Remove(hashBone);
NDBConfig.bonesToInclude.Add(hashBone);
NDB.specificButtonList[hashBone].GetComponentInChildren<Text>().text = $"Included - {boneName}";
}
else
{ //Removing both to ensure consistency
if (NDBConfig.bonesToExclude.Contains(hashBone)) NDBConfig.bonesToExclude.Remove(hashBone);
if (NDBConfig.bonesToInclude.Contains(hashBone)) NDBConfig.bonesToInclude.Remove(hashBone);
NDB.specificButtonList[hashBone].GetComponentInChildren<Text>().text = $"N/A - {boneName}";
}
}
private void ShowColliderSpecificMenu(Player selectedPlayer, bool useBigMenu)
{
if (selectedPlayer is null) return;
NDB.specificButtonList.Clear(); //Clear list of buttons
DynamicBoneCollider[] boneList = avatarsInScene[selectedPlayer._vrcplayer.prop_String_0].Item4;
ICustomShowableLayoutedMenu colliderSpecificMenu = null;
colliderSpecificMenu = useBigMenu ? ExpansionKitApi.CreateCustomFullMenuPopup(LayoutDescription.WideSlimList) : ExpansionKitApi.CreateCustomQuickMenuPage(LayoutDescriptionCustom.QuickMenu1Column);
//string playerName = selectedPlayer.field_Private_APIUser_0.displayName;
string avatarName = selectedPlayer.prop_ApiAvatar_0.name;
string aviID = selectedPlayer.prop_VRCPlayer_0.prop_VRCAvatarManager_0.prop_ApiAvatar_0.id;
colliderSpecificMenu.AddLabel($"Specificly Exclude/Include multiplayering colliders on avatar:\n{avatarName}");
colliderSpecificMenu.AddSimpleButton("<--Back", () => { colliderSpecificMenu.Hide(); AvatarMenu(selectedPlayer, useBigMenu); });
foreach (var bone in boneList)
{
if (bone.gameObject is null || bone.gameObject.Equals(null)) continue;
try
{
string hashBone = avatarName.Substring(0, Math.Min(avatarName.Length, 20)) + ":" + String.Format("{0:X}", aviID.GetHashCode()).Substring(4) + ":dbc:" + bone.name;
if (NDB.specificButtonList.ContainsKey(hashBone)) continue; //For the instance where a bone may have more than one db/dbc
NDB.specificButtonList.Add(hashBone, null);
string boneName = bone.name; //To stop an NRE if the player leaves or switches when menu is open
colliderSpecificMenu.AddSimpleButton($"{((NDBConfig.collidersToExclude.Contains(hashBone)) ? "Excluded - " : (NDBConfig.collidersToInclude.Contains(hashBone) ? "Included - " : "N/A - "))} {boneName}", () =>
{
ToggleColliderSpecific(hashBone, boneName);
}, (button) => NDB.specificButtonList[hashBone] = button.transform);
}
catch (System.Exception ex) { LogDebug(ConsoleColor.DarkRed, $"Error in ColliderList\n" + ex.ToString()); }
}
colliderSpecificMenu.AddSimpleButton("Reload MDB/Apply Changes", () =>
{
if (enabled) //This is lazy
{ RestoreOriginalColliderList(); AddAllCollidersToAllPlayers(); }
else ToggleState();
});
colliderSpecificMenu.AddSimpleButton("Debug: Print excluded to console", () => PrintBonesSpecific());
colliderSpecificMenu.AddSimpleButton("Close", () => { colliderSpecificMenu.Hide(); });
colliderSpecificMenu.Show();
}
private void ToggleColliderSpecific(string hashBone, string boneName)
{
if (!NDBConfig.collidersToExclude.Contains(hashBone) && !NDBConfig.collidersToInclude.Contains(hashBone))
{
NDBConfig.collidersToExclude.Add(hashBone);
NDB.specificButtonList[hashBone].GetComponentInChildren<Text>().text = $"Excluded - {boneName}";
}
else if (NDBConfig.collidersToExclude.Contains(hashBone))
{
NDBConfig.collidersToExclude.Remove(hashBone);
NDBConfig.collidersToInclude.Add(hashBone);
NDB.specificButtonList[hashBone].GetComponentInChildren<Text>().text = $"Included - {boneName}";
}
else
{ //Removing both to ensure consistency
if (NDBConfig.collidersToExclude.Contains(hashBone)) NDBConfig.collidersToExclude.Remove(hashBone);
if (NDBConfig.collidersToInclude.Contains(hashBone)) NDBConfig.collidersToInclude.Remove(hashBone);
NDB.specificButtonList[hashBone].GetComponentInChildren<Text>().text = $"N/A - {boneName}";
}
}
private void PrintBonesSpecific()
{
if (!enabled) { LogDebug(ConsoleColor.Cyan, $"DBM is disabled, nothing can be excluded"); return; }
if (NDBConfig.onlyOptimize) { LogDebug(ConsoleColor.Cyan, $"DBM is set to only optimized bones, nothing can be excluded"); return; }
LogDebug(ConsoleColor.Cyan, $"Printing Specificly Excluded DynamicBones and DynamicBoneColliders");
if (NDB.bonesExcluded != null && NDB.bonesExcluded.Count > 0)
{
List<string> templist = NDB.bonesExcluded.ToList<string>(); templist.Sort();
foreach (string excludedBone in templist) LogDebug( ConsoleColor.Cyan, $"db - {excludedBone}");
}
else LogDebug(ConsoleColor.Cyan, $"No bones excluded");
if (NDB.collidersExcluded != null && NDB.collidersExcluded.Count > 0)
{
List<string> templist = NDB.collidersExcluded.ToList<string>(); templist.Sort();
foreach (string excludedColliders in templist) LogDebug( ConsoleColor.Cyan, $"dbc - {excludedColliders}");
}
else LogDebug(ConsoleColor.Cyan, $"No colliders excluded");
LogDebug( ConsoleColor.Cyan, $"Printing Specificly Included DynamicBones and DynamicBoneColliders");
if (NDB.bonesIncluded != null && NDB.bonesIncluded.Count > 0)
{
List<string> templist = NDB.bonesIncluded.ToList<string>(); templist.Sort();
foreach (string includedBones in templist) LogDebug( ConsoleColor.Cyan, $"db - {includedBones}");
}
else LogDebug(ConsoleColor.Cyan, $"No bones included");
if (NDB.collidersIncluded != null && NDB.collidersIncluded.Count > 0)
{
List<string> templist = NDB.collidersIncluded.ToList<string>(); templist.Sort();
foreach (string includedColliders in templist) LogDebug(ConsoleColor.Cyan, $"dbc - {includedColliders}");
}
else LogDebug(ConsoleColor.Cyan, $"No colliders included");
}
private void CheckForUpdates()
{
try
{
string url = "https://raw.githubusercontent.com/9E4ECDDE/MultiplayerDynamicBonesMod/master/updateCheck";
WebClient client = new WebClient();
string updateCheckString = client.DownloadString(url);
if (float.Parse(updateCheckString) > float.Parse(NDB.VERSION_STR))
{
LogDebug(ConsoleColor.Green, $"New version found - Creating MessageBox to notify user. Local:{NDB.VERSION_STR} Remote:{updateCheckString}");
if (MessageBox(IntPtr.Zero, "There is an update avaiable for Multiplayer Dynamic Bones. Not updating could result in the mod not working or the game crashing. Do you want to launch the internet browser?", "Multiplayer Dynamic Bones Mod", 0x04 | 0x40 | 0x1000) == 6)
{
Process.Start("https://github.com/9E4ECDDE/MultiplayerDynamicBonesMod/releases");
MessageBox(IntPtr.Zero, "Please replace the file and restart VRChat for the update to apply", "Multiplayer Dynamic Bones Mod", 0x40 | 0x1000);
}
}
else LogDebugInt(1, ConsoleColor.DarkGreen, $"No Update Found. Local:{NDB.VERSION_STR} Remote:{updateCheckString}");
}
catch (Exception ex) { LogDebugError($"Update check error " + ex.ToString()); return; }
}
private void MoarBoneCheck()
{
try
{ //Change this next time to disable MoarBones if No is clicked - Add more explaination to what this does and how to disable.
LogDebug( ConsoleColor.Green, $"It is 4/1 - Checking if user wants to enable this feature");
if (MessageBox(IntPtr.Zero, "There is a new feature for Multiplayer Dynamic Bones! Do you want to enable it? \nYou can disable it later in Mod Settings: Moarbones", "Multiplayer Dynamic Bones Mod", 0x04 | 0x40 | 0x1000) == 6)
{
LogDebug( ConsoleColor.Magenta, $"~~~~~~~~~~~~~~~Moarbones Enabled~~~~~~~~~~~~~~~");
LogDebug( ConsoleColor.Magenta, $"THIS CAN BE DISABLED IN MOD SETTINGS - MOARBONES");
MelonPreferences.SetEntryValue<bool>("NDB", "MoarBones", true);
NDBConfig.moarBones = true;
}
}
catch (Exception ex) { LogDebugError(ex.ToString()); return; }
}
private static unsafe void RegisterModPrefs()
{
MelonPreferences.CreateCategory("NDB", "Multiplayer Dynamic Bones");
MelonPreferences.CreateEntry<bool>("NDB", "EnabledByDefault", true, "Enabled by default");
MelonPreferences.CreateEntry<bool>("NDB", "OptimizeOnly", false, "Optimize bones, don't enable interaction [QM]");
//What gets Mutliplayered?
MelonPreferences.CreateEntry<bool>("NDB", "OnlyMe", false, "Only I can interact with other bones [QM]");
MelonPreferences.CreateEntry<bool>("NDB", "OnlyFriends", false, "Only friends and I can interact w/ eachothers bones [QM]");
MelonPreferences.CreateEntry<bool>("NDB", "DisallowDesktoppers", false, "Desktopers's colliders and bones won't be multiplayer'd [QM]");
MelonPreferences.CreateEntry<bool>("NDB", "OnlyHandColliders", false, "Only enable colliders in hands [QM]");
MelonPreferences.CreateEntry<bool>("NDB", "OnlyDynamicBonesOnBreasts", false, "Only the breast bones will be multiplayer'd [QM]");
MelonPreferences.CreateEntry<bool>("NDB", "InteractSelf", false, "Add your colliders to your own bones (May cause buggy interactions) [QM]");
MelonPreferences.CreateEntry<bool>("NDB", "OthersInteractSelf", false, "Add other avatar's colliders to their own bones (May cause buggy interactions) [QM]");
MelonPreferences.CreateEntry<bool>("NDB", "AddAutoCollidersAll", false, "Auto add hand colliders to avatars that don't have them (Requires reload of avatar) [QM]");
MelonPreferences.CreateEntry<bool>("NDB", "ExcludeSpecificBones", true, "Exclude Specific Bones or Colliders from being Multiplayered[QM]");
MelonPreferences.CreateEntry<bool>("NDB", "IncludeSpecificBones", true, "Include Specific Bones or Colliders to be Multiplayered[QM]");
//Bone settings
MelonPreferences.CreateEntry<bool>("NDB", "DistanceDisable", true, "Disable bones if beyond a distance [QM]");
MelonPreferences.CreateEntry<float>("NDB", "DistanceToDisable", 4f, "Distance limit");
MelonPreferences.CreateEntry<bool>("NDB", "DisallowInsideColliders", true, "Disallow inside colliders from being multiplayered (Default Enabled) [QM]");
MelonPreferences.CreateEntry<bool>("NDB", "DestroyInsideColliders", false, "Destroy inside colliders (Requires reload of avatar) [QM]");
MelonPreferences.CreateEntry<float>("NDB", "ColliderSizeLimit", 1f, "Collider size limit ");
MelonPreferences.CreateEntry<int>("NDB", "DynamicBoneUpdateRate", 60, "Dynamic bone update rate");
MelonPreferences.CreateEntry<bool>("NDB", "DynamicBoneUpdateRateAdjSettings", true, "Adjust bone properties in a ratio from update rate change");
MelonPreferences.CreateEntry<bool>("NDB", "EnableJustIfVisible", true, "Enable dynamic bones only if they are in visible [QM]");
MelonPreferences.CreateEntry<float>("NDB", "VisibilityUpdateRate", 1f, "Visibility update rate (seconds)");
MelonPreferences.CreateEntry<int>("NDB", "BoneRadiusDivisor", 4, "Replace DB radius: Divisor - New Radius = BoneLegnth / ThisValue");
MelonPreferences.CreateEntry<float>("NDB", "EndBoneRadius", 0.05f, "Replace DB radius: This is the fallback radius if the calculated value is 0");
MelonPreferences.CreateEntry<bool>("NDB", "AdjustRadiusExcludeZero", false, "Replace DB radius: Excludes bone with a radius of 0 from being changed");
MelonPreferences.CreateEntry<bool>("NDB", "AdjustRadiusForAllZeroBones", false, "Replace DB radius: Adjust All Zero Radius Bones - Replace the radius for all bones with a radius of 0 on all avatars");
MelonPreferences.CreateEntry<bool>("NDB", "DisableAllBones", false, "Disable all Dynamic Bones in Scene [QM]");
//Mod settings
MelonPreferences.CreateEntry<bool>("NDB", "KeybindsEnabled", true, "Enable keyboard actuation(F1, F4 and F8)");
MelonPreferences.CreateEntry<int>("NDB", "UpdateMode", 2, "A value of 2 will notify the user when a new version of the mod is available, while 1 will not.");
MelonPreferences.CreateEntry<bool>("NDB", "EnableEditor", false, "EnableEditor (F5)");
//MelonPreferences.CreateEntry<bool>("NDB", "EnableUserPanelButton-AvatarsExclude", true, "Enable the button that allows per-avatar dynamic bones enable or disable (Restart Req)");
//MelonPreferences.CreateEntry<int>("NDB", "UserPanelButtonX", 0, "X offset for the user panel button (Restart Req - Default:0)");
//MelonPreferences.CreateEntry<int>("NDB", "UserPanelButtonY", -1, "Y offset for the user panel button (Restart Req - Default:-1)");
MelonPreferences.CreateEntry<int>("NDB", "QuickMenuButton", 1, "Quick Menu Button - 1:Settings Menu, 2:Just Toggle, 0:None (Restart Req)");
MelonPreferences.CreateEntry<string>("NDB", "LogLevelS", "0", "Console Logging Level:"); // 1-Just info, 2-Limited to once per avatar or behind a filter IF, 3-Filters/Logs in 1st Level Loops, 4-Filters/Logs in 2nd+ Level Loops , 5-Extra Debug Lines
ExpansionKitApi.RegisterSettingAsStringEnum("NDB", "LogLevelS", new[] { ("0", "Default"), ("1", "Info"), ("2", "Debug"), ("3", "Debug Loops"), ("4", "Debug Deep Loops(Very laggy)"), ("5", "All Possible(Very laggy)"), ("-1", "Silent Mode") });
MelonPreferences.CreateEntry<string>("NDB", "DebugLogs", "0", "DebugLog - Writes a seperate Debug log to disk");
ExpansionKitApi.RegisterSettingAsStringEnum("NDB", "DebugLogs", new[] { ("0", "Off"), ("1", "Info"), ("2", "Debug"), ("3", "Debug Loops"), ("4", "Debug Deep Loops(Laggy)"), ("5", "All Possible(Laggy)") });
MelonPreferences.CreateEntry<bool>("NDB", "MoarBones", false, "MoarBones: I hear you like bones~ (Makes all bones Dynamic)");
MelonPreferences.CreateEntry<bool>("NDB", "MoarBonesPref", true, "MoarBones: Performance Limit");
MelonPreferences.CreateEntry<bool>("NDB", "MoarBonesNotLocal", true, "MoarBones: Don't effect local avatar");
//Change to use this at one point
//ExpansionKitApi.RegisterSettingAsStringEnum("NDB", "QuickMenuButton", new[] { ("0", "Disable Trust Colours"), ("friends", "Trust Colours (with friend colour)"), ("trustonly", "Trust Colours (Ignore friend colour)"), ("trustname", "Trust Colours on Names Only") });
//MelonPreferences.CreateEntry<int>("NDB", "removeme", 0, "removeme"); // 1-Just info, 2-Limited to once per avatar or behind a filter IF, 3-Spammy stuff in loops
//Not shown
//MelonPreferences.CreateEntry<bool>("NDB", "HasShownCompatibilityIssueMessage", false, null, true);
MelonPreferences.CreateEntry<string>("NDB", "AvatarsToWhichNotApply", "", null, true);
MelonPreferences.CreateEntry<string>("NDB", "BonesToExclude", "", null, true);
MelonPreferences.CreateEntry<string>("NDB", "CollidersToExclude", "", null, true);
MelonPreferences.CreateEntry<string>("NDB", "BonesToAlwaysExclude", "Left Z_Wing_Bone_3;Left Z_Wing_Bone_2;Left Z_Wing_Bone_1;Right Z_Wing_Bone_3;Right Z_Wing_Bone_2;Right Z_Wing_Bone_1", null, true);
MelonPreferences.CreateEntry<string>("NDB", "AvatarsToAdjustDBRadius", "", null, true);
MelonPreferences.CreateEntry<string>("NDB", "AvatarsToAddColliders", "", null, true);
MelonPreferences.CreateEntry<string>("NDB", "BonesToInclude", "", null, true);
MelonPreferences.CreateEntry<string>("NDB", "CollidersToInclude", "", null, true);
}
private static int scenesLoaded;
public override void OnSceneWasLoaded(int buildIndex, string sceneName)
{
scenesLoaded++;
if (scenesLoaded == 2)
HookCallbackFunctions();
}
private unsafe void HookCallbackFunctions()
{
bool isPlayerEventAdded1 = false;
bool isPlayerEventAdded2 = false;
try
{
//Todo, make this use VRCUK if it is installed so I can be more lazy
MethodBase funcToHook = typeof(VRCAvatarManager).GetMethods().First(mb => mb.Name.StartsWith("Method_Private_Boolean_ApiAvatar_GameObject_")); //Thanks to loukylor
onAvatarInstantiatedPatch = HarmonyInstance.Patch(funcToHook, null, new HarmonyMethod(typeof(NDB).GetMethod(nameof(OnAvatarInstantiated), BindingFlags.NonPublic | BindingFlags.Static)));
LogDebug(ConsoleColor.Blue, $"Hooked OnAvatarInstantiated? {((onAvatarInstantiatedPatch != null) ? "Yes!" : "No: critical error!!")}");
onJoinedRoomPatch = HarmonyInstance.Patch(typeof(NetworkManager).GetMethods().Single((fi) => fi.Name.Contains("OnJoinedRoom")), new HarmonyMethod(typeof(NDB).GetMethod(nameof(Reset))));
LogDebug(ConsoleColor.Blue, $"Patched OnJoinedRoom? {((onJoinedRoomPatch != null) ? "Yes!" : "No: critical error!!")}");
AddToDelegate(NetworkManager.field_Internal_Static_NetworkManager_0.field_Internal_VRCEventDelegate_1_Player_0, EventA);
isPlayerEventAdded1 = true;
LogDebug(ConsoleColor.Blue, $"Added Delegate for Player Event (1/2)? {((isPlayerEventAdded1) ? "Yes!" : "No: critical error!!")}");
AddToDelegate(NetworkManager.field_Internal_Static_NetworkManager_0.field_Internal_VRCEventDelegate_1_Player_1, EventB);
isPlayerEventAdded2 = true;
LogDebug(ConsoleColor.Blue, $"Added Delegate for Player Event (2/2)? {((isPlayerEventAdded2) ? "Yes!" : "No: critical error!!")}");
}
catch (Exception ex) { LogDebugError(ex.ToString()); return; }
finally
{
if (onAvatarInstantiatedPatch == null || onJoinedRoomPatch == null || !isPlayerEventAdded1 || !isPlayerEventAdded2 || !HookLIC)
{
this.enabled = false;
LogDebugError("Multiplayer Dynamic Bones mod suffered a critical error! Mod version may be obsolete.");
}
}
LogDebug(ConsoleColor.Green, $"NDBMod is {((enabled == true) ? "enabled" : "disabled")}");
}
private static void AddToDelegate(VRCEventDelegate<Player> theDelegate, Action<Player> theEvent)
{
theDelegate.field_Private_HashSet_1_UnityAction_1_T_0.Add(theEvent);
}
private enum SeenFirst
{
None,
A,
B
}
private static SeenFirst seenFirst = SeenFirst.None;
public static void EventA(Player player)
{
if (seenFirst == SeenFirst.None)
seenFirst = SeenFirst.A;
if (player == null)
return;
if (seenFirst == SeenFirst.A)
OnPlayerJoin(player);
else
OnPlayerLeave(player);
}
public static void EventB(Player player)
{
if (seenFirst == SeenFirst.None)
seenFirst = SeenFirst.B;
if (player == null)
return;
if (seenFirst == SeenFirst.B)
OnPlayerJoin(player);
else
OnPlayerLeave(player);
}
private static void OnPlayerJoin(Player player)
{
//MelonLogger.Msg(ConsoleColor.Blue, $"{player.prop_APIUser_0?.displayName} Joined");
}
private static void OnPlayerLeave(Player player)
{
//MelonLogger.Msg(ConsoleColor.Blue, $"{player.prop_APIUser_0?.displayName} Left");
OnPlayerLeft(player);
}
public void LogLevelWarning(int loglvl)
{
if (loglvl >= 3) LogDebug(ConsoleColor.Magenta, $"Log level set to debug extra (3+), this will spam the console a lot and will cause lag. \n ======================== Disable this unless you are actively trying to debug something ======================== \n ======================== Disable this unless you are actively trying to debug something ========================");
else if (loglvl == 2) LogDebug(ConsoleColor.Magenta, $"Log level set to debug (2), this is mostly limited to once per avatar items or if(s) that get met.");
else if (loglvl == 1) LogDebug(ConsoleColor.Yellow, $"Log level set to info (1).");
else if (loglvl == -1) LogDebug(ConsoleColor.Yellow, $"Log level set to silent mode (-1). \n ======================== No Add/Leave Log Messages Will Print ======================== \n");
}
public override void OnPreferencesSaved()
{
int loglvl = 0;
try { loglvl = int.Parse(MelonPreferences.GetEntryValue<string>("NDB", "LogLevelS")); }
catch { LogDebug( ConsoleColor.Yellow, $"Log level value is invalid"); }
if (NDBConfig.logLevel != loglvl) LogLevelWarning(loglvl); //If settings changed, send warning
if (!firstrun && MelonPreferences.GetEntryValue<bool>("NDB", "MoarBones") != NDBConfig.moarBones)
{
LogDebug( ConsoleColor.Magenta, "MoarBones State Changed, Reload All Avatars");
moarbonesCount = 0;
try
{ // Reload All Avatar - Thanks loukylor - https://github.com/loukylor/VRC-Mods/blob/main/ReloadAvatars/ReloadAvatarsMod.cs
MethodInfo reloadAllAvatarsMethod = typeof(VRCPlayer).GetMethods().First(mi => mi.Name.StartsWith("Method_Public_Void_Boolean_") && mi.Name.Length < 30 && mi.GetParameters().All(pi => pi.HasDefaultValue ));// Both methods seem to do the same thing
reloadAllAvatarsMethod.Invoke(VRCPlayer.field_Internal_Static_VRCPlayer_0, new object[] { null });
//VRCPlayer.field_Internal_Static_VRCPlayer_0.Method_Public_Void_Boolean_0();
}
catch { LogDebugError("Failed to reload all avatars - You will have to rejoin the world - Check for a newer version of this mod or report this bug"); } // Ignore
}
NDBConfig.enabledByDefault = MelonPreferences.GetEntryValue<bool>("NDB", "EnabledByDefault");
NDBConfig.disallowInsideColliders = MelonPreferences.GetEntryValue<bool>("NDB", "DisallowInsideColliders");
NDBConfig.destroyInsideColliders = MelonPreferences.GetEntryValue<bool>("NDB", "DestroyInsideColliders");
NDBConfig.distanceToDisable = MelonPreferences.GetEntryValue<float>("NDB", "DistanceToDisable");
NDBConfig.distanceDisable = MelonPreferences.GetEntryValue<bool>("NDB", "DistanceDisable");
NDBConfig.colliderSizeLimit = MelonPreferences.GetEntryValue<float>("NDB", "ColliderSizeLimit");
NDBConfig.onlyForMyBones = MelonPreferences.GetEntryValue<bool>("NDB", "OnlyMe");
NDBConfig.onlyForMeAndFriends = MelonPreferences.GetEntryValue<bool>("NDB", "OnlyFriends");
NDBConfig.dynamicBoneUpdateRate = MelonPreferences.GetEntryValue<int>("NDB", "DynamicBoneUpdateRate");
NDBConfig.dynamicBoneUpdateRateAdjSettings = MelonPreferences.GetEntryValue<bool>("NDB", "DynamicBoneUpdateRateAdjSettings");
NDBConfig.disallowDesktoppers = MelonPreferences.GetEntryValue<bool>("NDB", "DisallowDesktoppers");
NDBConfig.enableBoundsCheck = MelonPreferences.GetEntryValue<bool>("NDB", "EnableJustIfVisible");
NDBConfig.visiblityUpdateRate = MelonPreferences.GetEntryValue<float>("NDB", "VisibilityUpdateRate");
NDBConfig.onlyHandColliders = MelonPreferences.GetEntryValue<bool>("NDB", "OnlyHandColliders");
NDBConfig.keybindsEnabled = MelonPreferences.GetEntryValue<bool>("NDB", "KeybindsEnabled");
NDBConfig.onlyOptimize = MelonPreferences.GetEntryValue<bool>("NDB", "OptimizeOnly");
NDBConfig.updateMode = MelonPreferences.GetEntryValue<int>("NDB", "UpdateMode");
//NDBConfig.hasShownCompatibilityIssueMessage = MelonPreferences.GetEntryValue<bool>("NDB", "HasShownCompatibilityIssueMessage");
NDBConfig.enableEditor = MelonPreferences.GetEntryValue<bool>("NDB", "EnableEditor");
NDBConfig.breastsOnly = MelonPreferences.GetEntryValue<bool>("NDB", "OnlyDynamicBonesOnBreasts");
//NDBConfig.enableUserPanelButton = MelonPreferences.GetEntryValue<bool>("NDB", "EnableUserPanelButton-AvatarsExclude");
//NDBConfig.userPanelButtonX = MelonPreferences.GetEntryValue<int>("NDB", "UserPanelButtonX");
//NDBConfig.userPanelButtonY = MelonPreferences.GetEntryValue<int>("NDB", "UserPanelButtonY");
NDBConfig.excludeSpecificBones = MelonPreferences.GetEntryValue<bool>("NDB", "ExcludeSpecificBones");
NDBConfig.includeSpecificBones = MelonPreferences.GetEntryValue<bool>("NDB", "IncludeSpecificBones");
NDBConfig.interactSelf = MelonPreferences.GetEntryValue<bool>("NDB", "InteractSelf");
NDBConfig.othersInteractSelf = MelonPreferences.GetEntryValue<bool>("NDB", "OthersInteractSelf");
NDBConfig.boneRadiusDivisor = MelonPreferences.GetEntryValue<int>("NDB", "BoneRadiusDivisor");
NDBConfig.endBoneRadius = MelonPreferences.GetEntryValue<float>("NDB", "EndBoneRadius");
NDBConfig.addAutoCollidersAll = MelonPreferences.GetEntryValue<bool>("NDB", "AddAutoCollidersAll");
NDBConfig.adjustRadiusExcludeZero = MelonPreferences.GetEntryValue<bool>("NDB", "AdjustRadiusExcludeZero");
NDBConfig.adjustRadiusForAllZeroBones = MelonPreferences.GetEntryValue<bool>("NDB", "AdjustRadiusForAllZeroBones");
NDBConfig.disableAllBones = MelonPreferences.GetEntryValue<bool>("NDB", "DisableAllBones");
NDBConfig.moarBones = MelonPreferences.GetEntryValue<bool>("NDB", "MoarBones");
NDBConfig.moarBonesPrefLimit = MelonPreferences.GetEntryValue<bool>("NDB", "MoarBonesPref");
NDBConfig.moarBonesNotLocal = MelonPreferences.GetEntryValue<bool>("NDB", "MoarBonesNotLocal");
NDBConfig.logLevel = loglvl;
try { NDBConfig.debugLog = int.Parse(MelonPreferences.GetEntryValue<string>("NDB", "DebugLogs")); }
catch { LogDebug(ConsoleColor.Yellow, $"Debug Log level value is invalid"); NDBConfig.debugLog = 0; }
if (NDBConfig.debugLog > 0) InitDebugLog();
SaveListFiles();
}
private void InitFileLists()
{
if (!Directory.Exists("UserData/MDB")) Directory.CreateDirectory("UserData/MDB");
if (!File.Exists(AvatarsToWhichNotApplyPath)) File.WriteAllText(AvatarsToWhichNotApplyPath, "", Encoding.UTF8);
if (!File.Exists(BonesToExcludePath)) File.WriteAllText(BonesToExcludePath, "", Encoding.UTF8);
if (!File.Exists(CollidersToExcludePath)) File.WriteAllText(CollidersToExcludePath, "", Encoding.UTF8);
if (!File.Exists(BonesToAlwaysExcludePath)) File.WriteAllText(BonesToAlwaysExcludePath, "", Encoding.UTF8);
if (!File.Exists(AvatarsToAdjustDBRadiusPath)) File.WriteAllText(AvatarsToAdjustDBRadiusPath, "", Encoding.UTF8);
if (!File.Exists(AvatarsToAddCollidersPath)) File.WriteAllText(AvatarsToAddCollidersPath, "", Encoding.UTF8);
if (!File.Exists(BonesToIncludePath)) File.WriteAllText(BonesToIncludePath, "", Encoding.UTF8);
if (!File.Exists(CollidersToIncludePath)) File.WriteAllText(CollidersToIncludePath, "", Encoding.UTF8);
//MigrateOrLoadHashSet("AvatarsToWhichNotApply", AvatarsToWhichNotApplyPath, ref NDBConfig.avatarsToWhichNotApply);
MigrateOrLoadHashSet("BonesToExclude", BonesToExcludePath, ref NDBConfig.bonesToExclude);
MigrateOrLoadHashSet("CollidersToExclude", CollidersToExcludePath, ref NDBConfig.collidersToExclude);
MigrateOrLoadHashSet("BonesToAlwaysExclude", BonesToAlwaysExcludePath, ref NDBConfig.bonesToAlwaysExclude);
MigrateOrLoadHashSet("BonesToInclude", BonesToIncludePath, ref NDBConfig.bonesToInclude);
MigrateOrLoadHashSet("CollidersToInclude", CollidersToIncludePath, ref NDBConfig.collidersToInclude);
var migrated = false;
try
{
if (MelonPreferences.GetEntryValue<string>("NDB", "AvatarsToWhichNotApply") != "")
{//If modprefs has value, then convert into standlone file
if (IsTextFileEmpty(AvatarsToWhichNotApplyPath))
{//Check if file already had content, if so, abort and error
var temp = new HashSet<string>(MelonPreferences.GetEntryValue<string>("NDB", "AvatarsToWhichNotApply").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
NDBConfig.avatarsToWhichNotApply = new Dictionary<string, bool>();
foreach (var value in temp)
{//Switching from just a list of values to togglable Enable/Disable/NA
NDBConfig.avatarsToWhichNotApply.Add(value, true);
}
File.WriteAllLines(AvatarsToWhichNotApplyPath, NDBConfig.avatarsToWhichNotApply.Select(p => string.Format("{0}, {1}", p.Key, p.Value)), Encoding.UTF8); //Save file
MelonPreferences.SetEntryValue<string>("NDB", "AvatarsToWhichNotApply", "");
migrated = true;
LogDebug(ConsoleColor.Blue, "Migrated from MelonPreferences to " + AvatarsToWhichNotApplyPath);
}
else LogDebug(ConsoleColor.Red, "MelonPreferences has content but " + AvatarsToWhichNotApplyPath + " is not empty. Can not migrate records. ");
}
if (!IsTextFileEmpty(AvatarsToWhichNotApplyPath))
{
if (!migrated)
{
NDBConfig.avatarsToWhichNotApply = new Dictionary<string, bool>(File.ReadAllLines(AvatarsToWhichNotApplyPath).Select(s => s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).Where(x => x.Length == 2).ToDictionary(p => p[0].Trim(), p => bool.Parse(p[1].Trim())));
LogDebug(ConsoleColor.DarkBlue, "Loaded - " + AvatarsToWhichNotApplyPath);
}
}
else NDBConfig.avatarsToWhichNotApply = new Dictionary<string, bool>();
}
catch (Exception ex)
{
LogDebugError("Possible corrupted file: " + AvatarsToWhichNotApplyPath + " File will be renamed and new file created \n" + ex.ToString());
NDBConfig.avatarsToWhichNotApply = new Dictionary<string, bool>();
File.Move(AvatarsToWhichNotApplyPath, AvatarsToWhichNotApplyPath + DateTime.Now.ToString("yyyy'-'MM'-'dd'_'HH'-'mm'-'ss") + ".bkp");
}
//======
migrated = false;
try
{
if (MelonPreferences.GetEntryValue<string>("NDB", "AvatarsToAdjustDBRadius") != "")
{//If modprefs has value, then convert into standlone file
if (IsTextFileEmpty(AvatarsToAdjustDBRadiusPath))
{//Check if file already had content, if so, abort and error
NDBConfig.avatarsToAdjustDBRadius = new Dictionary<string, int>(MelonPreferences.GetEntryValue<string>("NDB", "AvatarsToAdjustDBRadius").Split(';').Select(s => s.Split(',')).ToDictionary(p => p[0].Trim(), p => Int32.Parse(p[1].Trim())));
File.WriteAllLines(AvatarsToAdjustDBRadiusPath, NDBConfig.avatarsToAdjustDBRadius.Select(p => string.Format("{0}, {1}", p.Key, p.Value)), Encoding.UTF8); //Save file
MelonPreferences.SetEntryValue<string>("NDB", "AvatarsToAdjustDBRadius", "");
migrated = true;
LogDebug(ConsoleColor.Blue, "Migrated from MelonPreferences to " + AvatarsToAdjustDBRadiusPath);
}
else LogDebug(ConsoleColor.Red, "MelonPreferences has content but " + AvatarsToAdjustDBRadiusPath + " is not empty. Can not migrate records. ");
}
if (!IsTextFileEmpty(AvatarsToAdjustDBRadiusPath))
{
if (!migrated)
{
NDBConfig.avatarsToAdjustDBRadius = new Dictionary<string, int>(File.ReadAllLines(AvatarsToAdjustDBRadiusPath).Select(s => s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).Where(x => x.Length == 2).ToDictionary(p => p[0].Trim(), p => Int32.Parse(p[1].Trim())));
LogDebug(ConsoleColor.DarkBlue, "Loaded - " + AvatarsToAdjustDBRadiusPath);
}
}
else NDBConfig.avatarsToAdjustDBRadius = new Dictionary<string, int>();
}
catch (Exception ex)
{
LogDebugError("Possible corrupted file: " + AvatarsToAdjustDBRadiusPath + " File will be renamed and new file created \n" + ex.ToString());
NDBConfig.avatarsToAdjustDBRadius = new Dictionary<string, int>();
File.Move(AvatarsToAdjustDBRadiusPath, AvatarsToAdjustDBRadiusPath + DateTime.Now.ToString("yyyy'-'MM'-'dd'_'HH'-'mm'-'ss") + ".bkp");
}
//======
migrated = false;
try
{
if (MelonPreferences.GetEntryValue<string>("NDB", "AvatarsToAddColliders") != "")
{//If modprefs has value, then convert into standlone file
if (IsTextFileEmpty(AvatarsToAddCollidersPath))
{//Check if file already had content, if so, abort and error
NDBConfig.avatarsToAddColliders = new Dictionary<string, bool>(MelonPreferences.GetEntryValue<string>("NDB", "AvatarsToAddColliders").Split(';').Select(s => s.Split(',')).ToDictionary(p => p[0].Trim(), p => bool.Parse(p[1].Trim())));
File.WriteAllLines(AvatarsToAddCollidersPath, NDBConfig.avatarsToAddColliders.Select(p => string.Format("{0}, {1}", p.Key, p.Value)), Encoding.UTF8); //Save file
MelonPreferences.SetEntryValue<string>("NDB", "AvatarsToAddColliders", "");
migrated = true;