forked from Dathuss/VRCFPatcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VrcfPatcher.cs
283 lines (233 loc) · 11.2 KB
/
VrcfPatcher.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
using UnityEngine;
using VRC.SDK3.Avatars.Components;
using VRC.SDK3.Avatars.ScriptableObjects;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Animations;
#if USE_VRCFURY
using System.Reflection;
using VF.Menu;
using VF.Model;
#endif
#endif
using HarmonyLib;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Object = UnityEngine.Object;
using Random = UnityEngine.Random;
// This class aims to hook to AssetDatabase.AddObjectToAsset to prevent VRCFury from making sub-assets
// which disrupts the way KannaProtecc works. Extracting the assets on KannaProtecc's side could
// have worked if only unity's asset database system wasn't fucked up when working with sub assets.
// And it's also faster this way
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
internal static class VrcfPatcher
{
private const string _patchName = "vrcfpatcher";
private const string menuPrefix = "Tools/VRCFury/KannaProtecc/";
private static readonly Harmony _harmony = new Harmony(_patchName);
#if UNITY_EDITOR && USE_VRCFURY
static VrcfPatcher()
{
Debug.Log("Patching AssetDatabase...");
var assetDBmethod = typeof(AssetDatabase).GetMethod("AddObjectToAsset", new Type[] { typeof(Object), typeof(Object) });
var assetDBPrefix = new HarmonyMethod(typeof(VrcfPatcher).GetMethod(nameof(AssetDBPrefix)));
_harmony.UnpatchAll(_patchName);
_harmony.Patch(assetDBmethod, prefix: assetDBPrefix);
Debug.Log("Patched !");
}
// Types that we don't want to be added as sub-assets
private static readonly Dictionary<Type, (string, string)> _typePrefixExtensionKV = new Dictionary<Type, (string, string)>()
{
{ typeof(VRCExpressionsMenu), ("menu", "asset") },
{ typeof(AnimationClip), ("anim", "anim") },
{ typeof(BlendTree), ("blend_tree", "asset") }
};
private static bool _isBuilding = false;
public static bool AssetDBPrefix(Object objectToAdd, Object assetObject)
{
if (_isBuilding && _typePrefixExtensionKV.ContainsKey(objectToAdd.GetType()))
{
var folderPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(assetObject));
(var prefix, var extension) = _typePrefixExtensionKV[objectToAdd.GetType()];
// We don't keep the original asset names because sometimes they contain characters that cannot be
// contained in a file name. Instead we give them a simple name with an automatically assigned index
var filePath = AssetDatabase.GenerateUniqueAssetPath($"{folderPath}/{prefix}_0.{extension}");
AssetDatabase.CreateAsset(objectToAdd, filePath);
return false;
}
return true;
}
[MenuItem(menuPrefix + "Build avatar", validate = true)]
private static bool CheckAvatarBuild() => GetSelectedAvatar() != null;
private static GameObject GetSelectedAvatarGameObject()
{
var VFavatar = GetSelectedAvatar();
var avatar = VFavatar.GetType().GetField("_gameObject", AccessTools.all).GetValue(VFavatar) as GameObject;
Debug.Log($"Found selected avatar GameObject: {avatar?.name ?? "Null"}");
return avatar;
}
private static object GetSelectedAvatar()
{
var getSelected = GetMenuUtils().GetMethod("GetSelectedAvatar", AccessTools.all);
Debug.Log($"Found GetSelectedAvatar: {getSelected.Name}");
var avatar = getSelected.Invoke(null, Array.Empty<object>());
Debug.Log($"Found selected avatar: {avatar?.GetType()?.Name ?? "Null"}");
return avatar;
}
private static Type GetMenuUtils()
{
var menuUtils = AppDomain.CurrentDomain.GetAssemblies().First(o => o.GetName().Name == "VRCFury-Editor").GetTypes().First(o => o.Namespace == "VF.Menu" && o.Name == "MenuUtils");
Debug.Log($"Found MenuUtils: {menuUtils.Namespace}.{menuUtils.Name}");
return menuUtils;
}
//private static bool CheckAvatarBuilds() => MenuUtils.GetSelectedAvatar() != null;
[MenuItem(menuPrefix + "Build avatar")]
private static void StartAvatarBuild()
{
GameObject originalObject;
object originalObjectVF;
try
{
_isBuilding = true;
originalObjectVF = GetSelectedAvatar();
originalObject = GetSelectedAvatarGameObject();
AppDomain.CurrentDomain.GetAssemblies().First(o => o.GetName().Name == "VRCFury-Editor").GetTypes().First(o => o.Namespace == "VF.Menu" && o.Name == "VRCFuryTestCopyMenuItem").GetMethod("BuildTestCopy", AccessTools.all).Invoke(null, new []{ originalObjectVF });
}
catch (Exception e)
{
Debug.LogError("An exception occured when building avatar. This shouldn't happen but oh well. Exception :");
Debug.LogException(e);
_isBuilding = false;
return;
}
_isBuilding = false;
try
{
var clone = GameObject.Find("VRCF Test Copy for " + originalObject.name);
if (clone == null) return;
if (clone.GetComponents<Component>().FirstOrDefault(o => o.GetType().Name == "VRCFuryTest") is var test && test != null)
{
Object.DestroyImmediate(test);
}
VRCAvatarDescriptor.CustomAnimLayer[] cloneLayers;
{
var cloneDescriptor = clone.GetComponent<VRCAvatarDescriptor>();
cloneLayers = cloneDescriptor.baseAnimationLayers.Concat(cloneDescriptor.specialAnimationLayers).ToArray();
}
AssetDatabase.Refresh();
var sourcePath = $"Packages\\com.vrcfury.temp\\" + originalObject.name + "_Clone_";
sourcePath = AssetDatabase.GetSubFolders(sourcePath).First();
foreach (var guid in AssetDatabase.FindAssets("VRCFury *", new string[] { sourcePath }))
{
var path = AssetDatabase.GUIDToAssetPath(guid);
var fileName = Path.GetFileName(path);
if (fileName.EndsWith(".controller"))
{
var layerType = cloneLayers
.Where(l => l.animatorController == AssetDatabase.LoadAssetAtPath<AnimatorController>(path))
.First().type;
AssetDatabase.MoveAsset(path, $"{sourcePath}/{layerType}_layer.controller");
}
else if (fileName.StartsWith("VRCFury Params"))
{
AssetDatabase.MoveAsset(path, $"{sourcePath}/parameters.asset");
}
else if (fileName.StartsWith("VRCFury Menu"))
{
AssetDatabase.MoveAsset(path, $"{sourcePath}/main_menu.asset");
}
}
clone.name = $"VRCF clone ({originalObject.name})";
Debug.Log("Avatar cloned and VRCFPatcher did its thing !");
}
catch (Exception e)
{
Debug.LogError("Post processing the clone avatar failed. This will probably not impact "
+ "build, although you may have to open an issue on github. Exception :");
Debug.LogException(e);
}
finally
{
AssetDatabase.SaveAssets();
originalObject.SetActive(false);
}
}
[MenuItem(menuPrefix + "Fix Missing Parameters", validate = true)]
private static bool CheckFixMissingParameters()
{
if (GetSelectedAvatar() != null)
{
var obj = Selection.activeGameObject;
return obj.name.StartsWith("VRCF clone (") && obj.name.EndsWith(")_KannaProteccted");
}
return false;
}
[MenuItem(menuPrefix + "Fix Missing Parameters")]
private static void FixMissingParameters()
{
var avatar = GetSelectedAvatarGameObject().GetComponent<VRCAvatarDescriptor>();
var originalAvatarName = avatar.name.Remove(avatar.name.IndexOf("_KannaProteccted"));
var originalAvatar = Resources.FindObjectsOfTypeAll<VRCAvatarDescriptor>().Where(o => o.gameObject.name == originalAvatarName).First();
var parameters = avatar.expressionParameters.parameters.ToList();
void RecursiveCheckMenuParams(VRCExpressionsMenu currentMenu, VRCExpressionsMenu originalMenu)
{
for (int i = 0; i < currentMenu.controls.Count; i++)
{
var control = currentMenu.controls[i];
if (control.parameter != null
&& !string.IsNullOrEmpty(control.parameter.name)
&& !avatar.expressionParameters.parameters.Any(p => p.name == control.parameter.name))
{
var originalParameter = originalAvatar.expressionParameters.parameters.Where(p => p.name == originalMenu.controls[i].parameter.name).First();
var newParam = new VRCExpressionParameters.Parameter()
{
name = control.parameter.name,
valueType = originalParameter.valueType,
saved = originalParameter.saved,
defaultValue = originalParameter.defaultValue,
networkSynced = originalParameter.networkSynced
};
Debug.Log($"Adding '{newParam.name}' to the expression parameters");
parameters.Insert(Random.Range(0, parameters.Count), newParam);
}
for (int j = 0; j < control.subParameters.Length; j++)
{
var subParam = control.subParameters[j];
if (subParam != null
&& !string.IsNullOrEmpty(subParam.name)
&& !avatar.expressionParameters.parameters.Any(p => p.name == subParam.name))
{
var originalParameter = originalAvatar.expressionParameters.parameters.Where(p => p.name == originalMenu.controls[i].subParameters[j].name).First();
var newParam = new VRCExpressionParameters.Parameter()
{
name = control.subParameters[j].name,
valueType = originalParameter.valueType,
saved = originalParameter.saved,
defaultValue = originalParameter.defaultValue,
networkSynced = originalParameter.networkSynced
};
Debug.Log($"Adding '{newParam.name}' to the expression parameters");
parameters.Insert(Random.Range(0, parameters.Count), newParam);
}
}
if (control.type == VRCExpressionsMenu.Control.ControlType.SubMenu && control.subMenu != null)
{
RecursiveCheckMenuParams(control.subMenu, originalMenu.controls[i].subMenu);
}
}
}
RecursiveCheckMenuParams(avatar.expressionsMenu, originalAvatar.expressionsMenu);
avatar.expressionParameters.parameters = parameters.ToArray();
AssetDatabase.SaveAssets();
}
#else
static VrcfPatcher()
{
_harmony.UnpatchAll(_patchName);
}
#endif
}