-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
EasySetupOutfit.cs
526 lines (432 loc) · 20.3 KB
/
EasySetupOutfit.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
#region
using System.Collections.Generic;
using System.Linq;
using nadena.dev.modular_avatar.ui;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
using static nadena.dev.modular_avatar.core.editor.Localization;
#endregion
namespace nadena.dev.modular_avatar.core.editor
{
internal class ESOErrorWindow : EditorWindow
{
private string header;
private string[] messageGroups;
private static GUIStyle buttonStyle, labelStyle;
private const float SeparatorSize = 6f;
internal static bool Suppress = false;
static ESOErrorWindow()
{
}
internal static void InitStyles()
{
buttonStyle = new GUIStyle(EditorStyles.miniButtonRight);
labelStyle = new GUIStyle(EditorStyles.label);
labelStyle.wordWrap = true;
buttonStyle.fixedWidth = 40f;
buttonStyle.fixedHeight = EditorGUIUtility.singleLineHeight * 1.5f;
}
internal static void Show(
string header,
string[] messageGroups
)
{
if (Suppress) return;
InitStyles();
var window = CreateInstance<ESOErrorWindow>();
window.titleContent = new GUIContent("Setup Outfit");
window.header = header;
window.messageGroups = messageGroups;
// Compute required window size
var height = 0f;
var width = 450f;
height += SeparatorSize;
height += EditorStyles.helpBox.CalcHeight(new GUIContent(header), width);
foreach (var message in messageGroups)
{
height += 6f; // TODO: constant
height += labelStyle.CalcHeight(new GUIContent(message), width);
}
height += buttonStyle.fixedHeight;
height += SeparatorSize;
window.minSize = new Vector2(width, height);
window.ShowModal();
}
private void OnGUI()
{
EditorGUILayout.Space(SeparatorSize);
EditorGUILayout.HelpBox(header, MessageType.Error);
foreach (var message in messageGroups)
{
EditorGUILayout.Space(SeparatorSize);
var style = new GUIStyle(EditorStyles.label);
style.wordWrap = true;
EditorGUILayout.LabelField(message, style);
}
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("OK", buttonStyle))
{
Close();
}
EditorGUILayout.EndHorizontal();
var finalRect = GUILayoutUtility.GetRect(SeparatorSize, SeparatorSize, GUILayout.ExpandWidth(true));
var size = this.minSize;
size.y = finalRect.position.y + finalRect.height;
if (size.y > 10)
{
if (Vector2.Distance(this.minSize, size) > 1f)
{
this.minSize = size;
}
if (Vector2.Distance(this.maxSize, size) > 1f)
{
this.maxSize = size;
}
}
}
}
internal static class EasySetupOutfit
{
private static string[] errorMessageGroups;
private static string errorHeader;
[MenuItem(UnityMenuItems.GameObject_SetupOutfit, false, UnityMenuItems.GameObject_SetupOutfitOrder)]
internal static void SetupOutfit(MenuCommand cmd)
{
if (!ValidateSetupOutfit())
{
ESOErrorWindow.Show(errorHeader, errorMessageGroups);
return;
}
if (!FindBones(cmd.context,
out var avatarRoot, out var avatarHips, out var outfitHips)
) return;
var outfitRoot = cmd.context as GameObject;
var avatarArmature = avatarHips.transform.parent;
var outfitArmature = outfitHips.transform.parent;
if (outfitArmature.GetComponent<ModularAvatarMergeArmature>() == null)
{
var merge = Undo.AddComponent<ModularAvatarMergeArmature>(outfitArmature.gameObject);
merge.mergeTarget = new AvatarObjectReference();
merge.mergeTarget.referencePath = RuntimeUtil.RelativePath(avatarRoot, avatarArmature.gameObject);
merge.LockMode = ArmatureLockMode.BaseToMerge;
merge.InferPrefixSuffix();
List<Transform> subRoots = new List<Transform>();
HeuristicBoneMapper.RenameBonesByHeuristic(merge, skipped: subRoots);
// If the outfit has an UpperChest bone but the avatar doesn't, add an additional MergeArmature to
// help with this
foreach (var subRoot in subRoots)
{
var subConfig = Undo.AddComponent<ModularAvatarMergeArmature>(subRoot.gameObject);
var parentTransform = subConfig.transform.parent;
var parentConfig = parentTransform.GetComponentInParent<ModularAvatarMergeArmature>();
var parentMapping = parentConfig.MapBone(parentTransform);
subConfig.mergeTarget = new AvatarObjectReference();
subConfig.mergeTarget.referencePath =
RuntimeUtil.RelativePath(avatarRoot, parentMapping.gameObject);
subConfig.LockMode = ArmatureLockMode.BaseToMerge;
subConfig.prefix = merge.prefix;
subConfig.suffix = merge.suffix;
subConfig.mangleNames = false;
}
var avatarRootMatchingArmature = avatarRoot.transform.Find(outfitArmature.gameObject.name);
if (merge.prefix == "" && merge.suffix == "" && avatarRootMatchingArmature != null)
{
// We have an armature whose names exactly match the root armature - this can cause some serious
// confusion in Unity's humanoid armature matching system. Fortunately, we can avoid this by
// renaming a bone close to the root; this will ensure the number of matching bones is small, and
// Unity's heuristics (apparently) will choose the base avatar's armature as the "true" armature.
outfitArmature.name += ".1";
// Also make sure to refresh the avatar's animator humanoid bone cache.
var avatarAnimator = avatarRoot.GetComponent<Animator>();
var humanDescription = avatarAnimator.avatar;
avatarAnimator.avatar = null;
// ReSharper disable once Unity.InefficientPropertyAccess
avatarAnimator.avatar = humanDescription;
}
}
FixAPose(avatarRoot, outfitArmature);
if (outfitRoot != null
&& outfitRoot.GetComponent<ModularAvatarMeshSettings>() == null
&& outfitRoot.GetComponentInParent<ModularAvatarMeshSettings>() == null)
{
var meshSettings = Undo.AddComponent<ModularAvatarMeshSettings>(outfitRoot.gameObject);
Transform rootBone = null, probeAnchor = null;
Bounds bounds = ModularAvatarMeshSettings.DEFAULT_BOUNDS;
FindConsistentSettings(avatarRoot, avatarHips.transform, ref probeAnchor, ref rootBone, ref bounds);
if (probeAnchor == null)
{
probeAnchor = avatarHips.transform;
}
if (rootBone == null)
{
rootBone = avatarRoot.transform;
}
meshSettings.InheritProbeAnchor = ModularAvatarMeshSettings.InheritMode.Set;
meshSettings.InheritBounds = ModularAvatarMeshSettings.InheritMode.Set;
meshSettings.ProbeAnchor = new AvatarObjectReference();
meshSettings.ProbeAnchor.referencePath = RuntimeUtil.RelativePath(avatarRoot, probeAnchor.gameObject);
meshSettings.RootBone = new AvatarObjectReference();
meshSettings.RootBone.referencePath = RuntimeUtil.RelativePath(avatarRoot, rootBone.gameObject);
meshSettings.Bounds = bounds;
}
}
private static void FixAPose(GameObject avatarRoot, Transform outfitArmature)
{
var mergeArmature = outfitArmature.GetComponent<ModularAvatarMergeArmature>();
if (mergeArmature == null) return;
var mergeTarget = mergeArmature.mergeTarget.Get(mergeArmature)?.transform;
if (mergeTarget == null) return;
var rootAnimator = avatarRoot.GetComponent<Animator>();
if (rootAnimator == null) return;
FixSingleArm(HumanBodyBones.LeftShoulder);
FixSingleArm(HumanBodyBones.RightShoulder);
FixSingleArm(HumanBodyBones.LeftUpperArm);
FixSingleArm(HumanBodyBones.RightUpperArm);
void FixSingleArm(HumanBodyBones arm)
{
var lowerArm = (HumanBodyBones)((int)arm + 2);
// check if the rotation of the arm differs, but distances and origin point are the same
var avatarArm = rootAnimator.GetBoneTransform(arm);
var outfitArm = avatarToOutfit(avatarArm);
var avatarLowerArm = rootAnimator.GetBoneTransform(lowerArm);
var outfitLowerArm = avatarToOutfit(avatarLowerArm);
if (outfitArm == null) return;
if (outfitLowerArm == null) return;
if ((avatarArm.position - outfitArm.position).magnitude > 0.001f) return;
// check relative distance to lower arm as well
var avatarArmLength = (avatarLowerArm.position - avatarArm.position).magnitude;
var outfitArmLength = (outfitLowerArm.position - outfitArm.position).magnitude;
if (Mathf.Abs(avatarArmLength - outfitArmLength) > 0.001f) return;
// Rotate the outfit arm to ensure these two points match.
var relRot = Quaternion.FromToRotation(
outfitLowerArm.position - outfitArm.position,
avatarLowerArm.position - avatarArm.position
);
outfitArm.rotation = relRot * outfitArm.rotation;
PrefabUtility.RecordPrefabInstancePropertyModifications(outfitArm);
EditorUtility.SetDirty(outfitArm);
}
Transform avatarToOutfit(Transform avBone)
{
if (avBone == null) return null;
if (!avBone.IsChildOf(mergeTarget)) return null;
var parts = RuntimeUtil.RelativePath(mergeTarget.gameObject, avBone.gameObject)
.Split('/');
var outfitPath = string.Join("/", parts.Select(p => mergeArmature.prefix + p + mergeArmature.suffix));
var candidate = outfitArmature.transform.Find(outfitPath);
if (candidate == null) return null;
var merger = candidate.GetComponentInParent<ModularAvatarMergeArmature>();
if (merger != mergeArmature) return null;
return candidate;
}
}
private static void FindConsistentSettings(
GameObject avatarRoot,
Transform avatarHips,
ref Transform probeAnchor,
ref Transform rootBone,
ref Bounds bounds
)
{
// We assume the renderers directly under the avatar root came from the original avatar and are _probably_
// set consistently. If so, we use this as a basis for the new outfit's settings.
bool firstRenderer = true;
bool firstSkinnedMeshRenderer = true;
foreach (Transform directChild in avatarRoot.transform)
{
var renderer = directChild.GetComponent<Renderer>();
if (renderer == null) continue;
if (firstRenderer)
{
probeAnchor = renderer.probeAnchor;
}
else
{
if (renderer.probeAnchor != probeAnchor)
{
probeAnchor = null; // inconsistent configuration
}
}
firstRenderer = false;
var skinnedMeshRenderer = renderer as SkinnedMeshRenderer;
if (skinnedMeshRenderer == null) continue;
if (firstSkinnedMeshRenderer)
{
rootBone = skinnedMeshRenderer.rootBone;
bounds = skinnedMeshRenderer.localBounds;
}
else
{
if (rootBone != skinnedMeshRenderer.rootBone)
{
rootBone = avatarHips; // inconsistent configuration
bounds = TransformBounds(rootBone, ModularAvatarMeshSettings.DEFAULT_BOUNDS);
}
else if (Vector3.Distance(bounds.center, skinnedMeshRenderer.bounds.center) > 0.01f
|| Vector3.Distance(bounds.extents, skinnedMeshRenderer.bounds.extents) > 0.01f)
{
bounds = TransformBounds(rootBone, ModularAvatarMeshSettings.DEFAULT_BOUNDS);
}
}
firstSkinnedMeshRenderer = false;
}
}
private static Bounds TransformBounds(Transform rootBone, Bounds bounds)
{
bounds.extents = bounds.extents / (Vector3.Dot(rootBone.lossyScale, Vector3.one) / 3);
return bounds;
}
static bool ValidateSetupOutfit()
{
errorHeader = S("setup_outfit.err.header.notarget");
errorMessageGroups = new string[] { S("setup_outfit.err.unknown") };
if (Selection.objects.Length == 0)
{
errorMessageGroups = new string[] { S("setup_outfit.err.no_selection") };
return false;
}
foreach (var obj in Selection.objects)
{
errorHeader = S_f("setup_outfit.err.header", obj.name);
if (!(obj is GameObject gameObj)) return false;
var xform = gameObj.transform;
if (!FindBones(obj, out var _, out var _, out var outfitHips))
{
return false;
}
// Some users have been accidentally running Setup Outfit on the avatar itself, and/or nesting avatar
// descriptors when transplanting outfits. Block this (and require that there be only one avdesc) by
// refusing to run if we detect multiple avatar descriptors above the current object (or if we're run on
// the avdesc object itself)
var nearestAvatarTransform = RuntimeUtil.FindAvatarTransformInParents(xform);
if (nearestAvatarTransform == null)
{
errorMessageGroups = new string[]
{
S_f("setup_outfit.err.no_avatar_descriptor", xform.gameObject.name)
};
return false;
}
if (nearestAvatarTransform == xform)
{
errorMessageGroups = new string[]
{ S_f("setup_outfit.err.run_on_avatar_itself", xform.gameObject.name) };
return false;
}
var parent = nearestAvatarTransform.parent;
if (parent != null && RuntimeUtil.FindAvatarTransformInParents(parent) != null)
{
errorMessageGroups = new string[]
{
S_f("setup_outfit.err.multiple_avatar_descriptors", xform.gameObject.name)
};
return false;
}
}
return true;
}
internal static bool FindBones(Object obj, out GameObject avatarRoot, out GameObject avatarHips,
out GameObject outfitHips)
{
avatarHips = outfitHips = null;
var outfitRoot = obj as GameObject;
avatarRoot = outfitRoot != null
? RuntimeUtil.FindAvatarTransformInParents(outfitRoot.transform)?.gameObject
: null;
if (avatarRoot == null)
{
errorMessageGroups = new string[]
{
S_f("setup_outfit.err.no_avatar_descriptor", outfitRoot != null ? outfitRoot.name : "<null>")
};
}
if (outfitRoot == null || avatarRoot == null) return false;
var avatarAnimator = avatarRoot.GetComponent<Animator>();
if (avatarAnimator == null)
{
errorMessageGroups = new string[]
{
S("setup_outfit.err.no_animator")
};
return false;
}
avatarHips = avatarAnimator.isHuman
? avatarAnimator.GetBoneTransform(HumanBodyBones.Hips)?.gameObject
: null;
if (avatarHips == null)
{
errorMessageGroups = new string[]
{
S("setup_outfit.err.no_hips")
};
return false;
}
var outfitAnimator = outfitRoot.GetComponent<Animator>();
if (outfitAnimator != null)
{
outfitHips = outfitAnimator.isHuman
? outfitAnimator.GetBoneTransform(HumanBodyBones.Hips)?.gameObject
: null;
if (outfitHips != null && outfitHips.transform.parent == outfitRoot.transform)
{
// Sometimes broken rigs can have the hips as a direct child of the root, instead of having
// an intermediate Armature object. We do not currently support this kind of rig, and so we'll
// assume the outfit's humanoid rig is broken and move on to heuristic matching.
outfitHips = null;
}
}
var hipsCandidates = new List<string>();
if (outfitHips == null)
{
// Heuristic search - usually there'll be root -> Armature -> (single child) Hips.
// First, look for an exact match.
foreach (Transform child in outfitRoot.transform)
{
foreach (Transform tempHip in child)
{
if (tempHip.name.Contains(avatarHips.name))
{
outfitHips = tempHip.gameObject;
// Prefer the first hips we find
break;
}
}
if (outfitHips != null) break;
}
hipsCandidates.Add(avatarHips.name);
// If that doesn't work out, we'll check for heuristic bone mapper mappings.
foreach (var hbm in HeuristicBoneMapper.BoneToNameMap[HumanBodyBones.Hips])
{
if (hipsCandidates[0] != hbm)
{
hipsCandidates.Add(hbm);
}
}
foreach (Transform child in outfitRoot.transform)
{
foreach (Transform tempHip in child)
{
foreach (var candidate in hipsCandidates)
{
if (HeuristicBoneMapper.NormalizeName(tempHip.name).Contains(candidate))
{
outfitHips = tempHip.gameObject;
}
}
}
}
}
if (outfitHips == null)
{
errorMessageGroups = new string[]
{
S("setup_outfit.err.no_outfit_hips"),
string.Join("\n", hipsCandidates.Select(c => "・ " + c).ToArray())
};
}
return avatarHips != null && outfitHips != null;
}
}
}