add Physics support

This commit is contained in:
1605296300@qq.com
2022-08-10 16:54:20 +08:00
parent 33c8d35c84
commit f797fbb2fd
855 changed files with 649609 additions and 98 deletions
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a8c00ee8c4666954cb9915799f0248d2
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+9
View File
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 47bf04154c11c5e45b94b1aec2c0baf6
folderAsset: yes
timeCreated: 1516620867
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 8d2079bf8fd63d640a121f8fea6f5c5f
folderAsset: yes
timeCreated: 1516620916
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,498 @@
using UnityEngine;
using System.Collections;
using UnityEngine.Playables;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace RootMotion
{
/// <summary>
/// Base class for animation bakers, handles timing, keyframing and saving AnimationClips.
/// </summary>
[HelpURL("http://www.root-motion.com/finalikdox/html/page3.html")]
[AddComponentMenu("Scripts/RootMotion/Baker")]
public abstract class Baker : MonoBehaviour
{
// Open the User Manual URL
[ContextMenu("User Manual")]
void OpenUserManual()
{
Application.OpenURL("http://www.root-motion.com/finalikdox/html/page3.html");
}
// Open the Script Reference URL
[ContextMenu("Scrpt Reference")]
void OpenScriptReference()
{
Application.OpenURL("http://www.root-motion.com/finalikdox/html/class_root_motion_1_1_baker.html");
}
// Link to the Final IK Google Group
[ContextMenu("Support Group")]
void SupportGroup()
{
Application.OpenURL("https://groups.google.com/forum/#!forum/final-ik");
}
// Link to the Final IK Asset Store thread in the Unity Community
[ContextMenu("Asset Store Thread")]
void ASThread()
{
Application.OpenURL("http://forum.unity3d.com/threads/final-ik-full-body-ik-aim-look-at-fabrik-ccd-ik-1-0-released.222685/");
}
[System.Serializable]
public enum Mode
{
AnimationClips = 0,
AnimationStates = 1,
PlayableDirector = 2,
Realtime = 3
}
/// <summary>
/// In AnimationClips, AnimationStates or PlayableDirector mode - the frame rate at which the animation clip will be sampled. In Realtime mode - the frame rate at which the pose will be sampled. With the latter, the frame rate is not guaranteed if the player is not able to reach it.
/// </summary>
[Tooltip("In AnimationClips, AnimationStates or PlayableDirector mode - the frame rate at which the animation clip will be sampled. In Realtime mode - the frame rate at which the pose will be sampled. With the latter, the frame rate is not guaranteed if the player is not able to reach it.")]
[Range(1, 90)] public int frameRate = 30;
/// <summary>
/// Maximum allowed error for keyframe reduction.
/// </summary>
[Tooltip("Maximum allowed error for keyframe reduction.")]
[Range(0f, 0.1f)] public float keyReductionError = 0.01f;
/// <summary>
/// AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController. AnimationStates mode is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim. PlayableDirector mode bakes a Timeline. Realtime mode is for continuous baking of gameplay, ragdoll phsysics or PuppetMaster dynamics.
/// </summary>
[Tooltip("AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController. " +
"AnimationStates mode is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim. " +
"PlayableDirector mode bakes a Timeline. " +
"Realtime mode is for continuous baking of gameplay, ragdoll phsysics or PuppetMaster dynamics.")]
public Mode mode;
/// <summary>
/// AnimationClips to bake.
/// </summary>
[Tooltip("AnimationClips to bake.")]
public AnimationClip[] animationClips = new AnimationClip[0];
/// <summary>
/// The name of the AnimationStates to bake (must be on the base layer) in the Animator (Right-click on this component header and select 'Find Animation States' to have Baker fill those in automatically, required that state names match with the names of the clips used in them).
/// </summary>
[Tooltip("The name of the AnimationStates to bake (must be on the base layer) in the Animator above (Right-click on this component header and select 'Find Animation States' to have Baker fill those in automatically, required that state names match with the names of the clips used in them).")]
public string[] animationStates = new string[0];
/// <summary>
/// Sets the baked animation clip to loop time and matches the last frame keys with the first. Note that if you are overwriting a previously baked clip, AnimationClipSettings will be copied from the existing clip.
/// </summary>
[Tooltip("Sets the baked animation clip to loop time and matches the last frame keys with the first. Note that when overwriting a previously baked clip, AnimationClipSettings will be copied from the existing clip.")]
public bool loop = true;
/// <summary>
/// The folder to save the baked AnimationClips to.
/// </summary>
[Tooltip("The folder to save the baked AnimationClips to.")]
public string saveToFolder = "Assets";
/// <summary>
/// String that will be added to each clip or animation state name for the saved clip. For example if your animation state/clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
/// </summary>
[Tooltip("String that will be added to each clip or animation state name for the saved clip. For example if your animation state/clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.")]
public string appendName = "_Baked";
/// <summary>
/// Name of the created AnimationClip file.
/// </summary>
[Tooltip("Name of the created AnimationClip file.")]
public string saveName = "Baked Clip";
public bool isBaking { get; private set; }
public float bakingProgress { get; private set; }
[SerializeField] [HideInInspector] public Animator animator;
[SerializeField] [HideInInspector] public PlayableDirector director;
protected abstract Transform GetCharacterRoot();
protected abstract void OnStartBaking();
protected abstract void OnSetLoopFrame(float time);
protected abstract void OnSetCurves(ref AnimationClip clip);
protected abstract void OnSetKeyframes(float time, bool lastFrame);
protected float clipLength { get; private set; }
#if UNITY_EDITOR
private AnimationClip[] bakedClips = new AnimationClip[0];
private AnimatorStateInfo currentClipStateInfo;
private int currentClipIndex;
private float startBakingTime;
private float nextKeyframeTime;
private bool firstFrame;
private int clipFrames;
private int clipFrameNo;
private bool setKeyframes;
private float currentClipTime;
private float clipFrameInterval;
private const bool setLoopFrame = true; // Makes sure first and last keyframes in the baked clip match up if baking a looping clip.
#endif
// Start baking an animation state, clip or timeline, also called for each next clip in the baking array
public void BakeClip()
{
#if UNITY_EDITOR
switch (mode)
{
case Mode.AnimationClips:
AnimationClipSettings originalSettings = AnimationUtility.GetAnimationClipSettings(animationClips[currentClipIndex]);
loop = originalSettings.loopTime;
break;
}
StartBaking();
#endif
}
public void StartBaking()
{
#if UNITY_EDITOR
isBaking = true;
nextKeyframeTime = 0f;
bakingProgress = 0f;
clipFrameNo = 0;
if (bakedClips.Length == 0)
{
switch (mode)
{
case Mode.AnimationClips:
bakedClips = new AnimationClip[animationClips.Length];
break;
case Mode.AnimationStates:
bakedClips = new AnimationClip[animationStates.Length];
break;
default:
bakedClips = new AnimationClip[1];
break;
}
}
OnStartBaking();
firstFrame = true;
#endif
}
public void StopBaking()
{
#if UNITY_EDITOR
if (!isBaking) return;
if (mode != Mode.Realtime && loop && setLoopFrame)
{
OnSetLoopFrame(clipLength);
}
bakedClips[currentClipIndex] = new AnimationClip();
bakedClips[currentClipIndex].frameRate = frameRate;
OnSetCurves(ref bakedClips[currentClipIndex]);
bakedClips[currentClipIndex].EnsureQuaternionContinuity();
if (mode == Mode.Realtime)
{
isBaking = false;
SaveClips();
}
#endif
}
#if UNITY_EDITOR
[ContextMenu("Find Animation States")]
public void FindAnimationStates()
{
animator = GetComponent<Animator>();
if (animator == null)
{
Debug.LogError("No Animator found on Baker GameObject. Can not find animation states.");
return;
}
if (animator.runtimeAnimatorController == null)
{
Debug.LogError("Animator does not have a valid Controller. Can not find animation states.");
return;
}
var clips = animator.runtimeAnimatorController.animationClips;
animationStates = new string[clips.Length];
for (int i = 0; i < clips.Length; i++)
{
animationStates[i] = clips[i].name;
}
}
void Update()
{
// Baking procedure
if (isBaking)
{
if (mode != Mode.Realtime)
{
if (firstFrame)
{
transform.position = Vector3.zero;
transform.rotation = Quaternion.identity;
GetCharacterRoot().position = Vector3.zero;
GetCharacterRoot().rotation = Quaternion.identity;
StartAnimationUpdate();
currentClipTime = 0f;
firstFrame = false;
}
switch (mode)
{
case Mode.AnimationClips:
clipLength = animationClips[currentClipIndex].length;
bakingProgress = currentClipTime / clipLength;
break;
case Mode.AnimationStates:
currentClipStateInfo = animator.GetCurrentAnimatorStateInfo(0);
bakingProgress = currentClipStateInfo.normalizedTime;
if (currentClipStateInfo.speed <= 0f)
{
Debug.LogError("Baker can not bake a clip with 0 speed.");
return;
}
clipLength = currentClipStateInfo.length / currentClipStateInfo.speed / animator.speed;
break;
case Mode.PlayableDirector:
clipLength = (float)director.duration;
bakingProgress = (float)director.time / clipLength;
break;
}
clipFrames = (int)(clipLength * (frameRate));
clipFrameInterval = clipLength / (float)(clipFrames);
setKeyframes = true;
// Stop clip baking if the clip is finished, start baking the next clip if possible
if (clipFrameNo > clipFrames)
{
StopBaking();
currentClipIndex++;
if (currentClipIndex >= bakedClips.Length)
{
currentClipIndex = 0;
StopAnimationUpdate();
isBaking = false;
SaveClips();
return;
}
else
{
BakeClip();
setKeyframes = false;
}
}
if (!firstFrame) AnimationUpdate();
}
}
}
void LateUpdate()
{
if (!isBaking) return;
if (mode != Mode.Realtime)
{
if (setKeyframes)
{
OnSetKeyframes(clipFrameNo * clipFrameInterval, clipFrameNo >= clipFrames);
clipFrameNo++;
setKeyframes = false;
}
}
else
{
if (firstFrame)
{
startBakingTime = Time.time;
firstFrame = false;
}
if (Time.time < nextKeyframeTime) return;
OnSetKeyframes(Time.time - startBakingTime, false);
nextKeyframeTime = Time.time + (1f / (float)frameRate);
}
}
private void StartAnimationUpdate()
{
switch (mode)
{
case Mode.AnimationClips:
if (!AnimationMode.InAnimationMode()) AnimationMode.StartAnimationMode();
AnimationMode.BeginSampling();
AnimationMode.SampleAnimationClip(gameObject, animationClips[currentClipIndex], 0f);
AnimationMode.EndSampling();
break;
case Mode.AnimationStates:
animator.enabled = false;
animator.Play(animationStates[currentClipIndex], 0, 0f);
break;
case Mode.PlayableDirector:
director.enabled = false;
director.time = 0f;
director.Evaluate();
break;
}
}
private void StopAnimationUpdate()
{
switch (mode)
{
case Mode.AnimationClips:
if (AnimationMode.InAnimationMode()) AnimationMode.StopAnimationMode();
break;
case Mode.AnimationStates:
animator.enabled = true;
break;
case Mode.PlayableDirector:
director.enabled = true;
break;
}
}
private void AnimationUpdate()
{
switch (mode)
{
case Mode.AnimationClips:
if (!AnimationMode.InAnimationMode()) AnimationMode.StartAnimationMode();
AnimationMode.BeginSampling();
AnimationMode.SampleAnimationClip(gameObject, animationClips[currentClipIndex], currentClipTime);
AnimationMode.EndSampling();
currentClipTime += clipFrameInterval;
break;
case Mode.AnimationStates:
animator.Update(clipFrameInterval);
break;
case Mode.PlayableDirector:
director.time = currentClipTime;
director.Evaluate();
currentClipTime += clipFrameInterval;
break;
}
}
public void SaveClips()
{
var clips = GetBakedClips();
AnimationClip savedClip = null;
for (int i = 0; i < clips.Length; i++)
{
string path = GetFullPath(i);
switch (mode)
{
case Baker.Mode.Realtime: break;
case Baker.Mode.AnimationClips:
AnimationClipSettings originalSettings = AnimationUtility.GetAnimationClipSettings(animationClips[i]);
SetClipSettings(clips[i], originalSettings);
AnimationUtility.SetAnimationClipSettings(clips[i], originalSettings);
break;
default:
AnimationClipSettings settings = AnimationUtility.GetAnimationClipSettings(clips[i]);
settings.loopTime = loop;
SetClipSettings(clips[i], settings);
AnimationUtility.SetAnimationClipSettings(clips[i], settings);
break;
}
var existing = AssetDatabase.LoadAssetAtPath(path, typeof(AnimationClip)) as AnimationClip;
if (existing != null)
{
// Overwrite with existing settings
AnimationClipSettings existingSettings = AnimationUtility.GetAnimationClipSettings(existing);
AnimationUtility.SetAnimationClipSettings(clips[i], existingSettings);
EditorUtility.CopySerialized(clips[i], existing);
}
else
{
// Create new asset
AssetDatabase.CreateAsset(clips[i], path);
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
savedClip = AssetDatabase.LoadAssetAtPath(path, typeof(AnimationClip)) as AnimationClip;
Debug.Log(path + " successfully baked.");
}
Selection.activeObject = savedClip;
ClearBakedClips();
}
protected virtual void SetClipSettings(AnimationClip clip, AnimationClipSettings settings) {}
private string GetFullPath(int clipIndex)
{
switch (mode)
{
case Baker.Mode.AnimationClips:
return saveToFolder + "/" + animationClips[clipIndex].name + appendName + ".anim";
case Baker.Mode.AnimationStates:
return saveToFolder + "/" + animationStates[clipIndex] + appendName + ".anim";
case Baker.Mode.PlayableDirector:
return saveToFolder + "/" + saveName + ".anim";
default:
return saveToFolder + "/" + saveName + ".anim";
}
}
private AnimationClip[] GetBakedClips()
{
return bakedClips;
}
private void ClearBakedClips()
{
bakedClips = new AnimationClip[0];
}
#endif
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ab14efce3fefe4f4982f0fa6911d0cd4
timeCreated: 1516617114
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,134 @@
using UnityEngine;
using System.Collections;
using System;
namespace RootMotion
{
/// <summary>
/// Baker for Generic/Legacy animation.
/// </summary>
public class GenericBaker : Baker
{
/// <summary>
/// If true, produced AnimationClips will be marked as Legacy and usable with the Legacy animation system.
/// </summary>
[Tooltip("If true, produced AnimationClips will be marked as Legacy and usable with the Legacy animation system.")]
public bool markAsLegacy;
/// <summary>
/// Root Transform of the hierarchy to bake.
/// </summary>
[Tooltip("Root Transform of the hierarchy to bake.")]
public Transform root;
/// <summary>
/// Root Node used for root motion.
/// </summary>
[Tooltip("Root Node used for root motion.")]
public Transform rootNode;
/// <summary>
/// List of Transforms to ignore, rotation curves will not be baked for these Transforms.
/// </summary>
[Tooltip("List of Transforms to ignore, rotation curves will not be baked for these Transforms.")]
public Transform[] ignoreList;
/// <summary>
/// LocalPosition curves will be baked for these Transforms only. If you are baking a character, the pelvis bone should be added to this array.
/// </summary>
[Tooltip("LocalPosition curves will be baked for these Transforms only. If you are baking a character, the pelvis bone should be added to this array.")]
public Transform[] bakePositionList;
private BakerTransform[] children = new BakerTransform[0];
private BakerTransform rootChild;
private int rootChildIndex = -1;
void Awake()
{
// Find all the child Transforms of the Animator
Transform[] childrenAndRoot = (Transform[])root.GetComponentsInChildren<Transform>();
children = new BakerTransform[0];
// Exlude the ignore list, construct the children array
for (int i = 0; i < childrenAndRoot.Length; i++)
{
if (!IsIgnored(childrenAndRoot[i]))
{
Array.Resize(ref children, children.Length + 1);
bool isRootNode = childrenAndRoot[i] == rootNode;
if (isRootNode) rootChildIndex = children.Length - 1;
children[children.Length - 1] = new BakerTransform(childrenAndRoot[i], root, BakePosition(childrenAndRoot[i]), isRootNode);
}
}
}
protected override Transform GetCharacterRoot()
{
return root;
}
protected override void OnStartBaking()
{
for (int i = 0; i < children.Length; i++)
{
children[i].Reset();
if (i == rootChildIndex) children[i].SetRelativeSpace(root.position, root.rotation);
}
}
protected override void OnSetLoopFrame(float time)
{
// TODO Change to SetLoopFrame like in HumanoidBaker
for (int i = 0; i < children.Length; i++) children[i].AddLoopFrame(time);
}
protected override void OnSetCurves(ref AnimationClip clip)
{
// TODO Length Multiplier
for (int i = 0; i < children.Length; i++) children[i].SetCurves(ref clip);
}
protected override void OnSetKeyframes(float time, bool lastFrame)
{
for (int i = 0; i < children.Length; i++) children[i].SetKeyframes(time);
}
// Is the specified Transform in the ignore list?
private bool IsIgnored(Transform t)
{
for (int i = 0; i < ignoreList.Length; i++)
{
if (t == ignoreList[i]) return true;
}
return false;
}
// Should we record the localPosition channels of the Transform?
private bool BakePosition(Transform t)
{
for (int i = 0; i < bakePositionList.Length; i++)
{
if (t == bakePositionList[i]) return true;
}
return false;
}
#if UNITY_EDITOR
protected override void SetClipSettings(AnimationClip clip, UnityEditor.AnimationClipSettings settings)
{
clip.legacy = markAsLegacy;
if (mode != Baker.Mode.AnimationClips)
{
clip.wrapMode = loop ? WrapMode.Loop : WrapMode.Default;
}
}
#endif
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 27b32efee52144c4e934e6c3272ceb2c
timeCreated: 1516356533
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 15001
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: e468ef7e80a87f94588b5eeb3a423b91
folderAsset: yes
timeCreated: 1516621025
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,90 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;
namespace RootMotion
{
public class TQ
{
public TQ(Vector3 translation, Quaternion rotation)
{
t = translation;
q = rotation;
}
public Vector3 t;
public Quaternion q;
}
/*
Written with the kind help of the one commonly known as Mecanim-Dev.
*/
public class AvatarUtility
{
public static Quaternion GetPostRotation(Avatar avatar, AvatarIKGoal avatarIKGoal)
{
int humanId = (int)HumanIDFromAvatarIKGoal(avatarIKGoal);
if (humanId == (int)HumanBodyBones.LastBone) throw new InvalidOperationException("Invalid human id.");
MethodInfo methodGetPostRotation = typeof(Avatar).GetMethod("GetPostRotation", BindingFlags.Instance | BindingFlags.NonPublic);
if (methodGetPostRotation == null) throw new InvalidOperationException("Cannot find GetPostRotation method.");
return (Quaternion)methodGetPostRotation.Invoke(avatar, new object[] { humanId });
}
/// <summary>
/// Get IK position and rotation for foot/hand bone position/rotation.
/// </summary>
public static TQ GetIKGoalTQ(Avatar avatar, float humanScale, AvatarIKGoal avatarIKGoal, TQ bodyPositionRotation, TQ boneTQ)
{
int humanId = (int)HumanIDFromAvatarIKGoal(avatarIKGoal);
if (humanId == (int)HumanBodyBones.LastBone) throw new InvalidOperationException("Invalid human id.");
MethodInfo methodGetAxisLength = typeof(Avatar).GetMethod("GetAxisLength", BindingFlags.Instance | BindingFlags.NonPublic);
if (methodGetAxisLength == null) throw new InvalidOperationException("Cannot find GetAxisLength method.");
MethodInfo methodGetPostRotation = typeof(Avatar).GetMethod("GetPostRotation", BindingFlags.Instance | BindingFlags.NonPublic);
if (methodGetPostRotation == null) throw new InvalidOperationException("Cannot find GetPostRotation method.");
Quaternion postRotation = (Quaternion)methodGetPostRotation.Invoke(avatar, new object[] { humanId });
var goalTQ = new TQ(boneTQ.t, boneTQ.q * postRotation);
if (avatarIKGoal == AvatarIKGoal.LeftFoot || avatarIKGoal == AvatarIKGoal.RightFoot)
{
// Here you could use animator.leftFeetBottomHeight or animator.rightFeetBottomHeight rather than GetAxisLenght
// Both are equivalent but GetAxisLength is the generic way and work for all human bone
float axislength = (float)methodGetAxisLength.Invoke(avatar, new object[] { humanId });
Vector3 footBottom = new Vector3(axislength, 0, 0);
goalTQ.t += (goalTQ.q * footBottom);
}
// IK goal are in avatar body local space
Quaternion invRootQ = Quaternion.Inverse(bodyPositionRotation.q);
goalTQ.t = invRootQ * (goalTQ.t - bodyPositionRotation.t);
goalTQ.q = invRootQ * goalTQ.q;
goalTQ.t /= humanScale;
goalTQ.q = Quaternion.LookRotation(goalTQ.q * Vector3.forward, goalTQ.q * Vector3.up);
return goalTQ;
}
public static HumanBodyBones HumanIDFromAvatarIKGoal(AvatarIKGoal avatarIKGoal)
{
HumanBodyBones humanId = HumanBodyBones.LastBone;
switch (avatarIKGoal)
{
case AvatarIKGoal.LeftFoot: humanId = HumanBodyBones.LeftFoot; break;
case AvatarIKGoal.RightFoot: humanId = HumanBodyBones.RightFoot; break;
case AvatarIKGoal.LeftHand: humanId = HumanBodyBones.LeftHand; break;
case AvatarIKGoal.RightHand: humanId = HumanBodyBones.RightHand; break;
}
return humanId;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 2f9e403f0f8255c42b90254abc55f528
timeCreated: 1516435305
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,571 @@
using UnityEngine;
using System.Collections;
namespace RootMotion
{
public static class BakerUtilities
{
public static void ReduceKeyframes(AnimationCurve curve, float maxError)
{
if (maxError <= 0f) return;
curve.keys = GetReducedKeyframes(curve, maxError);
// TODO Flatten outTangent for keys that have the next key and testAfter sampled to the same value in the original clip. Same thing for the inTangent
}
public static Keyframe[] GetReducedKeyframes(AnimationCurve curve, float maxError)
{
Keyframe[] keys = curve.keys;
int i = 1;
while (i < keys.Length - 1 && keys.Length > 2)
{
Keyframe[] testKeys = new Keyframe[keys.Length - 1];
int c = 0;
for (int n = 0; n < keys.Length; n++)
{
if (i != n)
{
testKeys[c] = new Keyframe(keys[n].time, keys[n].value, keys[n].inTangent, keys[n].outTangent);
c++;
}
}
AnimationCurve testCurve = new AnimationCurve();
testCurve.keys = testKeys;
float test0 = Mathf.Abs(testCurve.Evaluate(keys[i].time) - keys[i].value);
float beforeTime = keys[i].time + (keys[i - 1].time - keys[i].time) * 0.5f;
float afterTime = keys[i].time + (keys[i + 1].time - keys[i].time) * 0.5f;
float testBefore = Mathf.Abs(testCurve.Evaluate(beforeTime) - curve.Evaluate(beforeTime));
float testAfter = Mathf.Abs(testCurve.Evaluate(afterTime) - curve.Evaluate(afterTime));
if (test0 < maxError && testBefore < maxError && testAfter < maxError)
{
keys = testKeys;
}
else
{
i++;
}
}
return keys;
}
public static void SetLoopFrame(float time, AnimationCurve curve)
{
Keyframe[] keys = curve.keys;
keys[keys.Length - 1].value = keys[0].value;
float inTangent = Mathf.Lerp(keys[0].inTangent, keys[keys.Length - 1].inTangent, 0.5f);
keys[0].inTangent = inTangent;
keys[keys.Length - 1].inTangent = inTangent;
float outTangent = Mathf.Lerp(keys[0].outTangent, keys[keys.Length - 1].outTangent, 0.5f);
keys[0].outTangent = outTangent;
keys[keys.Length - 1].outTangent = outTangent;
keys[keys.Length - 1].time = time;
curve.keys = keys;
}
public static void SetTangentMode(AnimationCurve curve)
{
#if UNITY_EDITOR
if (curve.length < 2) return;
for (int i = 1; i < curve.length - 1; i++)
{
UnityEditor.AnimationUtility.SetKeyLeftTangentMode(curve, i, UnityEditor.AnimationUtility.TangentMode.ClampedAuto);
UnityEditor.AnimationUtility.SetKeyRightTangentMode(curve, i, UnityEditor.AnimationUtility.TangentMode.ClampedAuto);
}
#endif
}
// Realigns quaternion keys to ensure shortest interpolation paths.
public static Quaternion EnsureQuaternionContinuity(Quaternion lastQ, Quaternion q)
{
Quaternion flipped = new Quaternion(-q.x, -q.y, -q.z, -q.w);
Quaternion midQ = new Quaternion(
Mathf.Lerp(lastQ.x, q.x, 0.5f),
Mathf.Lerp(lastQ.y, q.y, 0.5f),
Mathf.Lerp(lastQ.z, q.z, 0.5f),
Mathf.Lerp(lastQ.w, q.w, 0.5f)
);
Quaternion midQFlipped = new Quaternion(
Mathf.Lerp(lastQ.x, flipped.x, 0.5f),
Mathf.Lerp(lastQ.y, flipped.y, 0.5f),
Mathf.Lerp(lastQ.z, flipped.z, 0.5f),
Mathf.Lerp(lastQ.w, flipped.w, 0.5f)
);
float angle = Quaternion.Angle(lastQ, midQ);
float angleFlipped = Quaternion.Angle(lastQ, midQFlipped);
return angleFlipped < angle ? flipped : q;
}
}
//Manages the Animation Curves for Humanoid Q/T channels.
[System.Serializable]
public class BakerHumanoidQT
{
private Transform transform;
private string Qx, Qy, Qz, Qw;
private string Tx, Ty, Tz;
// Animation curves for each channel of the Transform
public AnimationCurve rotX, rotY, rotZ, rotW;
public AnimationCurve posX, posY, posZ;
private AvatarIKGoal goal;
private Quaternion lastQ;
private bool lastQSet;
// The custom constructor
public BakerHumanoidQT(string name)
{
Qx = name + "Q.x";
Qy = name + "Q.y";
Qz = name + "Q.z";
Qw = name + "Q.w";
Tx = name + "T.x";
Ty = name + "T.y";
Tz = name + "T.z";
Reset();
}
public BakerHumanoidQT(Transform transform, AvatarIKGoal goal, string name)
{
this.transform = transform;
this.goal = goal;
Qx = name + "Q.x";
Qy = name + "Q.y";
Qz = name + "Q.z";
Qw = name + "Q.w";
Tx = name + "T.x";
Ty = name + "T.y";
Tz = name + "T.z";
Reset();
}
// Clear all curves
public void Reset()
{
rotX = new AnimationCurve();
rotY = new AnimationCurve();
rotZ = new AnimationCurve();
rotW = new AnimationCurve();
posX = new AnimationCurve();
posY = new AnimationCurve();
posZ = new AnimationCurve();
lastQ = Quaternion.identity;
lastQSet = false;
}
public void SetIKKeyframes(float time, Avatar avatar, float humanScale, Vector3 bodyPosition, Quaternion bodyRotation)
{
// TODO Use character scale
TQ IKTQ = AvatarUtility.GetIKGoalTQ(avatar, humanScale, goal, new TQ(bodyPosition, bodyRotation), new TQ(transform.position, transform.rotation));
Quaternion rot = IKTQ.q;
if (lastQSet) rot = BakerUtilities.EnsureQuaternionContinuity(lastQ, IKTQ.q);
//rot.Normalize();
lastQ = rot;
lastQSet = true;
rotX.AddKey(time, rot.x);
rotY.AddKey(time, rot.y);
rotZ.AddKey(time, rot.z);
rotW.AddKey(time, rot.w);
Vector3 pos = IKTQ.t;
posX.AddKey(time, pos.x);
posY.AddKey(time, pos.y);
posZ.AddKey(time, pos.z);
}
public void SetKeyframes(float time, Vector3 pos, Quaternion rot)
{
// Rotation flipping already prevented in HumanoidBaker.UpdateHumanPose().
rotX.AddKey(time, rot.x);
rotY.AddKey(time, rot.y);
rotZ.AddKey(time, rot.z);
rotW.AddKey(time, rot.w);
posX.AddKey(time, pos.x);
posY.AddKey(time, pos.y);
posZ.AddKey(time, pos.z);
}
public void MoveLastKeyframes(float time)
{
MoveLastKeyframe(time, rotX);
MoveLastKeyframe(time, rotY);
MoveLastKeyframe(time, rotZ);
MoveLastKeyframe(time, rotW);
MoveLastKeyframe(time, posX);
MoveLastKeyframe(time, posY);
MoveLastKeyframe(time, posZ);
}
// Add a copy of the first frame to the specified time
public void SetLoopFrame(float time)
{
BakerUtilities.SetLoopFrame(time, rotX);
BakerUtilities.SetLoopFrame(time, rotY);
BakerUtilities.SetLoopFrame(time, rotZ);
BakerUtilities.SetLoopFrame(time, rotW);
BakerUtilities.SetLoopFrame(time, posX);
BakerUtilities.SetLoopFrame(time, posY);
BakerUtilities.SetLoopFrame(time, posZ);
}
private void MoveLastKeyframe(float time, AnimationCurve curve)
{
Keyframe[] keys = curve.keys;
keys[keys.Length - 1].time = time;
curve.keys = keys;
}
public void MultiplyLength(AnimationCurve curve, float mlp)
{
Keyframe[] keys = curve.keys;
for (int i = 0; i < keys.Length; i++)
{
keys[i].time *= mlp;
}
curve.keys = keys;
}
// Add curves to the AnimationClip for each channel
public void SetCurves(ref AnimationClip clip, float maxError, float lengthMlp)
{
MultiplyLength(rotX, lengthMlp);
MultiplyLength(rotY, lengthMlp);
MultiplyLength(rotZ, lengthMlp);
MultiplyLength(rotW, lengthMlp);
MultiplyLength(posX, lengthMlp);
MultiplyLength(posY, lengthMlp);
MultiplyLength(posZ, lengthMlp);
BakerUtilities.ReduceKeyframes(rotX, maxError);
BakerUtilities.ReduceKeyframes(rotY, maxError);
BakerUtilities.ReduceKeyframes(rotZ, maxError);
BakerUtilities.ReduceKeyframes(rotW, maxError);
BakerUtilities.ReduceKeyframes(posX, maxError);
BakerUtilities.ReduceKeyframes(posY, maxError);
BakerUtilities.ReduceKeyframes(posZ, maxError);
BakerUtilities.SetTangentMode(rotX);
BakerUtilities.SetTangentMode(rotY);
BakerUtilities.SetTangentMode(rotZ);
BakerUtilities.SetTangentMode(rotW);
/*
BakerUtilities.SetTangentMode(posX);
BakerUtilities.SetTangentMode(posY);
BakerUtilities.SetTangentMode(posZ);
*/
clip.SetCurve(string.Empty, typeof(Animator), Qx, rotX);
clip.SetCurve(string.Empty, typeof(Animator), Qy, rotY);
clip.SetCurve(string.Empty, typeof(Animator), Qz, rotZ);
clip.SetCurve(string.Empty, typeof(Animator), Qw, rotW);
clip.SetCurve(string.Empty, typeof(Animator), Tx, posX);
clip.SetCurve(string.Empty, typeof(Animator), Ty, posY);
clip.SetCurve(string.Empty, typeof(Animator), Tz, posZ);
}
}
// Manages the Animation Curves for a single Transform that is a child of the root Transform.
[System.Serializable]
public class BakerMuscle
{
// Animation curves for each channel of the Transform
public AnimationCurve curve;
private int muscleIndex = -1;
private string propertyName;
// The custom constructor
public BakerMuscle(int muscleIndex)
{
this.muscleIndex = muscleIndex;
this.propertyName = MuscleNameToPropertyName(HumanTrait.MuscleName[muscleIndex]);
Reset();
}
private string MuscleNameToPropertyName(string n)
{
// Left fingers
if (n == "Left Index 1 Stretched") return "LeftHand.Index.1 Stretched";
if (n == "Left Index 2 Stretched") return "LeftHand.Index.2 Stretched";
if (n == "Left Index 3 Stretched") return "LeftHand.Index.3 Stretched";
if (n == "Left Middle 1 Stretched") return "LeftHand.Middle.1 Stretched";
if (n == "Left Middle 2 Stretched") return "LeftHand.Middle.2 Stretched";
if (n == "Left Middle 3 Stretched") return "LeftHand.Middle.3 Stretched";
if (n == "Left Ring 1 Stretched") return "LeftHand.Ring.1 Stretched";
if (n == "Left Ring 2 Stretched") return "LeftHand.Ring.2 Stretched";
if (n == "Left Ring 3 Stretched") return "LeftHand.Ring.3 Stretched";
if (n == "Left Little 1 Stretched") return "LeftHand.Little.1 Stretched";
if (n == "Left Little 2 Stretched") return "LeftHand.Little.2 Stretched";
if (n == "Left Little 3 Stretched") return "LeftHand.Little.3 Stretched";
if (n == "Left Thumb 1 Stretched") return "LeftHand.Thumb.1 Stretched";
if (n == "Left Thumb 2 Stretched") return "LeftHand.Thumb.2 Stretched";
if (n == "Left Thumb 3 Stretched") return "LeftHand.Thumb.3 Stretched";
if (n == "Left Index Spread") return "LeftHand.Index.Spread";
if (n == "Left Middle Spread") return "LeftHand.Middle.Spread";
if (n == "Left Ring Spread") return "LeftHand.Ring.Spread";
if (n == "Left Little Spread") return "LeftHand.Little.Spread";
if (n == "Left Thumb Spread") return "LeftHand.Thumb.Spread";
// Right fingers
if (n == "Right Index 1 Stretched") return "RightHand.Index.1 Stretched";
if (n == "Right Index 2 Stretched") return "RightHand.Index.2 Stretched";
if (n == "Right Index 3 Stretched") return "RightHand.Index.3 Stretched";
if (n == "Right Middle 1 Stretched") return "RightHand.Middle.1 Stretched";
if (n == "Right Middle 2 Stretched") return "RightHand.Middle.2 Stretched";
if (n == "Right Middle 3 Stretched") return "RightHand.Middle.3 Stretched";
if (n == "Right Ring 1 Stretched") return "RightHand.Ring.1 Stretched";
if (n == "Right Ring 2 Stretched") return "RightHand.Ring.2 Stretched";
if (n == "Right Ring 3 Stretched") return "RightHand.Ring.3 Stretched";
if (n == "Right Little 1 Stretched") return "RightHand.Little.1 Stretched";
if (n == "Right Little 2 Stretched") return "RightHand.Little.2 Stretched";
if (n == "Right Little 3 Stretched") return "RightHand.Little.3 Stretched";
if (n == "Right Thumb 1 Stretched") return "RightHand.Thumb.1 Stretched";
if (n == "Right Thumb 2 Stretched") return "RightHand.Thumb.2 Stretched";
if (n == "Right Thumb 3 Stretched") return "RightHand.Thumb.3 Stretched";
if (n == "Right Index Spread") return "RightHand.Index.Spread";
if (n == "Right Middle Spread") return "RightHand.Middle.Spread";
if (n == "Right Ring Spread") return "RightHand.Ring.Spread";
if (n == "Right Little Spread") return "RightHand.Little.Spread";
if (n == "Right Thumb Spread") return "RightHand.Thumb.Spread";
return n;
}
public void MultiplyLength(AnimationCurve curve, float mlp)
{
Keyframe[] keys = curve.keys;
for (int i = 0; i < keys.Length; i++)
{
keys[i].time *= mlp;
}
curve.keys = keys;
}
// Add curves to the AnimationClip for each channel
public void SetCurves(ref AnimationClip clip, float maxError, float lengthMlp)
{
MultiplyLength(curve, lengthMlp);
BakerUtilities.ReduceKeyframes(curve, maxError);
// BakerUtilities.SetTangentMode(curve);
clip.SetCurve(string.Empty, typeof(Animator), propertyName, curve);
}
// Clear all curves
public void Reset()
{
curve = new AnimationCurve();
}
// Record a keyframe for each channel
public void SetKeyframe(float time, float[] muscles)
{
curve.AddKey(time, muscles[muscleIndex]);
}
// Add a copy of the first frame to the specified time
public void SetLoopFrame(float time)
{
BakerUtilities.SetLoopFrame(time, curve);
}
}
//Manages the Animation Curves for a single Transform that is a child of the root Transform.
[System.Serializable]
public class BakerTransform
{
public Transform transform; // The Transform component to record
// Animation curves for each channel of the Transform
public AnimationCurve
posX, posY, posZ,
rotX, rotY, rotZ, rotW;
private string relativePath; // Path relative to the root
private bool recordPosition; // Should we record the localPosition if the transform?
private Vector3 relativePosition;
private bool isRootNode;
private Quaternion relativeRotation;
// The custom constructor
public BakerTransform(Transform transform, Transform root, bool recordPosition, bool isRootNode)
{
this.transform = transform;
this.recordPosition = recordPosition || isRootNode;
this.isRootNode = isRootNode;
relativePath = string.Empty;
#if UNITY_EDITOR
relativePath = UnityEditor.AnimationUtility.CalculateTransformPath(transform, root);
#endif
Reset();
}
public void SetRelativeSpace(Vector3 position, Quaternion rotation)
{
relativePosition = position;
relativeRotation = rotation;
}
// Add curves to the AnimationClip for each channel
public void SetCurves(ref AnimationClip clip)
{
if (recordPosition)
{
clip.SetCurve(relativePath, typeof(Transform), "localPosition.x", posX);
clip.SetCurve(relativePath, typeof(Transform), "localPosition.y", posY);
clip.SetCurve(relativePath, typeof(Transform), "localPosition.z", posZ);
}
clip.SetCurve(relativePath, typeof(Transform), "localRotation.x", rotX);
clip.SetCurve(relativePath, typeof(Transform), "localRotation.y", rotY);
clip.SetCurve(relativePath, typeof(Transform), "localRotation.z", rotZ);
clip.SetCurve(relativePath, typeof(Transform), "localRotation.w", rotW);
if (isRootNode) AddRootMotionCurves(ref clip);
// @todo probably only need to do it once for the clip
clip.EnsureQuaternionContinuity(); // DOH!
}
private void AddRootMotionCurves(ref AnimationClip clip)
{
if (recordPosition)
{
clip.SetCurve("", typeof(Animator), "MotionT.x", posX);
clip.SetCurve("", typeof(Animator), "MotionT.y", posY);
clip.SetCurve("", typeof(Animator), "MotionT.z", posZ);
}
clip.SetCurve("", typeof(Animator), "MotionQ.x", rotX);
clip.SetCurve("", typeof(Animator), "MotionQ.y", rotY);
clip.SetCurve("", typeof(Animator), "MotionQ.z", rotZ);
clip.SetCurve("", typeof(Animator), "MotionQ.w", rotW);
}
// Clear all curves
public void Reset()
{
posX = new AnimationCurve();
posY = new AnimationCurve();
posZ = new AnimationCurve();
rotX = new AnimationCurve();
rotY = new AnimationCurve();
rotZ = new AnimationCurve();
rotW = new AnimationCurve();
}
public void ReduceKeyframes(float maxError)
{
BakerUtilities.ReduceKeyframes(rotX, maxError);
BakerUtilities.ReduceKeyframes(rotY, maxError);
BakerUtilities.ReduceKeyframes(rotZ, maxError);
BakerUtilities.ReduceKeyframes(rotW, maxError);
BakerUtilities.ReduceKeyframes(posX, maxError);
BakerUtilities.ReduceKeyframes(posY, maxError);
BakerUtilities.ReduceKeyframes(posZ, maxError);
}
// Record a keyframe for each channel
public void SetKeyframes(float time)
{
if (recordPosition)
{
Vector3 pos = transform.localPosition;
if (isRootNode)
{
pos = transform.position - relativePosition;
}
posX.AddKey(time, pos.x);
posY.AddKey(time, pos.y);
posZ.AddKey(time, pos.z);
}
Quaternion rot = transform.localRotation;
if (isRootNode)
{
rot = Quaternion.Inverse(relativeRotation) * transform.rotation;
}
rotX.AddKey(time, rot.x);
rotY.AddKey(time, rot.y);
rotZ.AddKey(time, rot.z);
rotW.AddKey(time, rot.w);
}
// Add a copy of the first frame to the specified time
public void AddLoopFrame(float time)
{
// TODO change to SetLoopFrame
if (recordPosition && !isRootNode)
{
posX.AddKey(time, posX.keys[0].value);
posY.AddKey(time, posY.keys[0].value);
posZ.AddKey(time, posZ.keys[0].value);
}
rotX.AddKey(time, rotX.keys[0].value);
rotY.AddKey(time, rotY.keys[0].value);
rotZ.AddKey(time, rotZ.keys[0].value);
rotW.AddKey(time, rotW.keys[0].value);
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 582052db0a6096149a7b2b75914ef3a6
timeCreated: 1516263395
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,194 @@
using UnityEngine;
using System.Collections;
using UnityEngine.Playables;
namespace RootMotion
{
/// <summary>
/// Baker for Humanoid animation.
/// </summary>
public class HumanoidBaker : Baker
{
/// <summary>
/// Should the hand IK curves be added to the animation? Disable this if the original hand positions are not important when using the clip on another character via Humanoid retargeting.
/// </summary>
[Tooltip("Should the hand IK curves be added to the animation? Disable this if the original hand positions are not important when using the clip on another character via Humanoid retargeting.")]
public bool bakeHandIK = true;
/// <summary>
/// Max keyframe reduction error for the Root.Q/T, LeftFoot IK and RightFoot IK channels. Having a larger error value for 'Key Reduction Error' and a smaller one for this enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.
/// </summary>
[Tooltip("Max keyframe reduction error for the Root.Q/T, LeftFoot IK and RightFoot IK channels. Having a larger error value for 'Key Reduction Error' and a smaller one for this enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.")]
[Range(0f, 0.1f)] public float IKKeyReductionError;
/// <summary>
/// Frame rate divider for the muscle curves. If you had 'Frame Rate' set to 30, and this value set to 3, the muscle curves will be baked at 10 fps. Only the Root Q/T and Hand and Foot IK curves will be baked at 30. This enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.
/// </summary>
[Tooltip("Frame rate divider for the muscle curves. If you have 'Frame Rate' set to 30, and this value set to 3, the muscle curves will be baked at 10 fps. Only the Root Q/T and Hand and Foot IK curves will be baked at 30. This enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.")]
[Range(1, 9)] public int muscleFrameRateDiv = 1;
private BakerMuscle[] bakerMuscles;
private BakerHumanoidQT rootQT;
private BakerHumanoidQT leftFootQT;
private BakerHumanoidQT rightFootQT;
private BakerHumanoidQT leftHandQT;
private BakerHumanoidQT rightHandQT;
private float[] muscles = new float[0];
private HumanPose pose = new HumanPose();
private HumanPoseHandler handler;
private Vector3 bodyPosition;
private Quaternion bodyRotation = Quaternion.identity;
private int mN = 0;
private Quaternion lastBodyRotation = Quaternion.identity;
void Awake()
{
animator = GetComponent<Animator>();
director = GetComponent<PlayableDirector>();
if (mode == Mode.AnimationStates || mode == Mode.AnimationClips)
{
if (animator == null || !animator.isHuman)
{
Debug.LogError("HumanoidBaker GameObject does not have a Humanoid Animator component, can not bake.");
enabled = false;
return;
}
animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
}
else if (mode == Mode.PlayableDirector)
{
if (director == null)
{
Debug.LogError("HumanoidBaker GameObject does not have a PlayableDirector component, can not bake.");
}
}
muscles = new float[HumanTrait.MuscleCount];
bakerMuscles = new BakerMuscle[HumanTrait.MuscleCount];
for (int i = 0; i < bakerMuscles.Length; i++)
{
bakerMuscles[i] = new BakerMuscle(i);
}
rootQT = new BakerHumanoidQT("Root");
leftFootQT = new BakerHumanoidQT(animator.GetBoneTransform(HumanBodyBones.LeftFoot), AvatarIKGoal.LeftFoot, "LeftFoot");
rightFootQT = new BakerHumanoidQT(animator.GetBoneTransform(HumanBodyBones.RightFoot), AvatarIKGoal.RightFoot, "RightFoot");
leftHandQT = new BakerHumanoidQT(animator.GetBoneTransform(HumanBodyBones.LeftHand), AvatarIKGoal.LeftHand, "LeftHand");
rightHandQT = new BakerHumanoidQT(animator.GetBoneTransform(HumanBodyBones.RightHand), AvatarIKGoal.RightHand, "RightHand");
handler = new HumanPoseHandler(animator.avatar, animator.transform);
}
protected override Transform GetCharacterRoot()
{
return animator.transform;
}
protected override void OnStartBaking()
{
rootQT.Reset();
leftFootQT.Reset();
rightFootQT.Reset();
leftHandQT.Reset();
rightHandQT.Reset();
for (int i = 0; i < bakerMuscles.Length; i++)
{
bakerMuscles[i].Reset();
}
mN = muscleFrameRateDiv;
lastBodyRotation = Quaternion.identity;
}
protected override void OnSetLoopFrame(float time)
{
for (int i = 0; i < bakerMuscles.Length; i++) bakerMuscles[i].SetLoopFrame(time);
rootQT.MoveLastKeyframes(time);
leftFootQT.SetLoopFrame(time);
rightFootQT.SetLoopFrame(time);
leftHandQT.SetLoopFrame(time);
rightHandQT.SetLoopFrame(time);
}
protected override void OnSetCurves(ref AnimationClip clip)
{
float length = bakerMuscles[0].curve.keys[bakerMuscles[0].curve.keys.Length - 1].time;
float lengthMlp = mode != Mode.Realtime ? clipLength / length : 1f;
for (int i = 0; i < bakerMuscles.Length; i++) bakerMuscles[i].SetCurves(ref clip, keyReductionError, lengthMlp);
rootQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
leftFootQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
rightFootQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
if (bakeHandIK)
{
leftHandQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
rightHandQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
}
}
protected override void OnSetKeyframes(float time, bool lastFrame)
{
// Skip muscle frames
mN++;
bool updateMuscles = true;
if (mN < muscleFrameRateDiv && !lastFrame)
{
updateMuscles = false;
}
if (mN >= muscleFrameRateDiv) mN = 0;
UpdateHumanPose();
if (updateMuscles)
{
for (int i = 0; i < bakerMuscles.Length; i++) bakerMuscles[i].SetKeyframe(time, muscles);
}
rootQT.SetKeyframes(time, bodyPosition, bodyRotation);
Vector3 bodyPositionScaled = bodyPosition * animator.humanScale;
leftFootQT.SetIKKeyframes(time, animator.avatar, animator.humanScale, bodyPositionScaled, bodyRotation);
rightFootQT.SetIKKeyframes(time, animator.avatar, animator.humanScale, bodyPositionScaled, bodyRotation);
leftHandQT.SetIKKeyframes(time, animator.avatar, animator.humanScale, bodyPositionScaled, bodyRotation);
rightHandQT.SetIKKeyframes(time, animator.avatar, animator.humanScale, bodyPositionScaled, bodyRotation);
}
private void UpdateHumanPose()
{
handler.GetHumanPose(ref pose);
bodyPosition = pose.bodyPosition;
bodyRotation = pose.bodyRotation;
bodyRotation = BakerUtilities.EnsureQuaternionContinuity(lastBodyRotation, bodyRotation);
lastBodyRotation = bodyRotation;
for (int i = 0; i < pose.muscles.Length; i++)
{
muscles[i] = pose.muscles[i];
}
}
#if UNITY_EDITOR
protected override void SetClipSettings(AnimationClip clip, UnityEditor.AnimationClipSettings settings)
{
settings.loopBlendOrientation = true;
settings.loopBlendPositionY = true;
settings.keepOriginalOrientation = true;
settings.keepOriginalPositionY = true;
}
#endif
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: efcc0ec5ed265a340a1412edb9110337
timeCreated: 1516287616
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 15000
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: c41cf13236c01a747b3dfb963402b3a0
folderAsset: yes
timeCreated: 1516620909
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a4b02f60233a6cf4eb1c424f90323213
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3451f091c656bfc429396cc701ac5b8d
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 7400000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,69 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!91 &9100000
AnimatorController:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Humanoid Baker Clip Sampler
serializedVersion: 5
m_AnimatorParameters: []
m_AnimatorLayers:
- serializedVersion: 5
m_Name: Base Layer
m_StateMachine: {fileID: 110737558}
m_Mask: {fileID: 0}
m_Motions: []
m_Behaviours: []
m_BlendingMode: 0
m_SyncedLayerIndex: -1
m_DefaultWeight: 0
m_IKPass: 0
m_SyncedLayerAffectsTiming: 0
m_Controller: {fileID: 9100000}
--- !u!1102 &110235224
AnimatorState:
serializedVersion: 5
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Clip 1
m_Speed: 1
m_CycleOffset: 0
m_Transitions: []
m_StateMachineBehaviours: []
m_Position: {x: 50, y: 50, z: 0}
m_IKOnFeet: 1
m_WriteDefaultValues: 1
m_Mirror: 0
m_SpeedParameterActive: 0
m_MirrorParameterActive: 0
m_CycleOffsetParameterActive: 0
m_TimeParameterActive: 0
m_Motion: {fileID: 7400000, guid: 739b2627204c24240aa40c4f67f59d0e, type: 3}
m_Tag:
m_SpeedParameter:
m_MirrorParameter:
m_CycleOffsetParameter:
m_TimeParameter:
--- !u!1107 &110737558
AnimatorStateMachine:
serializedVersion: 5
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Base Layer
m_ChildStates:
- serializedVersion: 1
m_State: {fileID: 110235224}
m_Position: {x: 300, y: 36, z: 0}
m_ChildStateMachines: []
m_AnyStateTransitions: []
m_EntryTransitions: []
m_StateMachineTransitions: {}
m_StateMachineBehaviours: []
m_AnyStatePosition: {x: 50, y: 20, z: 0}
m_EntryPosition: {x: 50, y: 120, z: 0}
m_ExitPosition: {x: 800, y: 120, z: 0}
m_ParentStateMachinePosition: {x: 800, y: 20, z: 0}
m_DefaultState: {fileID: 110235224}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 24d41cb619dc9dc42bf10705eb128c97
timeCreated: 1516284817
licenseType: Store
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0bd8d9a8cbacde343967c95c4458318e
timeCreated: 1517387718
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3349a7526568cf042bf8609694db3327
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,53 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RootMotion.Demos
{
// Adds simple FK rotation offset to bones.
public class FKOffset : MonoBehaviour
{
[System.Serializable]
public class Offset
{
[HideInInspector][SerializeField] public string name;
public HumanBodyBones bone;
public Vector3 rotationOffset;
private Transform t;
public void Apply(Animator animator)
{
if (t == null) t = animator.GetBoneTransform(bone);
if (t == null) return;
t.localRotation *= Quaternion.Euler(rotationOffset);
}
}
public Offset[] offsets;
private Animator animator;
private void Start()
{
animator = GetComponent<Animator>();
}
private void LateUpdate()
{
foreach (Offset offset in offsets)
{
offset.Apply(animator);
}
}
private void OnDrawGizmosSelected()
{
foreach (Offset offset in offsets)
{
offset.name = offset.bone.ToString();
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ea198996b9a58624b82f921e56faf4ba
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 10875975faa2a3c4f815508f7f376c21
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: fe88a087b0795174f9c8ec2369f4ccb2
folderAsset: yes
timeCreated: 1516620937
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,176 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEngine.Playables;
using System;
namespace RootMotion
{
public class BakerInspector : Editor
{
protected void DrawKeyframeSettings(Baker script)
{
if (script.isBaking) return;
EditorGUILayout.Space();
EditorGUILayout.PropertyField(serializedObject.FindProperty("frameRate"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("keyReductionError"));
}
protected void DrawModeSettings(Baker script)
{
if (script.isBaking) return;
EditorGUILayout.Space();
EditorGUILayout.PropertyField(serializedObject.FindProperty("mode"));
switch (script.mode)
{
case Baker.Mode.AnimationClips:
EditorGUILayout.PropertyField(serializedObject.FindProperty("animationClips"), true);
EditorGUILayout.PropertyField(serializedObject.FindProperty("appendName"));
break;
case Baker.Mode.AnimationStates:
EditorGUILayout.PropertyField(serializedObject.FindProperty("loop"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("animationStates"), true);
EditorGUILayout.PropertyField(serializedObject.FindProperty("appendName"));
break;
case Baker.Mode.PlayableDirector:
EditorGUILayout.PropertyField(serializedObject.FindProperty("loop"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("saveName"));
break;
default:
EditorGUILayout.PropertyField(serializedObject.FindProperty("saveName"));
break;
}
//EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
EditorGUILayout.LabelField(new GUIContent("Save To Folder"));
if (EditorGUILayout.DropdownButton(new GUIContent(serializedObject.FindProperty("saveToFolder").stringValue, "The folder to save the baked AnimationClips to."), FocusType.Passive, GUILayout.MaxWidth(400)))
{
serializedObject.FindProperty("saveToFolder").stringValue = SaveClipFolderPanel.Apply(serializedObject.FindProperty("saveToFolder").stringValue);
}
//EditorGUILayout.EndHorizontal();
}
private void TryBake(Baker script)
{
switch (script.mode)
{
case Baker.Mode.AnimationClips:
if (script.animator == null)
{
EditorGUILayout.LabelField("No Animator found on Baker GameObject", EditorStyles.helpBox);
return;
}
if (script.animator.isHuman && script.animator.runtimeAnimatorController == null)
{
EditorGUILayout.LabelField("Humanoid Animator needs to have a valid Controller assigned for clip baking (Unity crash bug)", EditorStyles.helpBox);
return;
}
if (script.animationClips.Length == 0)
{
EditorGUILayout.LabelField("Please add AnimationClips to bake", EditorStyles.helpBox);
return;
}
foreach (AnimationClip clip in script.animationClips)
{
if (clip == null)
{
EditorGUILayout.LabelField("One of the AnimationClips is null, can not bake.", EditorStyles.helpBox);
return;
}
}
if (GUILayout.Button("Bake Animation Clips")) script.BakeClip();
return;
case Baker.Mode.AnimationStates:
if (script.animator == null)
{
EditorGUILayout.LabelField("No Animator found on Baker GameObject", EditorStyles.helpBox);
return;
}
if (script.animationStates.Length == 0)
{
EditorGUILayout.LabelField("Please add Animation State names to bake. The Animator must contain AnimationStates with matching names. If AnimationState names match with clip names used in them, you can have the Baker fill the names in automatically by right-clicking on the component header and selecting 'Find Animation States'.", EditorStyles.helpBox);
return;
}
for (int i = 0; i < script.animationStates.Length; i++)
{
if (script.animationStates[i] == string.Empty || script.animationStates[i] == "")
{
EditorGUILayout.LabelField("One of the animation state names in 'Animation States' is empty, can not bake.", EditorStyles.helpBox);
return;
}
}
if (GUILayout.Button("Bake Animation States")) script.BakeClip();
return;
case Baker.Mode.PlayableDirector:
if (script.director == null)
{
EditorGUILayout.LabelField("No PlayableDirector found on Baker GameObject", EditorStyles.helpBox);
return;
}
if (GUILayout.Button("Bake Timeline")) script.BakeClip();
break;
case Baker.Mode.Realtime:
if (GUILayout.Button("Start Baking")) script.StartBaking();
return;
}
}
protected void DrawButtons(Baker script)
{
if (!script.enabled) return;
if (script.animator == null)
{
serializedObject.FindProperty("animator").objectReferenceValue = script.GetComponent<Animator>();
}
if (script.director == null)
{
serializedObject.FindProperty("director").objectReferenceValue = script.GetComponent<PlayableDirector>();
}
if (!Application.isPlaying)
{
EditorGUILayout.LabelField("Enter Play Mode to bake.", EditorStyles.helpBox);
return;
}
if (!script.isBaking)
{
TryBake(script);
}
else
{
GUI.color = Color.red;
switch (script.mode)
{
case Baker.Mode.Realtime:
if (GUILayout.Button("Stop Baking")) script.StopBaking();
break;
default:
GUILayout.Label("Baking Progress: " + System.Math.Round(script.bakingProgress, 2));
break;
}
GUI.color = Color.white;
EditorUtility.SetDirty(script);
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: dcf5801ad3ff7fa43b06824f09d82160
timeCreated: 1516619065
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,52 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion
{
[CustomEditor(typeof(GenericBaker))]
public class GenericBakerInspector : BakerInspector
{
private GenericBaker script { get { return target as GenericBaker; } }
private MonoScript monoScript;
void OnEnable()
{
// Changing the script execution order
if (!Application.isPlaying)
{
monoScript = MonoScript.FromMonoBehaviour(script);
int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
if (currentExecutionOrder != 15001) MonoImporter.SetExecutionOrder(monoScript, 15001);
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawKeyframeSettings(script as Baker);
DrawGenericKeyframeSettings(script);
DrawModeSettings(script as Baker);
DrawButtons(script as Baker);
if (serializedObject.ApplyModifiedProperties())
{
EditorUtility.SetDirty(script);
}
}
private void DrawGenericKeyframeSettings(GenericBaker script)
{
if (script.isBaking) return;
EditorGUILayout.PropertyField(serializedObject.FindProperty("markAsLegacy"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("root"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("rootNode"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("ignoreList"), true);
EditorGUILayout.PropertyField(serializedObject.FindProperty("bakePositionList"), true);
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8f544a5bc87054e74ac2e415889ba75a
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 73b96cf8495867d429c9c5b31ff6d6da
folderAsset: yes
timeCreated: 1516621014
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,38 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion
{
public static class AnimationUtilityExtended
{
/// <summary>
/// Copies the curves with the specified property names from clipFrom to clipTo.
/// </summary>
/// <param name="fromClip">copy from clip.</param>
/// <param name="toClip">paste to clip</param>
/// <param name="propertyNames">Property names ("Root.T", "Root.Q", "LeftFoot.T"...).</param>
public static void CopyCurves(AnimationClip fromClip, AnimationClip toClip, string[] propertyNames)
{
EditorCurveBinding[] bindings = AnimationUtility.GetCurveBindings(fromClip);
for (int i = 0; i < bindings.Length; i++)
{
for (int n = 0; n < propertyNames.Length; n++)
{
if (bindings[i].propertyName == propertyNames[n])
{
CopyCurve(fromClip, toClip, bindings[i]);
}
}
}
}
public static void CopyCurve(AnimationClip fromClip, AnimationClip toClip, EditorCurveBinding binding)
{
AnimationCurve curve = AnimationUtility.GetEditorCurve(fromClip, binding);
toClip.SetCurve(string.Empty, typeof(Animator), binding.propertyName, curve);
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 054c55a0c5c10dc4fafcfd81aeaaec56
timeCreated: 1516620625
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,22 @@
using UnityEngine;
using UnityEditor;
using System.IO;
using System;
namespace RootMotion
{
public class SaveClipFolderPanel : EditorWindow
{
public static string Apply(string currentPath)
{
string path = EditorUtility.SaveFolderPanel("Save clip(s) to folder", currentPath, "");
if (path.Length != 0)
{
return path.Substring(path.IndexOf("Assets/"));
}
return currentPath;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7edb6cbf0a3b9924d8f631c4c00fd38a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,52 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion
{
[CustomEditor(typeof(HumanoidBaker))]
public class HumanoidBakerInspector : BakerInspector
{
private HumanoidBaker script { get { return target as HumanoidBaker; } }
private MonoScript monoScript;
void OnEnable()
{
// Changing the script execution order
if (!Application.isPlaying)
{
monoScript = MonoScript.FromMonoBehaviour(script);
int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
if (currentExecutionOrder != 15000) MonoImporter.SetExecutionOrder(monoScript, 15000);
}
}
// TODO Move this to BakerInspector.cs
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawKeyframeSettings(script as Baker);
DrawHumanoidKeyframeSettings(script);
DrawModeSettings(script as Baker);
DrawButtons(script as Baker);
if (serializedObject.ApplyModifiedProperties())
{
EditorUtility.SetDirty(script);
}
}
protected void DrawHumanoidKeyframeSettings(HumanoidBaker script)
{
if (script.isBaking) return;
EditorGUILayout.PropertyField(serializedObject.FindProperty("IKKeyReductionError"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("muscleFrameRateDiv"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("bakeHandIK"));
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f8139af98945e154885b65eedbb102cc
timeCreated: 1516265598
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 100c77ad1e0b943c5b6e6e67b5649801
folderAsset: yes
timeCreated: 1436186340
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,63 @@
using UnityEditor;
using UnityEngine;
namespace RootMotion.Dynamics {
// Custom drawer for BehaviourPuppet MasterProps.
[CustomPropertyDrawer (typeof (BehaviourPuppet.MasterProps))]
public class BehaviourPuppetMasterPropsDrawer : PropertyDrawer {
private float lineHeight = 22f;
public override float GetPropertyHeight(SerializedProperty prop, GUIContent label) {
lineHeight = base.GetPropertyHeight(prop, label);
int enumValueIndex = prop.FindPropertyRelative("normalMode").enumValueIndex;
switch(enumValueIndex) {
case 1: return lineHeight * 2;
case 2: return lineHeight * 3;
default: return lineHeight;
}
}
private void NextLine(ref Rect pos) {
pos = EditorGUI.IndentedRect(pos);
pos.width -= pos.x - pos.x;
pos.x = pos.x;
pos.y += lineHeight;
pos.height = lineHeight;
}
public override void OnGUI (Rect pos, SerializedProperty prop, GUIContent label) {
int indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField (new Rect(pos.x, pos.y, pos.width, lineHeight), prop.FindPropertyRelative ("normalMode"), new GUIContent("Normal Mode", "Active mode keeps the puppet and it's mapping active at all times. " +
"Unmapped mode blends in mapping only if the puppet becomes in contact with something and blends out again later to maintain 100% animation accuracy while not in contact. " +
"If Kinematic, will set the PuppetMaster.mode to Active when any of the muscles collides with something (static colliders are ignored if 'Activate On Static Collisions' is false) or is hit. PuppetMaster.mode will be set to Kinematic when all muscles are pinned and the puppet is in normal Puppet state. This will increase performance and enable you to have full animation accuracy when PuppetMaster is not needed. Note that collision events are only broadcasted if one of the Rigidbodies is not kinematic, so if you need 2 characters to wake up each other, one has to be active."));
int enumValueIndex = prop.FindPropertyRelative("normalMode").enumValueIndex;
switch(enumValueIndex) {
case 1:
NextLine(ref pos);
EditorGUI.PropertyField (pos, prop.FindPropertyRelative ("mappingBlendSpeed"), new GUIContent("Mapping Blend Speed", "The speed of blending in mapping in case of contact."));
break;
case 2:
NextLine(ref pos);
EditorGUI.PropertyField (pos, prop.FindPropertyRelative ("activateOnStaticCollisions"), new GUIContent("Activate On Static Collisions", "The speed of blending in mapping in case of contact."));
NextLine(ref pos);
EditorGUI.PropertyField (pos, prop.FindPropertyRelative ("activateOnImpulse"), new GUIContent("Activate On Impulse", "Minimum collision impulse for activating the puppet."));
break;
default: break;
}
EditorGUI.EndChangeCheck();
EditorGUI.indentLevel = indent;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 78a5ae1e71291429f8916d4c02a498b7
timeCreated: 1452015016
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,254 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion.Dynamics
{
[CustomEditor(typeof(PropMuscle))]
public class PropMuscleInspector : Editor
{
private PropMuscle script { get { return target as PropMuscle; } }
private GUIStyle style = new GUIStyle();
private GUIStyle miniLabelStyle = new GUIStyle();
private static Color pro = new Color(0.5f, 0.7f, 0.3f, 1f);
private static Color free = new Color(0.2f, 0.3f, 0.1f, 1f);
private static Color sceneColor = new Color(0.2f, 0.7f, 1f);
public override void OnInspectorGUI()
{
if (script == null) return;
serializedObject.Update();
style.wordWrap = true;
style.normal.textColor = EditorGUIUtility.isProSkin ? pro : free;
miniLabelStyle.wordWrap = true;
miniLabelStyle.fontSize = 10;
miniLabelStyle.normal.textColor = EditorStyles.miniLabel.normal.textColor;
if (!Application.isPlaying)
{
if (GUILayout.Button("Remove This Prop Muscle"))
{
//int index = script.muscle.index;
//Debug.Log(index);
var puppetMasterS = new SerializedObject(script.puppetMaster);
SerializedProperty muscles = puppetMasterS.FindProperty("muscles");
int index = 0;
ConfigurableJoint joint = script.GetComponent<ConfigurableJoint>();
for (int i = 0; i < puppetMasterS.FindProperty("muscles").arraySize; i++)
{
muscles.GetArrayElementAtIndex(i).FindPropertyRelative("index").intValue = i;
if (muscles.GetArrayElementAtIndex(i).FindPropertyRelative("joint").objectReferenceValue == joint) index = i;
}
/*
if (script.muscle.additionalPin != null)
{
script.muscle.additionalPin.gameObject.hideFlags = HideFlags.None;
script.muscle.additionalPinTarget.gameObject.hideFlags = HideFlags.None;
}
script.muscle.target.gameObject.hideFlags = HideFlags.None;
*/
var target = script.muscle.target;
muscles.DeleteArrayElementAtIndex(index);
for (int i = 0; i < puppetMasterS.FindProperty("muscles").arraySize; i++)
{
muscles.GetArrayElementAtIndex(i).FindPropertyRelative("index").intValue = i;
}
puppetMasterS.ApplyModifiedProperties();
PuppetMasterInspector.DestroyImmediateSafe(target.gameObject);
PuppetMasterInspector.DestroyImmediateSafe(script.gameObject);
return;
}
}
DrawDefaultInspector();
//GUILayout.Space(10);
if (!Application.isPlaying)
{
if (script.muscle.additionalPin == null)
{
if (GUILayout.Button("Add Additional Pin"))
{
AddAdditionalPin();
}
}
else
{
if (GUILayout.Button("Remove Additional Pin"))
{
RemoveAdditionalPin();
}
}
EditorGUILayout.LabelField("Additional Pins help to pin this prop muscle to animation from another point. Without it, the prop muscle would be actuated by Muscle Spring only, which is likely not enough to follow fast swinging animations. Move the additional pin by 'Additional Pin Offset' towards the end of the prop (tip of the sword).", miniLabelStyle);
}
serializedObject.ApplyModifiedProperties();
}
private bool AddAdditionalPin()
{
if (script.muscle.additionalPin != null) return false;
ConfigurableJoint additionalJoint = null;
Transform additionalTarget = null;
AddAdditionalPinUnserialized(script, out additionalJoint, out additionalTarget);
var puppetMasterS = new SerializedObject(script.puppetMaster);
puppetMasterS.FindProperty("muscles").GetArrayElementAtIndex(script.muscle.index).FindPropertyRelative("additionalPin").objectReferenceValue = additionalJoint;
puppetMasterS.FindProperty("muscles").GetArrayElementAtIndex(script.muscle.index).FindPropertyRelative("additionalPinTarget").objectReferenceValue = additionalTarget;
puppetMasterS.ApplyModifiedProperties();
serializedObject.ApplyModifiedProperties();
//muscle.additionalPin.gameObject.hideFlags = HideFlags.HideInHierarchy;
//muscle.additionalPinTarget.gameObject.hideFlags = HideFlags.HideInHierarchy;
return true;
}
public static void AddAdditionalPinUnserialized(PropMuscle script, out ConfigurableJoint joint, out Transform target)
{
var addGO = new GameObject("Additional Pin");
addGO.gameObject.layer = script.gameObject.layer;
addGO.transform.parent = script.transform;
addGO.transform.localPosition = script.additionalPinOffset;
addGO.transform.localRotation = Quaternion.identity;
//script.lastAdditionalPinOffset = additionalPinOffset;
addGO.AddComponent<Rigidbody>();
joint = addGO.AddComponent<ConfigurableJoint>();
joint.connectedBody = script.muscle.joint.GetComponent<Rigidbody>();
joint.autoConfigureConnectedAnchor = false;
joint.connectedAnchor = script.additionalPinOffset;
joint.xMotion = ConfigurableJointMotion.Locked;
joint.yMotion = ConfigurableJointMotion.Locked;
joint.zMotion = ConfigurableJointMotion.Locked;
joint.angularXMotion = ConfigurableJointMotion.Locked;
joint.angularYMotion = ConfigurableJointMotion.Locked;
joint.angularZMotion = ConfigurableJointMotion.Locked;
var addTargetGO = new GameObject("Additional Pin Target");
addTargetGO.layer = script.muscle.target.gameObject.layer;
addTargetGO.transform.parent = script.muscle.target;
addTargetGO.transform.position = addGO.transform.position;
addTargetGO.transform.rotation = addGO.transform.rotation;
target = addTargetGO.transform;
}
private bool RemoveAdditionalPin()
{
if (script.muscle.additionalPin == null) return false;
//script.muscle.additionalPin.gameObject.hideFlags = HideFlags.None;
//script.muscle.additionalPinTarget.gameObject.hideFlags = HideFlags.None;
PuppetMasterInspector.DestroyImmediateSafe(script.muscle.additionalPin.gameObject);
PuppetMasterInspector.DestroyImmediateSafe(script.muscle.additionalPinTarget.gameObject);
var puppetMasterS = new SerializedObject(script.puppetMaster);
puppetMasterS.FindProperty("muscles").GetArrayElementAtIndex(script.muscle.index).FindPropertyRelative("additionalPin").objectReferenceValue = null;
puppetMasterS.FindProperty("muscles").GetArrayElementAtIndex(script.muscle.index).FindPropertyRelative("additionalPinTarget").objectReferenceValue = null;
puppetMasterS.ApplyModifiedProperties();
return true;
}
private static float GetHandleSize(Vector3 position)
{
float s = HandleUtility.GetHandleSize(position) * 0.1f;
return Mathf.Lerp(s, 0.025f, 0.2f);
}
void OnSceneGUI() {
DrawScene(script);
}
private static void CubeCapSafe(Vector3 position, Quaternion rotation, float size)
{
#if UNITY_5_6_OR_NEWER
Handles.CubeHandleCap(0, position, rotation, size, EventType.Repaint);
#else
Handles.CubeCap(0, position, rotation, size);
#endif
}
private static void SphereCapSafe(Vector3 position, Quaternion rotation, float size)
{
#if UNITY_5_6_OR_NEWER
Handles.SphereHandleCap(0, position, rotation, size, EventType.Repaint);
#else
Handles.SphereCap(0, position, rotation, size);
#endif
}
public static void DrawScene(PropMuscle script)
{
if (script == null) return;
if (Application.isPlaying) return;
GUIStyle sceneLabelStyle = new GUIStyle();
sceneLabelStyle.wordWrap = false;
sceneLabelStyle.normal.textColor = sceneColor;
Handles.color = sceneColor;
float size = GetHandleSize(script.transform.position);
if (Selection.activeGameObject == script.gameObject)
{
Handles.Label(script.transform.position + script.transform.forward * size * 2f, new GUIContent(script.transform.name), sceneLabelStyle);
} else
{
Handles.Label(script.transform.position + script.transform.forward * size * 2f, new GUIContent("Click to select Prop Muscle"), sceneLabelStyle);
}
if (Selection.activeGameObject == script.gameObject)
{
CubeCapSafe(script.transform.position, script.transform.rotation, size * 2f);
} else
{
if (DotButton(script.transform.position, script.transform.rotation, size, size))
{
Selection.activeGameObject = script.gameObject;
}
}
if (script.muscle.additionalPin != null)
{
Handles.DrawLine(script.transform.position, script.muscle.additionalPin.transform.position);
SphereCapSafe(script.muscle.additionalPin.transform.position, script.muscle.additionalPin.transform.rotation, size);
if (Selection.activeGameObject == script.gameObject)
{
Handles.Label(script.muscle.additionalPin.transform.position + script.transform.forward * size * 2f, new GUIContent("Additional Pin"), sceneLabelStyle);
}
}
Handles.color = Color.white;
}
public static bool DotButton(Vector3 position, Quaternion direction, float size, float pickSize)
{
#if UNITY_5_6_OR_NEWER
return Handles.Button(position, direction, size, pickSize, Handles.DotHandleCap);
#else
return Handles.Button(position, direction, size, pickSize, Handles.DotCap);
#endif
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 2d0583daa68217f49b271ee02c9374f5
timeCreated: 1550562021
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,21 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
namespace RootMotion.Dynamics {
[CustomEditor(typeof(PuppetMasterHumanoidConfig))]
public class PuppetMasterHumanoidConfigInspector : Editor {
private PuppetMasterHumanoidConfig script { get { return target as PuppetMasterHumanoidConfig; } }
public override void OnInspectorGUI() {
foreach (PuppetMasterHumanoidConfig.HumanoidMuscle m in script.muscles) {
m.name = m.bone.ToString();
}
DrawDefaultInspector ();
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f97a5dd098e6d624caf82f29ed6896d2
timeCreated: 1485252527
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,437 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using System;
namespace RootMotion.Dynamics
{
[CustomEditor(typeof(PuppetMaster))]
public class PuppetMasterInspector : Editor
{
private PuppetMaster script { get { return target as PuppetMaster; } }
private Transform animatedCharacter;
private bool isValid;
private int characterControllerLayer = 8;
private int ragdollLayer = 9;
private ConfigurableJoint addPropMuscleTo;
private MonoScript monoScript;
private Animator targetAnimator;
private SkinnedMeshRenderer[] skinnedMeshRenderers = new SkinnedMeshRenderer[0];
// Colors
private GUIStyle style = new GUIStyle();
private GUIStyle miniLabelStyle = new GUIStyle();
private static Color pro = new Color(0.5f, 0.7f, 0.3f, 1f);
private static Color free = new Color(0.2f, 0.3f, 0.1f, 1f);
#region Inspector
void OnEnable()
{
if (!Application.isPlaying)
{
monoScript = MonoScript.FromMonoBehaviour(script);
int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
if (currentExecutionOrder != 10100) MonoImporter.SetExecutionOrder(monoScript, 10100);
// Fix negative collider sizes for ragdolls created before PuppetMaster 0.3
BoxCollider[] boxColliders = script.GetComponentsInChildren<BoxCollider>();
foreach (BoxCollider box in boxColliders)
{
box.size = new Vector3(Mathf.Abs(box.size.x), Mathf.Abs(box.size.y), Mathf.Abs(box.size.z));
}
CapsuleCollider[] capsuleColliders = script.GetComponentsInChildren<CapsuleCollider>();
foreach (CapsuleCollider capsule in capsuleColliders)
{
capsule.height = Mathf.Abs(capsule.height);
capsule.radius = Mathf.Abs(capsule.radius);
}
if (script.transform.parent != null)
{
targetAnimator = script.transform.parent.GetComponentInChildren<Animator>();
}
}
else
{
if (script.initiated) targetAnimator = script.targetAnimator;
}
if (script.transform.parent != null)
{
skinnedMeshRenderers = script.transform.parent.GetComponentsInChildren<SkinnedMeshRenderer>();
}
isValid = IsValid();
}
private bool IsValid()
{
if (script.muscles.Length > 0) return true;
ConfigurableJoint[] joints = script.gameObject.GetComponentsInChildren<ConfigurableJoint>();
if (joints == null || joints.Length == 0)
{
return false;
}
if (animatedCharacter == null) animatedCharacter = script.transform;
return true;
}
public override void OnInspectorGUI()
{
if (script == null) return;
serializedObject.Update();
if (script.muscles.Length > 0 && script.muscles[0].target != null && script.targetRoot == null) script.targetRoot = script.FindTargetRootRecursive(script.muscles[0].target);
style.wordWrap = true;
style.normal.textColor = EditorGUIUtility.isProSkin ? pro : free;
miniLabelStyle.wordWrap = true;
miniLabelStyle.fontSize = 10;
miniLabelStyle.normal.textColor = EditorStyles.miniLabel.normal.textColor;
if (!isValid)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(
"To set up PuppetMaster, add the component to a ragdoll character that is built with ConfigurableJoints. " +
"If your ragdoll uses other types of joints, you can easily convert them by selecting the character and clicking on GameObject/Convert To ConfigurableJoints."
, style);
EditorGUILayout.Space();
return;
}
if (!Application.isPlaying)
{
for (int i = 0; i < script.muscles.Length; i++)
{
script.muscles[i].index = i;
}
}
foreach (Muscle m in script.muscles)
{
if (m.joint == null)
{
m.name = "Missing Joint Reference!";
}
else if (m.target == null)
{
m.name = "Missing Target Reference!";
}
else m.name = m.joint.name;
}
if (script.muscles.Length == 0)
{
GUILayout.Space(5);
animatedCharacter = (Transform)EditorGUILayout.ObjectField(new GUIContent("Animated Target", "If it is assigned to the same GameObject, it will be duplicated and cleaned up of all the ragdoll components. It can also be an instance of the character or even another character as long as the positions of the bones match. The rotations of the bones don't need to be identical. That makes it possible to share ragdoll structures and is also most useful when the feet bones are not aligned to the ground (like Mixamo characters). In that case you can simply rotate the ragdoll's feet to align, keeping the target's feet where they are."), animatedCharacter, typeof(Transform), true);
GUILayout.Space(5);
characterControllerLayer = EditorGUILayout.IntField(new GUIContent("Character Controller Layer", "The layer to assign the character controller to. Collisions between this layer and the 'Ragdoll Layer' will be ignored, or else the ragdoll would collide with the character controller."), characterControllerLayer);
ragdollLayer = EditorGUILayout.IntField(new GUIContent("Ragdoll Layer", "The layer to assign the PuppetMaster and all it's muscles to. Collisions between this layer and the 'Character Controller Layer' will be ignored, or else the ragdoll would collide with the character controller."), ragdollLayer);
if (characterControllerLayer == ragdollLayer)
{
GUILayout.Space(5);
EditorGUILayout.LabelField(
"The 'Character Controller Layer' must not be the same as the 'Ragdoll Layer', your ragdoll bones would collide with the character controller."
, style);
EditorGUILayout.Space();
}
if (animatedCharacter != null && characterControllerLayer != ragdollLayer)
{
GUILayout.Space(5);
if (GUILayout.Button("Set Up PuppetMaster", GUILayout.MaxWidth(140)))
{
#if UNITY_2018_3_OR_NEWER
if (animatedCharacter == script.transform)
{
if (PrefabUtility.IsPartOfPrefabInstance(animatedCharacter.gameObject)) PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetNearestPrefabInstanceRoot(animatedCharacter.gameObject), PrefabUnpackMode.Completely, InteractionMode.UserAction);
} else
{
if (PrefabUtility.IsPartOfPrefabInstance(script.gameObject)) PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetNearestPrefabInstanceRoot(script.gameObject), PrefabUnpackMode.Completely, InteractionMode.UserAction);
}
#endif
script.SetUpTo(animatedCharacter, characterControllerLayer, ragdollLayer);
animatedCharacter = null;
}
EditorGUILayout.LabelField("Setting up PuppetMaster is not undoable. Make sure to make a backup duplicate of the character before you do that.", miniLabelStyle);
if (animatedCharacter == script.transform)
{
GUILayout.Space(5);
EditorGUILayout.BeginVertical("Box");
GUILayout.Label("NB! 'Animated Target' is set to the same GameObject as this. PuppetMaster will make a duplicate of this GameObject and break the prefab to remove ragdoll components. It is recommended to set up the ragdoll on a new model instance, add PuppetMater to that and assign the original character as it's 'Animated Target'.", miniLabelStyle);
EditorGUILayout.EndVertical();
}
}
GUILayout.Space(5);
}
else
{
// Fix muscle positions and rotations to their targets
if (!Application.isPlaying && script.targetRoot != null)
{
if (script.transform.parent == script.targetRoot.parent)
{
script.transform.localPosition = Vector3.zero;
script.transform.localRotation = Quaternion.identity;
script.targetRoot.localPosition = Vector3.zero;
script.targetRoot.localRotation = Quaternion.identity;
}
foreach (Muscle m in script.muscles)
{
if (m.joint != null && m.target != null && !m.isPropMuscle)
{
m.joint.transform.position = m.target.position;
var r = m.joint.GetComponent<Rigidbody>();
bool hasChild = false;
foreach (Muscle otherMuscle in script.muscles)
{
if (otherMuscle != m && otherMuscle.joint != null && otherMuscle.joint.connectedBody != null)
{
if (otherMuscle.joint.connectedBody == r)
{
hasChild = true;
break;
}
}
}
if (hasChild)
{
m.joint.transform.rotation = m.target.rotation;
}
}
}
}
if (!Application.isPlaying && script.humanoidConfig != null && script.targetRoot != null && script.targetAnimator != null && script.targetAnimator.isHuman)
{
script.humanoidConfig.ApplyTo(script);
GUILayout.Space(5);
EditorGUILayout.BeginVertical("Box");
GUILayout.Label("Properties of this PuppetMaster are locked to the Humanoid Config file.", miniLabelStyle);
EditorGUILayout.EndVertical();
GUILayout.Space(5);
}
script.muscleSpring = Mathf.Clamp(script.muscleSpring, 0f, script.muscleSpring);
script.muscleDamper = Mathf.Clamp(script.muscleDamper, 0f, script.muscleDamper);
DrawDefaultInspector();
GUILayout.Space(10);
// Prop Muscles
GUIStyle largeHeaderStyle = new GUIStyle(GUI.skin.label);
largeHeaderStyle.fontSize = 16;
largeHeaderStyle.fontStyle = FontStyle.Normal;
//largeHeaderStyle.alignment = TextAnchor.LowerLeft;
largeHeaderStyle.alignment = TextAnchor.MiddleLeft;
GUI.color = Color.grey * 0.7f;
EditorGUILayout.LabelField("Prop Muscles", largeHeaderStyle);
GUI.color = Color.white;
EditorGUILayout.BeginHorizontal("Box");
addPropMuscleTo = (ConfigurableJoint)EditorGUILayout.ObjectField(GUIContent.none, addPropMuscleTo, typeof(ConfigurableJoint), true);
if (GUILayout.Button("Add Prop Muscle"))
{
serializedObject.ApplyModifiedProperties();
AddPropMuscle(script, addPropMuscleTo, addPropMuscleTo.transform.position, addPropMuscleTo.transform.rotation, Vector3.forward * 0.5f);
serializedObject.Update();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Prop Muscles are muscles that props (PuppetMasterProp) can be attached to. For example, to put a sword in the right hand, assign the right hand muscle above, click on 'Add Prop Muscle', then move the added muscle to where you would want the sword to be held. To pick up the sword, just assign it as 'Current Prop' in the PropMuscle component on the prop muscle.", miniLabelStyle);
GUILayout.Space(5);
}
bool animatorWarning = targetAnimator != null && targetAnimator.cullingMode != AnimatorCullingMode.AlwaysAnimate;
if (animatorWarning)
{
GUILayout.Space(5);
EditorGUILayout.BeginVertical("Box");
GUILayout.Label("If Animator 'Culling Mode' is not set to 'Always Animate', animation might pause and cause glitches when the ragdoll is out of SkinnedMeshRenderer.bounds.", miniLabelStyle);
EditorGUILayout.EndVertical();
}
bool rendererWarning = false;
foreach (SkinnedMeshRenderer s in skinnedMeshRenderers)
{
if (!s.updateWhenOffscreen)
{
rendererWarning = true;
break;
}
}
if (rendererWarning)
{
if (!animatorWarning) GUILayout.Space(5);
EditorGUILayout.BeginVertical("Box");
GUILayout.Label("One of the SkinnedMeshRenderers in the animated character hierarchy has 'Update When Offscreen' set to false. This might cause it to disappear from view when the ragdoll is out of the renderer's bounds.", miniLabelStyle);
EditorGUILayout.EndVertical();
}
serializedObject.ApplyModifiedProperties();
}
public static void DestroyImmediateSafe(GameObject go)
{
#if UNITY_2018_3_OR_NEWER
if (PrefabUtility.IsPartOfPrefabInstance(go)) PrefabUtility.UnpackPrefabInstance(PrefabUtility.GetNearestPrefabInstanceRoot(go), PrefabUnpackMode.Completely, InteractionMode.UserAction);
#endif
DestroyImmediate(go);
}
public static bool AddPropMuscle(PuppetMaster script, ConfigurableJoint addPropMuscleTo, Vector3 position, Quaternion rotation, Vector3 additionalPinOffset, Transform targetParent = null)
{
var serializedObject = new SerializedObject(script);
if (addPropMuscleTo != null)
{
bool isFlat = script.HierarchyIsFlat();
var addToMuscle = script.GetMuscle(addPropMuscleTo);
if (addToMuscle != null)
{
GameObject go = new GameObject("Prop Muscle " + addPropMuscleTo.name);
go.layer = addPropMuscleTo.gameObject.layer;
go.transform.parent = isFlat ? script.transform : addPropMuscleTo.transform;
go.transform.position = position;
go.transform.rotation = rotation;
var r = go.AddComponent<Rigidbody>();
GameObject target = new GameObject("Prop Muscle Target " + addPropMuscleTo.name);
target.gameObject.layer = addToMuscle.target.gameObject.layer;
target.transform.parent = targetParent == null ? addToMuscle.target : targetParent;
target.transform.position = go.transform.position;
target.transform.rotation = go.transform.rotation;
var joint = go.AddComponent<ConfigurableJoint>();
joint.connectedBody = addToMuscle.joint.gameObject.GetComponent<Rigidbody>();
joint.xMotion = ConfigurableJointMotion.Locked;
joint.yMotion = ConfigurableJointMotion.Locked;
joint.zMotion = ConfigurableJointMotion.Locked;
joint.angularXMotion = ConfigurableJointMotion.Locked;
joint.angularYMotion = ConfigurableJointMotion.Locked;
joint.angularZMotion = ConfigurableJointMotion.Locked;
r.interpolation = joint.connectedBody.interpolation;
int newLength = script.muscles.Length + 1;
int newMuscleIndex = newLength - 1;
SerializedProperty muscles = serializedObject.FindProperty("muscles");
muscles.InsertArrayElementAtIndex(newMuscleIndex);
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("index").intValue = newMuscleIndex;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("joint").objectReferenceValue = joint;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("target").objectReferenceValue = target.transform;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("props").FindPropertyRelative("group").intValue = 8;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("isPropMuscle").boolValue = true;
serializedObject.ApplyModifiedProperties();
var propMuscle = joint.gameObject.AddComponent<PropMuscle>();
var propMuscleS = new SerializedObject(propMuscle);
propMuscleS.FindProperty("puppetMaster").objectReferenceValue = script;
propMuscleS.FindProperty("additionalPinOffset").vector3Value = additionalPinOffset;
propMuscleS.ApplyModifiedProperties();
if (additionalPinOffset != Vector3.zero)
{
propMuscleS.Update();
ConfigurableJoint additionalJoint = null;
Transform additionalTarget = null;
PropMuscleInspector.AddAdditionalPinUnserialized(propMuscle, out additionalJoint, out additionalTarget);
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("additionalPin").objectReferenceValue = additionalJoint;
muscles.GetArrayElementAtIndex(newMuscleIndex).FindPropertyRelative("additionalPinTarget").objectReferenceValue = additionalTarget;
propMuscleS.ApplyModifiedProperties();
}
serializedObject.ApplyModifiedProperties();
// TODO Do not add if addPropMuscleTo already has a PropMuscle
return true;
}
else
{
Debug.LogError("Can't add Prop Muscle to a ConfigurableJoint that is not in the list of PuppetMaster.muscles.", script.transform);
return false;
}
}
else
{
Debug.LogError("Please assign the ConfigurableJoint of the muscle you wish to add the Prop Muscle to.", script.transform);
return false;
}
}
private bool IsRagdoll()
{
Rigidbody[] rigidbodies = (Rigidbody[])script.gameObject.GetComponentsInChildren<Rigidbody>();
foreach (Rigidbody r in rigidbodies)
{
if (r != script.GetComponent<Rigidbody>()) return true;
}
return false;
}
#endregion Inspector
#region Scene
void OnSceneGUI()
{
if (script == null) return;
if (Application.isPlaying) return;
foreach (Muscle m in script.muscles)
{
if (m.joint != null)
{
var propMuscle = m.joint.GetComponent<PropMuscle>();
if (propMuscle != null)
{
PropMuscleInspector.DrawScene(propMuscle);
}
}
}
Handles.color = Color.white;
}
#endregion Scene
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d63c5bd59fb5541eeb1098d1f4a6d01c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,37 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion.Dynamics
{
[CustomEditor(typeof(PuppetMasterProp))]
public class PuppetMasterPropInspector : Editor
{
private PuppetMasterProp script { get { return target as PuppetMasterProp; } }
private GUIStyle style = new GUIStyle();
private GUIStyle miniLabelStyle = new GUIStyle();
private static Color pro = new Color(0.5f, 0.7f, 0.3f, 1f);
private static Color free = new Color(0.2f, 0.3f, 0.1f, 1f);
public override void OnInspectorGUI()
{
if (script == null) return;
serializedObject.Update();
style.wordWrap = true;
style.normal.textColor = EditorGUIUtility.isProSkin ? pro : free;
miniLabelStyle.wordWrap = true;
miniLabelStyle.fontSize = 10;
miniLabelStyle.normal.textColor = EditorStyles.miniLabel.normal.textColor;
DrawDefaultInspector();
script.muscleProps.group = Muscle.Group.Prop;
serializedObject.ApplyModifiedProperties();
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: a7f9c20921f4b1942b1f7b410dd66836
timeCreated: 1550561801
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,46 @@
using UnityEngine;
using UnityEditor;
namespace RootMotion.Dynamics {
[CustomPropertyDrawer (typeof (Weight))]
public class WeightDrawer : PropertyDrawer {
const int valueWidth = 30;
const int gap = 20;
const float min = 0;
const float max = 1;
public override void OnGUI (Rect pos, SerializedProperty prop, GUIContent label) {
SerializedProperty mode = prop.FindPropertyRelative("mode");
SerializedProperty floatValue = prop.FindPropertyRelative ("floatValue");
SerializedProperty curve = prop.FindPropertyRelative ("curve");
SerializedProperty tooltip = prop.FindPropertyRelative("tooltip");
label.tooltip = tooltip.stringValue;
Rect left = new Rect(pos.x, pos.y, pos.width - valueWidth - gap, pos.height);
Rect right = new Rect (pos.width - valueWidth, pos.y, valueWidth, pos.height);
Weight.Mode m = (Weight.Mode)mode.enumValueIndex;
if (m == Weight.Mode.Float) {
floatValue.floatValue = EditorGUI.FloatField(left, label, floatValue.floatValue);
} else {
// Draw curve
int indent = EditorGUI.indentLevel;
EditorGUI.PropertyField (left, curve, label);
EditorGUI.indentLevel = indent;
}
int i = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
m = (Weight.Mode)EditorGUI.EnumPopup(right, GUIContent.none, ( Weight.Mode)mode.enumValueIndex, EditorStyles.miniBoldLabel);
mode.enumValueIndex = (int)m;
EditorGUI.indentLevel = i;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f882d03cc62ed40c7b8febce6ef4a0de
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 98d02ab32f6fa4551b1983c76cea4586
folderAsset: yes
timeCreated: 1452250914
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,75 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using RootMotion.Dynamics;
namespace RootMotion.Demos {
[CustomEditor(typeof(CharacterMeleeDemo))]
public class CharacterMeleeDemoInspector : Editor {
private CharacterMeleeDemo script { get { return target as CharacterMeleeDemo; }}
private GameObject replace;
private static Color pro = new Color(0.7f, 0.9f, 0.5f, 1f);
private static Color free = new Color(0.4f, 0.5f, 0.3f, 1f);
public override void OnInspectorGUI() {
GUI.changed = false;
if (!Application.isPlaying) {
GUI.color = EditorGUIUtility.isProSkin? pro: free;
EditorGUILayout.BeginHorizontal();
replace = (GameObject)EditorGUILayout.ObjectField("Replace Character Model", replace, typeof(GameObject), true);
if (replace != null) {
if (GUILayout.Button("Replace")) {
Debug.Log("PropMuscle needs to be set up manually and assigned as 'Prop Muscle' in the CharacterMeleeDemo component on the character.");
/* TODO Update to PropMuscle
PropRoot propRoot = script.propRoot;
Vector3 localPosition = propRoot.transform.localPosition;
Quaternion localRotation = propRoot.transform.localRotation;
propRoot.transform.parent = null;
CharacterPuppetInspector.ReplacePuppetModel(script as CharacterThirdPerson, replace);
Animator animator = script.characterAnimation.GetComponent<Animator>();
PuppetMaster puppetMaster = script.transform.parent.GetComponentInChildren<PuppetMaster>();
propRoot.transform.parent = animator.GetBoneTransform(HumanBodyBones.RightHand);
propRoot.transform.localPosition = localPosition;
propRoot.transform.localRotation = localRotation;
propRoot.puppetMaster = puppetMaster;
propRoot.connectTo = GetRigidbody(puppetMaster, animator.GetBoneTransform(HumanBodyBones.RightLowerArm));
Debug.Log("You probably need to adjust the localPosition and localRotation of the Prop Root to match this character's hand.");
*/
UserControlAI[] userControls = (UserControlAI[])GameObject.FindObjectsOfType<UserControlAI>();
foreach (UserControlAI ai in userControls) {
if (ai.moveTarget == null) {
ai.moveTarget = script.transform.parent.GetComponentInChildren<PuppetMaster>().muscles[0].joint.transform;
}
}
}
}
EditorGUILayout.EndHorizontal();
GUI.color = Color.white;
}
DrawDefaultInspector();
if (GUI.changed) EditorUtility.SetDirty(script);
}
private Rigidbody GetRigidbody(PuppetMaster puppetMaster, Transform target) {
foreach (Muscle m in puppetMaster.muscles) {
if (m.target == target) return m.joint.GetComponent<Rigidbody>();
}
return null;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5c5c74fcc11b441abb014b8119cb9e5f
timeCreated: 1452255675
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,176 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using RootMotion.Dynamics;
namespace RootMotion.Demos {
[CustomEditor(typeof(CharacterPuppet))]
public class CharacterPuppetInspector : Editor {
private CharacterPuppet script { get { return target as CharacterPuppet; }}
private GameObject replace;
private static Color pro = new Color(0.7f, 0.9f, 0.5f, 1f);
private static Color free = new Color(0.4f, 0.5f, 0.3f, 1f);
public override void OnInspectorGUI() {
GUI.changed = false;
if (!Application.isPlaying) {
GUI.color = EditorGUIUtility.isProSkin? pro: free;
EditorGUILayout.BeginHorizontal();
replace = (GameObject)EditorGUILayout.ObjectField("Replace Character Model", replace, typeof(GameObject), true);
if (replace != null) {
if (GUILayout.Button("Replace")) {
ReplacePuppetModel(script as CharacterThirdPerson, replace);
replace = null;
}
}
GUI.color = Color.white;
EditorGUILayout.EndHorizontal();
}
DrawDefaultInspector();
if (GUI.changed) EditorUtility.SetDirty(script);
}
public static void ReplacePuppetModel(CharacterThirdPerson script, GameObject replace) {
// Drag your Humanoid character to the scene, parent it to the "Animation Controller" just where the Pilot is
GameObject find = GameObject.Find(replace.name);
bool isSceneObject = find != null && find == replace;
GameObject instance = isSceneObject? replace: (GameObject)GameObject.Instantiate(replace, script.transform.position, script.transform.rotation);
instance.transform.parent = script.characterAnimation.transform;
instance.name = replace.name;
instance.transform.position = script.transform.position;
instance.transform.rotation = script.transform.rotation;
Animator animator = instance.GetComponentInChildren<Animator>();
bool isAnimator = animator != null;
if (!isAnimator || !animator.isHuman) {
Debug.LogWarning("The demo character controller requires a Humanoid character.");
return;
}
SkinnedMeshRenderer[] skinnedMeshRenders = instance.GetComponentsInChildren<SkinnedMeshRenderer>();
foreach (SkinnedMeshRenderer s in skinnedMeshRenders) s.updateWhenOffscreen = true;
// Unparent "Character Controller" from the "ThirdPersonPuppet"
Transform oldRoot = script.transform.parent;
PuppetMaster oldPM = script.transform.parent.GetComponentInChildren<PuppetMaster>();
RigidbodyInterpolation oldInterpolation = oldPM.muscles[0].joint.GetComponent<Rigidbody>().interpolation;
BehaviourBase[] behaviours = script.transform.parent.GetComponentsInChildren<BehaviourBase>();
Camera camera = script.transform.parent.GetComponentInChildren<Camera>();
CameraController cameraController = null;
if (camera != null) cameraController = camera.gameObject.GetComponent<CameraController>();
LayerSetup layerSetup = oldPM.GetComponent<LayerSetup>();
script.transform.parent = null;
// Delete the "Pilot"
DestroyImmediate(script.characterAnimation.transform.GetChild(0).gameObject);
// Replace the Avatar in the Animator component of the "Animation Controller" gameobject.
Animator characterAnimator = script.characterAnimation.GetComponent<Animator>();
characterAnimator.avatar = animator.avatar;
// Add BipedRagdollCreator to the "Animation Controller", use it to create a ragdoll, delete the component when done
Joint joint = instance.GetComponentInChildren<Joint>();
bool isRagdoll = joint != null;
bool isConfigurable = isRagdoll && joint is ConfigurableJoint;
if (isRagdoll && !isConfigurable) {
JointConverter.ToConfigurable(instance);
}
if (!isRagdoll) {
BipedRagdollReferences r = BipedRagdollReferences.FromAvatar(animator);
BipedRagdollCreator.Options options = BipedRagdollCreator.AutodetectOptions(r);
// Edit options here if you need to
BipedRagdollCreator.Create(r, options);
}
// Delete the Animator from your character root (not the one on "Animation Controller")
DestroyImmediate(animator);
// Add PuppetMaster to the "Character Controller", click on Set Up PuppetMaster.
int cLayer = layerSetup != null? layerSetup.characterControllerLayer: script.gameObject.layer;
int rLayer = layerSetup != null? layerSetup.ragdollLayer: oldPM.muscles[0].joint.gameObject.layer;
PuppetMaster newPuppetMaster = PuppetMaster.SetUp(script.transform, cLayer, rLayer);
foreach (Muscle m in newPuppetMaster.muscles) {
m.joint.GetComponent<Rigidbody>().interpolation = oldInterpolation;
}
// Move the "Puppet" and "Fall" behaviours from the old rig to the new one (parent them to the "Behaviours").
Transform behaviourRoot = newPuppetMaster.transform.parent.Find("Behaviours");
Transform oldBehaviourRoot = behaviours.Length > 0? behaviours[0].transform.parent: FindChildNameContaining(oldRoot, "Behaviours");
foreach (BehaviourBase behaviour in behaviours) behaviour.transform.parent = behaviourRoot;
if (oldBehaviourRoot != null) DestroyImmediate(oldBehaviourRoot.gameObject);
// 9. Move the "Character Camera" to the new rig, replace the "Target" of the CharacterController component
if (camera != null) camera.transform.parent = newPuppetMaster.transform.parent;
if (cameraController != null) cameraController.target = newPuppetMaster.muscles[0].joint.transform;
// THIS IS NOT REQUIRED SINCE 0.3 Use the RagdollEditor (add it to the PuppetMaster) to multiply the mass of the ragdoll by 10
// 10. Copy the LayerSetup component from the old PuppetMaster to the new one if you have not set up the layers in the Layer Collision Matrix.
if (layerSetup != null) {
LayerSetup newLayerSetup = newPuppetMaster.gameObject.AddComponent<LayerSetup>();
if (newLayerSetup != null) {
newLayerSetup.characterController = layerSetup.characterController;
newLayerSetup.characterControllerLayer = layerSetup.characterControllerLayer;
newLayerSetup.ragdollLayer = layerSetup.ragdollLayer;
newLayerSetup.ignoreCollisionWithCharacterController = layerSetup.ignoreCollisionWithCharacterController;
}
}
// 11. Make sure the new PuppetMaster settings match with the old one, delete the old rig
newPuppetMaster.state = oldPM.state;
newPuppetMaster.stateSettings = oldPM.stateSettings;
newPuppetMaster.mode = oldPM.mode;
newPuppetMaster.blendTime = oldPM.blendTime;
newPuppetMaster.fixTargetTransforms = oldPM.fixTargetTransforms;
newPuppetMaster.solverIterationCount = oldPM.solverIterationCount;
newPuppetMaster.visualizeTargetPose = oldPM.visualizeTargetPose;
newPuppetMaster.mappingWeight = oldPM.mappingWeight;
newPuppetMaster.pinWeight = oldPM.pinWeight;
newPuppetMaster.muscleWeight = oldPM.muscleWeight;
newPuppetMaster.muscleSpring = oldPM.muscleSpring;
newPuppetMaster.muscleDamper = oldPM.muscleDamper;
newPuppetMaster.pinPow = oldPM.pinPow;
newPuppetMaster.pinDistanceFalloff = oldPM.pinDistanceFalloff;
newPuppetMaster.updateJointAnchors = oldPM.updateJointAnchors;
newPuppetMaster.supportTranslationAnimation = oldPM.supportTranslationAnimation;
newPuppetMaster.angularLimits = oldPM.angularLimits;
newPuppetMaster.internalCollisions = oldPM.internalCollisions;
// 12 Parent this CharacterPuppet to the new puppet root
script.transform.parent = newPuppetMaster.transform.parent;
// 13. Delete the old root
script.transform.parent.name = oldRoot.name;
for (int i = 0; i < oldRoot.childCount; i++) {
var child = oldRoot.GetChild(i);
if (child != oldPM.transform && child != behaviourRoot) {
child.parent = script.transform.parent;
}
}
DestroyImmediate(oldRoot.gameObject);
}
private static Transform FindChildNameContaining(Transform t, string name) {
for (int i = 0; i < t.childCount; i++) {
if (t.GetChild(i).name.Contains(name)) return t.GetChild(i);
}
return null;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: d86142a0934834027a39b8a2e105c009
timeCreated: 1452250930
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: e216fee95a1f04dd38a1e457aed7617a
folderAsset: yes
timeCreated: 1436186405
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,168 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using RootMotion;
namespace RootMotion.Dynamics {
[CustomEditor(typeof(BipedRagdollCreator))]
public class BipedRagdollCreatorInspector : Editor {
public BipedRagdollCreator script { get { return target as BipedRagdollCreator; }}
private GUIStyle miniLabelStyle = new GUIStyle();
void OnEnable() {
if (script == null) return;
//if (Application.isPlaying) return;
// Autodetection
if (script.references.IsEmpty(false)) {
Animator animator = script.gameObject.GetComponent<Animator>();
if (animator == null && script.references.root != null) {
animator = script.references.root.GetComponentInChildren<Animator>();
if (animator == null) animator = GetAnimatorInParents(script.references.root);
}
if (animator != null) {
script.references = BipedRagdollReferences.FromAvatar(animator);
} else {
BipedReferences r = new BipedReferences();
BipedReferences.AutoDetectReferences(ref r, script.transform, BipedReferences.AutoDetectParams.Default);
if (r.isFilled) script.references = BipedRagdollReferences.FromBipedReferences(r);
}
if (!OnRoot()) {
Debug.LogWarning("BipedRagdollCreator must be added to the root of the character. Destroying the component.");
DestroyImmediate(script);
return;
}
string msg = string.Empty;
if (script.references.IsValid(ref msg)) {
script.options = BipedRagdollCreator.AutodetectOptions(script.references);
//BipedRagdollCreator.Create(script.references, script.options);
//if (animator != null) DestroyImmediate(animator);
//if (script.GetComponent<Animation>() != null) DestroyImmediate(script.GetComponent<Animation>());
}
}
}
private bool OnRoot() {
if (script.references.Contains(script.transform, true)) return false;
if (script.references.root != null) {
var bipedRagdollCreatorOnChild = script.references.root.GetComponentInChildren<BipedRagdollCreator>();
if (bipedRagdollCreatorOnChild != null && bipedRagdollCreatorOnChild.transform != script.references.root) return false;
}
return true;
}
public override void OnInspectorGUI() {
miniLabelStyle.wordWrap = true;
miniLabelStyle.fontSize = 9;
miniLabelStyle.normal.textColor = EditorStyles.miniLabel.normal.textColor;
serializedObject.Update();
//if (Application.isPlaying) {
// GUILayout.BeginVertical("Box");
// GUILayout.Label("Can not edit ragdolls in play mode.");
// GUILayout.EndVertical();
// return;
//}
GUI.changed = false;
GUILayout.Space(10);
EditorGUILayout.BeginVertical("Box");
int indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(serializedObject.FindProperty("references"), new GUIContent("References", "Definition of the biped ragdoll."), true);
if (GUI.changed) {
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(script);
}
string msg = string.Empty;
bool referencesValid = script.references.IsValid(ref msg);
if (serializedObject.FindProperty("references").isExpanded) GUILayout.Space(5);
EditorGUILayout.EndVertical();
if (referencesValid) {
if (!script.canBuild) {
UnityEditor.EditorApplication.isPaused = true;
GUILayout.Space(5);
if (GUILayout.Button("Create a Ragdoll")) {
script.canBuild = true;
}
GUILayout.Label("Clears all existing physics components, creates a new ragdoll and starts live-updating. NB! THIS CAN NOT BE UNDONE!", miniLabelStyle);
GUILayout.Space(5);
}
if (script.canBuild) {
GUI.changed = false;
//GUILayout.Space(5);
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.PropertyField(serializedObject.FindProperty("options"), new GUIContent("Options", "Options for automatic ragdoll generation."), true);
if (GUI.changed) {
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(script);
}
if (serializedObject.FindProperty("options").isExpanded) GUILayout.Space(5);
EditorGUILayout.EndVertical();
BipedRagdollCreator.Create(script.references, script.options);
GUILayout.Space(10);
if (GUILayout.Button("Done")) {
UnityEditor.EditorApplication.isPaused = false;
EditorGUI.indentLevel = indent;
DestroyImmediate(script);
return;
}
GUILayout.Label("Removes this component.", miniLabelStyle);
if (GUILayout.Button("Start Editing Manually")) {
script.gameObject.AddComponent<RagdollEditor>();
EditorGUI.indentLevel = indent;
DestroyImmediate(script);
return;
}
GUILayout.Label("Replaces this component with the RagdollEditor.", miniLabelStyle);
GUILayout.Space(10);
}
} else {
GUILayout.Space(10);
GUILayout.BeginVertical("Box");
GUILayout.Label(msg);
GUILayout.EndVertical();
GUILayout.Space(10);
if (script.canBuild) RagdollCreator.ClearAll(script.transform);
}
EditorGUI.indentLevel = indent;
}
private static Animator GetAnimatorInParents(Transform transform) {
if (transform.GetComponent<Animator>() != null) return transform.GetComponent<Animator>();
if (transform.parent == null) return null;
return GetAnimatorInParents(transform.parent);
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3b4d10c84c3764847812025f2e5986e6
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,48 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System;
namespace RootMotion.Dynamics {
[CustomEditor(typeof(CharacterJoint))]
public class CharacterJointInspector : JointInspector {
private static Color
highTwistColor = new Color(1, 0.75f, 0, 0.3f),
lowTwistColor = new Color(0.8f, 0.65f, 0, 0.3f),
swing1Color = new Color(0, 1, 0, 0.3f),
swing2Color = new Color(0, 0, 1, 0.3f);
public static void DrawJoint(CharacterJoint joint, bool modifiable = true, float alphaMlp = 1f) {
if (joint == null) return;
Vector3 axis = Vector3.zero;
if (joint.axis != Vector3.zero) axis = joint.axis.normalized;
Vector3 swingAxis = Vector3.zero;
if (joint.swingAxis != Vector3.zero) swingAxis = joint.swingAxis.normalized;
Vector3 crossAxis = swingAxis;
if (swingAxis != axis) crossAxis = Vector3.Cross(swingAxis, axis);
float newLowTwistLimit = DrawJointLimit(joint as Joint, "Low Twist Limit", axis, joint.lowTwistLimit.limit, MlpAlpha(lowTwistColor, alphaMlp), -25, modifiable);
joint.lowTwistLimit = NewJointLimit(newLowTwistLimit, joint.lowTwistLimit, -180, 180);
float newHighTwistLimit = joint.highTwistLimit.limit;
if (newLowTwistLimit != 0 || (newLowTwistLimit == 0 && newHighTwistLimit != 0)) newHighTwistLimit = DrawJointLimit(joint as Joint, "High Twist Limit", axis, joint.highTwistLimit.limit, MlpAlpha(highTwistColor, alphaMlp), 25, modifiable);
joint.highTwistLimit = NewJointLimit(newHighTwistLimit, joint.highTwistLimit, -180, 180);
float newSwing1Limit = DrawJointLimit(joint as Joint, "Swing1 Limit", swingAxis, -joint.swing1Limit.limit, MlpAlpha(swing1Color, alphaMlp), 25, false);
newSwing1Limit = DrawJointLimit(joint as Joint, "Swing1 Limit", swingAxis, -newSwing1Limit, MlpAlpha(swing1Color, alphaMlp), 25, modifiable);
joint.swing1Limit = NewJointLimit(newSwing1Limit, joint.swing1Limit, 0, 180);
float newSwing2Limit = DrawJointLimit(joint as Joint, "Swing2 Limit", crossAxis, -joint.swing2Limit.limit, MlpAlpha(swing2Color, alphaMlp), 25, false);
newSwing2Limit = DrawJointLimit(joint as Joint, "Swing2 Limit", crossAxis, -newSwing2Limit, MlpAlpha(swing2Color, alphaMlp), 25, modifiable);
joint.swing2Limit = NewJointLimit(newSwing2Limit, joint.swing2Limit, 0, 180);
}
public void OnSceneGUI() {
DrawJoint(target as CharacterJoint);
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: df75c9b4717ec4cf996ae3055c26373e
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,250 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion.Dynamics {
// Tools for editing Colliders.
public class ColliderTools: Editor {
public static void ConvertToSphereCollider(CapsuleCollider capsule) {
SphereCollider sphere = Undo.AddComponent(capsule.gameObject, typeof(SphereCollider)) as SphereCollider;
sphere.center = capsule.center;
sphere.radius = capsule.radius;
Undo.DestroyObjectImmediate(capsule);
}
public static void ConvertToSphereCollider(BoxCollider box) {
SphereCollider sphere = Undo.AddComponent(box.gameObject, typeof(SphereCollider)) as SphereCollider;
sphere.center = box.center;
sphere.radius = Mathf.Max(new float[3] { box.size.x, box.size.y, box.size.z }) * 0.5f;
Undo.DestroyObjectImmediate(box);
}
public static void ConvertToBoxCollider(SphereCollider sphere) {
BoxCollider box = Undo.AddComponent(sphere.gameObject, typeof(BoxCollider)) as BoxCollider;
box.center = sphere.center;
box.size = Vector3.one * sphere.radius * 2f;
Undo.DestroyObjectImmediate(sphere);
}
public static void ConvertToCapsuleCollider(SphereCollider sphere) {
CapsuleCollider capsule = Undo.AddComponent(sphere.gameObject, typeof(CapsuleCollider)) as CapsuleCollider;
capsule.center = sphere.center;
capsule.radius = sphere.radius;
capsule.height = sphere.radius;
Undo.DestroyObjectImmediate(sphere);
}
public static void ConvertToBoxCollider(CapsuleCollider capsule) {
BoxCollider box = Undo.AddComponent(capsule.gameObject, typeof(BoxCollider)) as BoxCollider;
box.center = capsule.center;
float diameter = capsule.radius * 2f;
float height = Mathf.Max(diameter, capsule.height);
if (capsule.direction == 0) box.size = new Vector3(height, diameter, diameter);
else if (capsule.direction == 1) box.size = new Vector3(diameter, height, diameter);
else if (capsule.direction == 2) box.size = new Vector3(diameter, diameter, height);
Undo.DestroyObjectImmediate(capsule);
}
public static void ConvertToCapsuleCollider(BoxCollider box) {
float absX = Mathf.Abs(box.size.x);
float absY = Mathf.Abs(box.size.y);
float absZ = Mathf.Abs(box.size.z);
CapsuleCollider capsule = Undo.AddComponent(box.gameObject, typeof(CapsuleCollider)) as CapsuleCollider;
capsule.center = box.center;
capsule.direction = 0;
if (absY > absX && absY > absZ) capsule.direction = 1;
if (absZ > absX && absZ > absY) capsule.direction = 2;
if (capsule.direction == 0) {
capsule.height = absX;
capsule.radius = Mathf.Max(absY, absZ) * 0.5f;
} else if (capsule.direction == 1) {
capsule.height = absY;
capsule.radius = Mathf.Max(absX, absZ) * 0.5f;
} else if (capsule.direction == 2) {
capsule.height = absZ;
capsule.radius = Mathf.Max(absX, absY) * 0.5f;
}
Undo.DestroyObjectImmediate(box);
}
public static void SetColliderCenterWorld(Collider r, Collider s, Vector3 value, Transform root) {
Vector3 newCenter = r.transform.InverseTransformPoint(value);
Vector3 centerWorld = Vector3.zero;
Vector3 deltaWorld = Vector3.zero;
if (r is BoxCollider) {
var box = r as BoxCollider;
centerWorld = r.transform.TransformPoint(box.center);
deltaWorld = value - centerWorld;
box.center = newCenter;
if (s != null && s is BoxCollider) s.transform.GetComponent<BoxCollider>().center += s.transform.InverseTransformVector(SymmetryTools.Mirror(deltaWorld, root));
return;
}
if (r is CapsuleCollider) {
var capsule = r as CapsuleCollider;
centerWorld = r.transform.TransformPoint(capsule.center);
deltaWorld = value - centerWorld;
capsule.center = newCenter;
if (s != null && s is CapsuleCollider) s.transform.GetComponent<CapsuleCollider>().center += s.transform.InverseTransformVector(SymmetryTools.Mirror(deltaWorld, root));
return;
}
if (r is SphereCollider) {
var sphere = r as SphereCollider;
centerWorld = r.transform.TransformPoint(sphere.center);
deltaWorld = value - centerWorld;
sphere.center = newCenter;
if (s != null && s is SphereCollider) s.transform.GetComponent<SphereCollider>().center += s.transform.InverseTransformVector(SymmetryTools.Mirror(deltaWorld, root));
return;
}
}
public static Vector3 GetColliderCenterWorld(Collider r) {
if (r == null) return Vector3.zero;
if (r is BoxCollider) {
return r.transform.TransformPoint((r as BoxCollider).center);
}
if (r is CapsuleCollider) {
return r.transform.TransformPoint((r as CapsuleCollider).center);
}
if (r is SphereCollider) {
return r.transform.TransformPoint((r as SphereCollider).center);
}
return r.transform.position;
}
public static void SetColliderSize(Collider r, Collider s, Vector3 value, Vector3 lastValue, Vector3 lastValueS, Transform root) {
Vector3 delta = Vector3.zero;
Vector3 deltaM = Vector3.zero;
if (r is BoxCollider) {
var box = r as BoxCollider;
delta = value - box.size;
box.size = value;
if (s != null && s is BoxCollider) {
var boxS = s as BoxCollider;
deltaM = SymmetryTools.MirrorDelta(r.transform, s.transform, root, delta);
boxS.size += deltaM;
}
}
if (r is CapsuleCollider) {
var capsule = r as CapsuleCollider;
delta = value - GetCapsuleSize(capsule);
SetCapsuleSize(capsule, value, lastValue);
if (s != null && s is CapsuleCollider) {
var capsuleS = s as CapsuleCollider;
if (capsuleS != null) {
deltaM = SymmetryTools.MirrorDelta(r.transform, s.transform, root, delta);
Vector3 capsuleSSize = GetCapsuleSize(capsuleS);
capsuleSSize += deltaM;
SetCapsuleSize(capsuleS, capsuleSSize, lastValueS);
}
}
}
if (r is SphereCollider) {
var sphere = r as SphereCollider;
delta = value - GetColliderSize(r);
SetSphereSize(sphere, value, lastValue);
if (s != null && s is SphereCollider) {
var sphereS = s as SphereCollider;
Vector3 sphereSSize = GetColliderSize(s);
sphereSSize += delta;
if (sphereS != null) {
SetSphereSize(sphereS, sphereSSize, lastValueS);
}
}
}
}
public static Vector3 GetColliderSize(Collider r) {
if (r == null) return Vector3.zero;
if (r is BoxCollider) return (r as BoxCollider).size;
if (r is CapsuleCollider) return GetCapsuleSize(r as CapsuleCollider);
if (r is SphereCollider) return Vector3.one * (r as SphereCollider).radius;
return r.transform.localScale;
}
public static void SetCapsuleSize(CapsuleCollider capsule, Vector3 size, Vector3 lastSize) {
if (capsule.direction == 0) {
capsule.height = size.x;
float absY = Mathf.Abs(size.y - lastSize.y);
float absZ = Mathf.Abs(size.z - lastSize.z);
capsule.radius = absY > absZ? size.y: size.z;
}
if (capsule.direction == 1) {
capsule.height = size.y;
float absX = Mathf.Abs(size.x - lastSize.x);
float absZ = Mathf.Abs(size.z - lastSize.z);
capsule.radius = absX > absZ? size.x: size.z;
}
if (capsule.direction == 2) {
capsule.height = size.z;
float absX = Mathf.Abs(size.x - lastSize.x);
float absY = Mathf.Abs(size.y - lastSize.y);
capsule.radius = absX > absY? size.x: size.y;
}
}
public static void SetSphereSize(SphereCollider sphere, Vector3 size, Vector3 lastSize) {
if (size.x != lastSize.z) {
sphere.radius += size.x - lastSize.x;
} else if (size.y != lastSize.y) {
sphere.radius += size.y - lastSize.y;
} else if (size.z != lastSize.z) {
sphere.radius += size.z - lastSize.z;
}
}
public static Vector3 GetCapsuleSize(CapsuleCollider capsule) {
if (capsule.direction == 0) return new Vector3(capsule.height, capsule.radius, capsule.radius);
if (capsule.direction == 1) return new Vector3(capsule.radius, capsule.height, capsule.radius);
return new Vector3(capsule.radius, capsule.radius, capsule.height);
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 9ed7bfe787e81435c8b76e75353a45fb
timeCreated: 1444653054
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,56 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System;
namespace RootMotion.Dynamics {
[CustomEditor(typeof(ConfigurableJoint))]
public class ConfigurableJointInspector : JointInspector {
private static Color
highAngularXColor = new Color(1, 0.75f, 0, 0.3f),
lowAngularXColor = new Color(0.8f, 0.65f, 0, 0.3f),
angularYColor = new Color(0, 1, 0, 0.3f),
angularZColor = new Color(0, 0, 1, 0.3f);
private const string lowX = "Low X", highX = "High X", y = "Y", z = "Z";
public static void DrawJoint(ConfigurableJoint joint, bool modifiable = true, float alphaMlp = 1f) {
if (joint == null) return;
Vector3 axis = Vector3.zero;
if (joint.axis != Vector3.zero) axis = joint.axis.normalized;
Vector3 secondaryAxis = Vector3.zero;
if (joint.secondaryAxis != Vector3.zero) secondaryAxis = joint.secondaryAxis.normalized;
Vector3 crossAxis = secondaryAxis;
if (secondaryAxis != axis) crossAxis = Vector3.Cross(secondaryAxis, axis);
if (joint.angularXMotion == ConfigurableJointMotion.Limited) {
float newLowAngularXLimit = DrawJointLimit(joint as Joint, lowX, axis, joint.lowAngularXLimit.limit, MlpAlpha(lowAngularXColor, alphaMlp), -25, modifiable);
joint.lowAngularXLimit = NewJointLimit(newLowAngularXLimit, joint.lowAngularXLimit, -180, 180);
float newHighAngularXLimit = joint.highAngularXLimit.limit;
if (newLowAngularXLimit != 0 || (newLowAngularXLimit == 0 && newHighAngularXLimit != 0)) newHighAngularXLimit = DrawJointLimit(joint as Joint, highX, axis, joint.highAngularXLimit.limit, MlpAlpha(highAngularXColor, alphaMlp), 25, modifiable);
joint.highAngularXLimit = NewJointLimit(newHighAngularXLimit, joint.highAngularXLimit, -180, 180);
}
if (joint.angularYMotion == ConfigurableJointMotion.Limited) {
float newAngularYLimit = DrawJointLimit(joint as Joint, y, secondaryAxis, -joint.angularYLimit.limit, MlpAlpha(angularYColor, alphaMlp), 25, false);
newAngularYLimit = DrawJointLimit(joint as Joint, y, secondaryAxis, -newAngularYLimit, MlpAlpha(angularYColor, alphaMlp), 25, modifiable);
joint.angularYLimit = NewJointLimit(newAngularYLimit, joint.angularYLimit, 0, 180);
}
if (joint.angularZMotion == ConfigurableJointMotion.Limited) {
float newAngularZLimit = DrawJointLimit(joint as Joint, z, crossAxis, -joint.angularZLimit.limit, MlpAlpha(angularZColor, alphaMlp), 25, false);
newAngularZLimit = DrawJointLimit(joint as Joint, z, crossAxis, -newAngularZLimit, MlpAlpha(angularZColor, alphaMlp), 25, modifiable);
joint.angularZLimit = NewJointLimit(newAngularZLimit, joint.angularZLimit, 0, 180);
}
}
public void OnSceneGUI() {
DrawJoint(target as ConfigurableJoint);
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 79e48320bea5b4a49a128eabdb1b39b2
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,27 @@
using UnityEngine;
using UnityEditor;
namespace RootMotion.Dynamics {
/// <summary>
/// Converting 3D joints to ConfigurableJoints
/// </summary>
public class ConvertToConfigurableJoints: Editor {
/// <summary>
/// Converts any 3D joints on the selected Transform and it's children to ConfigurableJoints
/// </summary>
//[MenuItem ("Component/Physics/Convert to ConfigurableJoints")]
[MenuItem ("GameObject/Convert to ConfigurableJoints")]
public static void ConvertSelected() {
if (Selection.activeGameObject == null) {
Debug.Log("Please select the root of the ragdoll that you wish to convert to use ConfigurableJoints.");
return;
}
// @todo undo
JointConverter.ToConfigurable(Selection.activeGameObject);
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5c49a237763c444bda35d3387fed6c35
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace RootMotion.Dynamics
{
public class DragRig : MonoBehaviour
{
private Rigidbody rig;
private void Start()
{
rig = transform.GetComponent<Rigidbody>();
}
private void OnMouseDrag()
{
Vector3 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rig.AddForce(0.01f * Time.deltaTime * (cursorPos-transform.position).normalized,ForceMode.Force);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b32271905ed4afe44b53328a916f382a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,139 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
namespace RootMotion.Dynamics {
public class JointInspector : Editor {
#region Public methods
private static bool isDragging;
public static float DrawJointLimit(Joint joint, string label, Vector3 axis, float limit, Color color, float openValue, bool drawHandles) {
if (Event.current.type == EventType.MouseDown) isDragging = false;
if (Event.current.type == EventType.MouseUp) isDragging = false;
float radius = HandleUtility.GetHandleSize(joint.transform.position);
Vector3 center = joint.transform.TransformPoint(joint.anchor);
Quaternion axisOffset = Quaternion.AngleAxis(GetViewOffset(joint, axis), axis);
Vector3 limitAxis = joint.transform.TransformDirection(axisOffset * axis).normalized;
Vector3 limitAxisOrtho = joint.transform.TransformDirection(axisOffset * new Vector3(axis.z, axis.x, axis.y)).normalized;
Vector3 limitAxisCross = Vector3.Cross(limitAxis, limitAxisOrtho);
Handles.color = color;
Handles.DrawSolidArc(center, limitAxis, limitAxisCross, -limit, radius);
Handles.color = new Color(color.r, color.g, color.b, 1f);
GUI.color = new Color(color.r, color.g, color.b, 1f);
//if (limitAxis != Vector3.zero) Handles.CircleCap(0, center, Quaternion.LookRotation(limitAxis), radius);
Quaternion angleAxis = Quaternion.AngleAxis(-limit, limitAxis);
Vector3 handleVector = angleAxis * limitAxisCross;
Quaternion handleRotation = Quaternion.AngleAxis(-limit, limitAxis);
if (limitAxisCross != Vector3.zero && limitAxisOrtho != Vector3.zero) {
handleRotation = Quaternion.AngleAxis(-limit, limitAxis) * Quaternion.LookRotation(limitAxisCross) * Quaternion.LookRotation(limitAxisOrtho);
}
if (!drawHandles) return limit;
float newLimit = Inspector.ScaleValueHandleSphere(limit, center + handleVector * radius, Quaternion.identity, radius, 1);
//float newLimit = Handles.han(handleRotation, center + handleVector * radius, limit);
string labelInfo = label;
if (newLimit == 0) {
labelInfo = "Open " + label;
if (Inspector.SphereButton(center + handleVector * radius, handleRotation, radius * 0.2f, radius * 0.07f)) {
newLimit = openValue;
}
}
Handles.Label(center + handleVector * radius * 1.2f, labelInfo);
if (newLimit != limit) {
if (!isDragging) {
Undo.RecordObject(joint, "Change Joint Limits");
isDragging = true;
}
}
GUI.color = Color.white;
return newLimit;
}
public static SoftJointLimit NewJointLimit(float limit, SoftJointLimit referenceJointLimit, float min, float max) {
SoftJointLimit newJointLimit = new SoftJointLimit();
newJointLimit.limit = Mathf.Clamp(limit, min, max);
newJointLimit.bounciness = referenceJointLimit.bounciness;
return newJointLimit;
}
public static Color MlpAlpha(Color color, float alphaMlp) {
return new Color(color.r, color.g, color.b, color.a * alphaMlp);
}
#endregion
private static float GetViewOffset(Joint joint, Vector3 axis) {
if (joint.connectedBody == null) return 0;
Vector3 directionAxis = joint.transform.right;
Axis viewAxis = GetViewAxis(joint);
switch(viewAxis) {
case Axis.Y: directionAxis = joint.transform.up; break;
case Axis.Z: directionAxis = joint.transform.forward; break;
}
if (FlipAxis(joint, viewAxis)) directionAxis = -directionAxis;
Vector3 axisWorld = joint.transform.TransformDirection(axis).normalized;
Vector3 axisWorldOrtho = joint.transform.TransformDirection(new Vector3(axis.z, axis.x, axis.y)).normalized;
float dot = Vector3.Dot(axisWorldOrtho, directionAxis);
float dot2 = Vector3.Dot(axisWorldOrtho, Vector3.Cross(directionAxis, axisWorld));
if (dot >= 0.5f) return -90;
if (dot2 >= 0.5f) return 0;
if (dot < -0.5f) return 90;
if (dot2 < -0.5f) return 180;
return 0;
}
private static Axis GetViewAxis(Joint joint) {
if (joint.connectedBody == null) return Axis.Z;
CapsuleCollider capsule = joint.GetComponent<CapsuleCollider>();
if (capsule != null && capsule.center != Vector3.zero) return AxisTools.ToAxis(capsule.center);
else {
BoxCollider box = joint.GetComponent<BoxCollider>();
if (box != null && box.center != Vector3.zero) return AxisTools.ToAxis(box.center);
}
return AxisTools.GetAxisToPoint(joint.transform, joint.connectedBody.worldCenterOfMass);
}
private static bool FlipAxis(Joint joint, Axis axis) {
Vector3 direction = Vector3.Normalize(joint.transform.position - joint.connectedBody.worldCenterOfMass);
CapsuleCollider capsuleCollider = joint.GetComponent<CapsuleCollider>();
if (capsuleCollider != null) {
direction = Vector3.Normalize(joint.transform.position - (joint.transform.position - (joint.transform.rotation * capsuleCollider.center)));
}
switch(axis) {
case Axis.X:
return Vector3.Dot(joint.transform.right, direction) < 0;
case Axis.Y:
return Vector3.Dot(joint.transform.up, direction) < 0;
default: return Vector3.Dot(joint.transform.forward, direction) < 0;
}
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2c166e20a769d4ec3a0f504c4fa3ffe7
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,276 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion.Dynamics {
public enum JointAxis {
Primary,
Secondary,
Tertiary
}
// Tools for editing Joints.
public class JointTools: Editor {
public static Quaternion LocalToJointSpace(ConfigurableJoint joint) {
Vector3 forward = Vector3.Cross (joint.axis, joint.secondaryAxis).normalized;
Vector3 up = Vector3.Cross(forward, joint.axis).normalized;
if (forward == up) {
Debug.LogWarning("Joint " + joint.name + " secondaryAxis is in the exact same direction as it's axis. Please make sure they are not aligned.");
}
return Quaternion.LookRotation(forward, up);
}
public static Quaternion LocalToJointSpace(CharacterJoint joint) {
Vector3 forward = Vector3.Cross (joint.axis, joint.swingAxis).normalized;
Vector3 up = Vector3.Cross(forward, joint.axis).normalized;
if (forward == up) {
Debug.LogWarning("Joint " + joint.name + " swingAxis is in the exact same direction as it's axis. Please make sure they are not aligned.");
}
return Quaternion.LookRotation(forward, up);
}
public static Quaternion JointToLocalSpace(ConfigurableJoint joint) {
return Quaternion.Inverse(LocalToJointSpace(joint));
}
public static Quaternion JointToLocalSpace(CharacterJoint joint) {
return Quaternion.Inverse(LocalToJointSpace(joint));
}
public static JointAxis GetJointAxis(ConfigurableJoint joint, Vector3 vLocal) {
return GetJointAxis(joint.axis, joint.secondaryAxis, vLocal);
}
public static JointAxis GetJointAxis(CharacterJoint joint, Vector3 vLocal) {
return GetJointAxis(joint.axis, joint.swingAxis, vLocal);
}
public static JointAxis GetJointAxis(Vector3 axis, Vector3 secondaryAxis, Vector3 vLocal) {
vLocal = vLocal.normalized;
float axisDot = Mathf.Abs(Vector3.Dot(axis, vLocal));
float secondaryAxisDot = Mathf.Abs(Vector3.Dot(secondaryAxis, vLocal));
float tertiaryAxisDot = Mathf.Abs(Vector3.Dot(Vector3.Cross(axis, secondaryAxis), vLocal));
if (axisDot > secondaryAxisDot && axisDot > tertiaryAxisDot) return JointAxis.Primary;
if (secondaryAxisDot > axisDot && secondaryAxisDot > tertiaryAxisDot) return JointAxis.Secondary;
return JointAxis.Tertiary;
}
public static JointAxis GetSymmetricJointAxis(ConfigurableJoint joint, JointAxis jointAxis, ConfigurableJoint symmetricJoint, Transform root) {
return GetSymmetricJointAxis(joint.transform, joint.axis, joint.secondaryAxis, jointAxis, symmetricJoint.transform, symmetricJoint.axis, symmetricJoint.secondaryAxis, root);
}
public static JointAxis GetSymmetricJointAxis(CharacterJoint joint, JointAxis jointAxis, CharacterJoint symmetricJoint, Transform root) {
return GetSymmetricJointAxis(joint.transform, joint.axis, joint.swingAxis, jointAxis, symmetricJoint.transform, symmetricJoint.axis, symmetricJoint.swingAxis, root);
}
public static JointAxis GetSymmetricJointAxis(Transform jointTransform, Vector3 axis, Vector3 secondaryAxis, JointAxis jointAxis, Transform symmetricTransform, Vector3 symmetricAxis, Vector3 symmetricSecondaryAxis, Transform root) {
Vector3 a = JointAxisToVector3(axis, secondaryAxis, jointAxis);
Vector3 aWorld = jointTransform.rotation * a;
Vector3 aWorldMirror = SymmetryTools.Mirror(aWorld, root);
Vector3 aLocalMirror = Quaternion.Inverse(symmetricTransform.rotation) * aWorldMirror;
Vector3 sAVector = AxisTools.GetAxisVectorToDirection(symmetricTransform, aWorldMirror);
Vector3 sA = Vector3.Project(aLocalMirror, sAVector);
return GetJointAxis(symmetricAxis, symmetricSecondaryAxis, sA);
}
public static Vector3 JointAxisToVector3(ConfigurableJoint joint, JointAxis jointAxis) {
return JointAxisToVector3(joint.axis, joint.secondaryAxis, jointAxis);
}
public static Vector3 JointAxisToVector3(CharacterJoint joint, JointAxis jointAxis) {
return JointAxisToVector3(joint.axis, joint.swingAxis, jointAxis);
}
public static Vector3 JointAxisToVector3(Vector3 axis, Vector3 secondaryAxis, JointAxis jointAxis) {
switch(jointAxis) {
case JointAxis.Primary: return axis;
case JointAxis.Secondary: return secondaryAxis;
default: return Vector3.Cross(axis, secondaryAxis);
}
}
public static void ApplyXDeltaToJointLimit(ref ConfigurableJoint joint, float delta, JointAxis jointAxis, bool low) {
switch(jointAxis) {
case JointAxis.Primary:
if (low) {
SoftJointLimit lowX = joint.lowAngularXLimit;
lowX.limit += delta;
joint.lowAngularXLimit = lowX;
} else {
SoftJointLimit highX = joint.highAngularXLimit;
highX.limit -= delta;
joint.highAngularXLimit = highX;
}
break;
case JointAxis.Secondary:
SoftJointLimit y = joint.angularYLimit;
y.limit += delta * 0.5f;
joint.angularYLimit = y;
break;
case JointAxis.Tertiary:
SoftJointLimit z = joint.angularZLimit;
z.limit += delta * 0.5f;
joint.angularZLimit = z;
break;
}
}
public static void ApplyXDeltaToJointLimit(ref CharacterJoint joint, float delta, JointAxis jointAxis, bool low) {
switch(jointAxis) {
case JointAxis.Primary:
if (low) {
SoftJointLimit lowX = joint.lowTwistLimit;
lowX.limit += delta;
joint.lowTwistLimit = lowX;
} else {
SoftJointLimit highX = joint.highTwistLimit;
highX.limit -= delta;
joint.highTwistLimit = highX;
}
break;
case JointAxis.Secondary:
SoftJointLimit y = joint.swing1Limit;
y.limit += delta * 0.5f;
joint.swing1Limit = y;
break;
case JointAxis.Tertiary:
SoftJointLimit z = joint.swing2Limit;
z.limit += delta * 0.5f;
joint.swing2Limit = z;
break;
}
}
public static void ApplyDeltaToJointLimit(ref ConfigurableJoint joint, float delta, JointAxis jointAxis) {
switch(jointAxis) {
case JointAxis.Primary:
SoftJointLimit lowX = joint.lowAngularXLimit;
lowX.limit += delta;
joint.lowAngularXLimit = lowX;
SoftJointLimit highX = joint.highAngularXLimit;
highX.limit += delta;
joint.highAngularXLimit = highX;
break;
case JointAxis.Secondary:
SoftJointLimit y = joint.angularYLimit;
y.limit += delta;
joint.angularYLimit = y;
break;
case JointAxis.Tertiary:
SoftJointLimit z = joint.angularZLimit;
z.limit += delta;
joint.angularZLimit = z;
break;
}
}
public static void ApplyDeltaToJointLimit(ref CharacterJoint joint, float delta, JointAxis jointAxis) {
switch(jointAxis) {
case JointAxis.Primary:
SoftJointLimit lowX = joint.lowTwistLimit;
lowX.limit += delta;
joint.lowTwistLimit = lowX;
SoftJointLimit highX = joint.highTwistLimit;
highX.limit += delta;
joint.highTwistLimit = highX;
break;
case JointAxis.Secondary:
SoftJointLimit y = joint.swing1Limit;
y.limit += delta;
joint.swing1Limit = y;
break;
case JointAxis.Tertiary:
SoftJointLimit z = joint.swing2Limit;
z.limit += delta;
joint.swing2Limit = z;
break;
}
}
public static Vector3 GetLowXAxisWorld(Joint joint) {
return joint.transform.rotation * joint.axis;
}
public static Vector3 GetHighXAxisWorld(Joint joint) {
return joint.transform.rotation * -joint.axis;
}
public static void SwitchXY(ref ConfigurableJoint joint) {
Undo.RecordObject(joint, "Switch Yellow/Green Joint Axis");
Vector3 axis = joint.axis;
joint.axis = joint.secondaryAxis;
joint.secondaryAxis = axis;
}
public static void SwitchXZ(ref ConfigurableJoint joint) {
Undo.RecordObject(joint, "Switch Yellow/Blue Joint Axis");
Vector3 cross = Vector3.Cross(joint.axis, joint.secondaryAxis).normalized;
joint.axis = cross;
}
public static void SwitchYZ(ref ConfigurableJoint joint) {
Undo.RecordObject(joint, "Switch Green/Blue Joint Axis");
Vector3 cross = Vector3.Cross(joint.axis, joint.secondaryAxis).normalized;
joint.secondaryAxis = cross;
}
public static void SwitchXY(ref CharacterJoint joint) {
Undo.RecordObject(joint, "Switch Yellow/Green Joint Axis");
Vector3 axis = joint.axis;
joint.axis = joint.swingAxis;
joint.swingAxis = axis;
}
public static void SwitchXZ(ref CharacterJoint joint) {
Undo.RecordObject(joint, "Switch Yellow/Blue Joint Axis");
Vector3 cross = Vector3.Cross(joint.axis, joint.swingAxis).normalized;
joint.axis = cross;
}
public static void SwitchYZ(ref CharacterJoint joint) {
Undo.RecordObject(joint, "Switch Green/Blue Joint Axis");
Vector3 cross = Vector3.Cross(joint.axis, joint.swingAxis).normalized;
joint.swingAxis = cross;
}
public static void InvertAxis(ref Joint joint) {
Undo.RecordObject(joint, "Invert Axis");
joint.axis = -joint.axis;
}
public static void InvertSecondaryAxis(ref Joint joint) {
if (joint is ConfigurableJoint) {
var j = joint as ConfigurableJoint;
Undo.RecordObject(j, "Invert Secondary Axis");
j.secondaryAxis = -j.secondaryAxis;
}
if (joint is CharacterJoint) {
var j = joint as CharacterJoint;
Undo.RecordObject(j, "Invert Swing Axis");
j.swingAxis = -j.swingAxis;
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 7d88fb763cb86436197038e855690500
timeCreated: 1444653109
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,566 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
using RootMotion;
namespace RootMotion.Dynamics {
[CustomEditor(typeof(RagdollEditor))]
public class RagdollEditorInspector : Editor {
public RagdollEditor script { get { return target as RagdollEditor; }}
private float massMlp = 1f;
private Transform t;
private bool isDragging;
public override void OnInspectorGUI() {
DrawDefaultInspector();
GUILayout.Space(10);
EditorGUILayout.LabelField("Rigidbodies", EditorStyles.boldLabel);
GUILayout.BeginHorizontal();
massMlp = EditorGUILayout.FloatField("Mass Multiplier", massMlp);
if (massMlp <= 0f) massMlp = 0.00001f;
if (GUILayout.Button(new GUIContent("Multiply", "Multiplies the mass of all child Rigidbodies."))) {
Rigidbody[] rigidbodies = GetRigidbodies();
Undo.RecordObjects(rigidbodies, "Multiply Mass");
float totalMass = 0f;
foreach (Rigidbody r in rigidbodies) {
r.mass *= massMlp;
totalMass += r.mass;
}
Debug.Log("Character mass: " + totalMass);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button(new GUIContent("Set All Kinematic", "Enables 'Is Kinematic' on all child Rigidbodies."))) {
Rigidbody[] rigidbodies = GetRigidbodies();
Undo.RecordObjects(rigidbodies, "Set All Kinematic");
foreach (Rigidbody r in rigidbodies) {
r.isKinematic = true;
}
}
if (GUILayout.Button(new GUIContent("Set All Non-Kinematic", "Disables 'Is Kinematic' on all child Rigidbodies."))) {
Rigidbody[] rigidbodies = GetRigidbodies();
Undo.RecordObjects(rigidbodies, "Set All Non-Kinematic");
foreach (Rigidbody r in rigidbodies) {
r.isKinematic = false;
}
}
GUILayout.EndHorizontal();
GUILayout.Space(10);
EditorGUILayout.LabelField("Joints", EditorStyles.boldLabel);
GUILayout.BeginHorizontal();
if (GUILayout.Button(new GUIContent("Disable Preprocessing", "Unchecks 'Enable Preprocessing' on all joints. This can make ragdolls more stable."))) {
Joint[] joints = GetJoints();
Undo.RecordObjects(joints, "Disable Preprocessing");
foreach (Joint j in joints) {
j.enablePreprocessing = false;
}
}
if (GUILayout.Button(new GUIContent("Enable Preprocessing", "Checks 'Enable Preprocessing' on all joints."))) {
Joint[] joints = GetJoints();
Undo.RecordObjects(joints, "Enable Preprocessing");
foreach (Joint j in joints) {
j.enablePreprocessing = true;
}
}
GUILayout.EndHorizontal();
GUILayout.Space(10);
GUILayout.Label("Use the Scene View gizmos to edit Colliders and Joint limits", EditorStyles.miniLabel);
}
private Rigidbody[] GetRigidbodies() {
return (Rigidbody[])script.GetComponentsInChildren<Rigidbody>();
}
private Joint[] GetJoints() {
return (Joint[])script.GetComponentsInChildren<Joint>();
}
void OnEnable() {
t = script.transform;
}
void OnDisable() {
if (script == null) return;
Collider[] colliders = script.transform.GetComponentsInChildren<Collider>();
foreach (Collider collider in colliders) collider.enabled = true;
}
void OnDestroy() {
if (t == null) return;
Collider[] colliders = t.GetComponentsInChildren<Collider>();
foreach (Collider collider in colliders) collider.enabled = true;
}
void OnSceneGUI() {
Rigidbody[] rigidbodies = script.transform.GetComponentsInChildren<Rigidbody>();
if (rigidbodies.Length == 0) return;
Collider[] colliders = script.transform.GetComponentsInChildren<Collider>();
if (script.selectedRigidbody == null) script.selectedRigidbody = rigidbodies[0];
if (script.selectedCollider == null && colliders.Length > 0) script.selectedCollider = colliders[0];
Rigidbody symmetricRigidbody = script.symmetry && script.selectedRigidbody != null? SymmetryTools.GetSymmetric(script.selectedRigidbody, rigidbodies, script.transform): null;
Collider symmetricCollider = script.symmetry && script.selectedCollider != null? SymmetryTools.GetSymmetric(script.selectedCollider, colliders, script.transform): null;
Joint joint = script.selectedRigidbody != null? script.selectedRigidbody.GetComponent<Joint>(): null;
Joint symmetricJoint = joint != null && symmetricRigidbody != null? symmetricRigidbody.GetComponent<Joint>(): null;
// Selected
Transform selected = script.mode == RootMotion.Dynamics.RagdollEditor.Mode.Colliders? (script.selectedCollider != null? script.selectedCollider.transform: null): (script.selectedRigidbody != null? script.selectedRigidbody.transform: null);
if (selected != null) {
Handles.BeginGUI();
GUILayout.BeginVertical(new GUIContent("Ragdoll Editor", string.Empty), "Window", GUILayout.Width(200), GUILayout.Height(20));
GUILayout.BeginHorizontal();
GUILayout.Label(selected.name);
if (GUILayout.Button("Select GameObject", EditorStyles.miniButton)) {
Selection.activeGameObject = selected.gameObject;
}
GUILayout.EndHorizontal();
GUILayout.Space(10);
//GUILayout.BeginVertical("Box");
GUILayout.BeginHorizontal();
GUILayout.Label("Edit Mode", GUILayout.Width(86));
script.mode = (RagdollEditor.Mode)EditorGUILayout.EnumPopup(string.Empty, script.mode, GUILayout.Width(100));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Symmetry", GUILayout.Width(86));
script.symmetry = GUILayout.Toggle(script.symmetry, string.Empty);
GUILayout.EndHorizontal();
GUILayout.Space(10);
// COLLIDERS
if (script.mode == RagdollEditor.Mode.Colliders && selected != null) {
if (script.selectedCollider is CapsuleCollider) {
var capsule = script.selectedCollider as CapsuleCollider;
var capsuleS = symmetricCollider != null? symmetricCollider.transform.GetComponent<CapsuleCollider>(): null;
if (GUILayout.Button("Convert To Box Collider")) {
ColliderTools.ConvertToBoxCollider(capsule);
script.selectedCollider = selected.GetComponent<Collider>();
if (capsuleS != null) ColliderTools.ConvertToBoxCollider(capsuleS);
return;
}
if (GUILayout.Button("Convert To Sphere Collider")) {
ColliderTools.ConvertToSphereCollider(capsule);
script.selectedCollider = selected.GetComponent<Collider>();
if (capsuleS != null) ColliderTools.ConvertToSphereCollider(capsuleS);
return;
}
string capsuleDir = capsule.direction == 0? "X": (capsule.direction == 1? "Y": "Z");
if (GUILayout.Button("Direction: " + capsuleDir)) {
if (capsuleS == null) {
Undo.RecordObject(capsule, "Change Capsule Direction");
} else {
Undo.RecordObjects(new Object[2] { capsule, capsuleS }, "Change Capsule Direction");
}
capsule.direction ++;
if (capsule.direction > 2) capsule.direction = 0;
if (capsuleS != null) capsuleS.direction = capsule.direction;
}
} else if (script.selectedCollider is BoxCollider) {
var box = script.selectedCollider as BoxCollider;
var boxS = symmetricCollider != null? symmetricCollider.transform.GetComponent<BoxCollider>(): null;
if (GUILayout.Button("Convert To Capsule Collider")) {
ColliderTools.ConvertToCapsuleCollider(box);
script.selectedCollider = selected.GetComponent<Collider>();
if (boxS != null) ColliderTools.ConvertToCapsuleCollider(boxS);
return;
}
if (GUILayout.Button("Convert To Sphere Collider")) {
ColliderTools.ConvertToSphereCollider(box);
script.selectedCollider = selected.GetComponent<Collider>();
if (boxS != null) ColliderTools.ConvertToSphereCollider(boxS);
return;
}
if (GUILayout.Button("Rotate Collider")) {
if (boxS == null) {
Undo.RecordObject(box, "Rotate Collider");
} else {
Undo.RecordObjects(new Object[2] { box, boxS }, "Rotate Collider");
}
box.size = new Vector3(box.size.y, box.size.z, box.size.x);
if (boxS != null) boxS.size = box.size;
}
} else if (script.selectedCollider is SphereCollider) {
var sphere = script.selectedCollider as SphereCollider;
var sphereS = symmetricCollider != null? symmetricCollider.transform.GetComponent<SphereCollider>(): null;
if (GUILayout.Button("Convert To Capsule Collider")) {
ColliderTools.ConvertToCapsuleCollider(sphere);
script.selectedCollider = selected.GetComponent<Collider>();
if (sphereS != null) ColliderTools.ConvertToCapsuleCollider(sphereS);
return;
}
if (GUILayout.Button("Convert To Box Collider")) {
ColliderTools.ConvertToBoxCollider(sphere);
script.selectedCollider = selected.GetComponent<Collider>();
if (sphereS != null) ColliderTools.ConvertToBoxCollider(sphereS);
return;
}
}
}
// JOINTS
if (script.mode == RagdollEditor.Mode.Joints) {
if (joint != null && (joint is CharacterJoint || joint is ConfigurableJoint)) {
GUILayout.BeginHorizontal();
GUILayout.Label("Connected Body");
var lastConnectedBody = joint.connectedBody;
var newConnectedBody = (Rigidbody)EditorGUILayout.ObjectField(joint.connectedBody, typeof(Rigidbody), true);
if (newConnectedBody != lastConnectedBody) {
Undo.RecordObject(joint, "Changing Joint ConnectedBody");
joint.connectedBody = newConnectedBody;
}
GUILayout.EndHorizontal();
if (joint is CharacterJoint) {
var j = joint as CharacterJoint;
var sJ = symmetricJoint != null && symmetricJoint is CharacterJoint? symmetricJoint as CharacterJoint: null;
if (GUILayout.Button("Convert to Configurable")) {
JointConverter.CharacterToConfigurable(j);
if (sJ != null) {
JointConverter.CharacterToConfigurable(sJ);
}
}
if (GUILayout.Button("Switch Yellow/Green")) {
JointTools.SwitchXY(ref j);
if (sJ != null) JointTools.SwitchXY(ref sJ);
}
if (GUILayout.Button("Switch Yellow/Blue")) {
JointTools.SwitchXZ(ref j);
if (sJ != null) JointTools.SwitchXZ(ref sJ);
}
if (GUILayout.Button("Switch Green/Blue")) {
JointTools.SwitchYZ(ref j);
if (sJ != null) JointTools.SwitchYZ(ref sJ);
}
if (GUILayout.Button("Invert Yellow")) {
JointTools.InvertAxis(ref joint);
if (sJ != null) JointTools.InvertAxis(ref symmetricJoint);
}
}
if (joint is ConfigurableJoint) {
var j = joint as ConfigurableJoint;
var sJ = symmetricJoint != null && symmetricJoint is ConfigurableJoint? symmetricJoint as ConfigurableJoint: null;
if (GUILayout.Button("Switch Yellow/Green")) {
JointTools.SwitchXY(ref j);
if (sJ != null) JointTools.SwitchXY(ref sJ);
}
if (GUILayout.Button("Switch Yellow/Blue")) {
JointTools.SwitchXZ(ref j);
if (sJ != null) JointTools.SwitchXZ(ref sJ);
}
if (GUILayout.Button("Switch Green/Blue")) {
JointTools.SwitchYZ(ref j);
if (sJ != null) JointTools.SwitchYZ(ref sJ);
}
if (GUILayout.Button("Invert Yellow")) {
JointTools.InvertAxis(ref joint);
if (sJ != null) JointTools.InvertAxis(ref symmetricJoint);
}
}
}
}
GUILayout.EndVertical();
//GUILayout.EndArea();
Handles.EndGUI();
if (script.mode == RagdollEditor.Mode.Joints && joint != null) {
if (joint is CharacterJoint) {
var j = joint as CharacterJoint;
SoftJointLimit lowTwistLimit = j.lowTwistLimit;
SoftJointLimit highTwistLimit = j.highTwistLimit;
SoftJointLimit swing1Limit = j.swing1Limit;
SoftJointLimit swing2Limit = j.swing2Limit;
CharacterJointInspector.DrawJoint(j);
if (symmetricJoint != null && symmetricJoint is CharacterJoint) {
var sJ = symmetricJoint as CharacterJoint;
CharacterJointInspector.DrawJoint(sJ, false, 0.5f);
// Low Twist
if (lowTwistLimit.limit != j.lowTwistLimit.limit) {
Undo.RecordObject(sJ, "Change Joint Limits");
Vector3 lowXAxisWorld = JointTools.GetLowXAxisWorld(j);
Vector3 lowXAxisWorldS = JointTools.GetLowXAxisWorld(sJ);
Vector3 lowXAxisWorldMirror = SymmetryTools.Mirror(lowXAxisWorld, script.transform);
bool low = Vector3.Dot(lowXAxisWorldMirror, lowXAxisWorldS) < 0f;
JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Primary, sJ, script.transform);
float delta = j.lowTwistLimit.limit - lowTwistLimit.limit;
JointTools.ApplyXDeltaToJointLimit(ref sJ, delta, sJointAxis, low);
}
// High Twist
if (highTwistLimit.limit != j.highTwistLimit.limit) {
Undo.RecordObject(sJ, "Change Joint Limits");
Vector3 highXAxisWorld = JointTools.GetHighXAxisWorld(j);
Vector3 highXAxisWorldS = JointTools.GetHighXAxisWorld(sJ);
Vector3 highXAxisWorldMirror = SymmetryTools.Mirror(highXAxisWorld, script.transform);
bool low = Vector3.Dot(highXAxisWorldMirror, highXAxisWorldS) > 0f;
JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Primary, sJ, script.transform);
float delta = j.highTwistLimit.limit - highTwistLimit.limit;
JointTools.ApplyXDeltaToJointLimit(ref sJ, -delta, sJointAxis, low);
}
// Swing 1
if (swing1Limit.limit != j.swing1Limit.limit) {
Undo.RecordObject(sJ, "Change Joint Limits");
JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Secondary, sJ, script.transform);
float delta = j.swing1Limit.limit - swing1Limit.limit;
JointTools.ApplyDeltaToJointLimit(ref sJ, delta, sJointAxis);
}
// Swing 2
if (swing2Limit.limit != j.swing2Limit.limit) {
Undo.RecordObject(sJ, "Change Joint Limits");
JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Tertiary, sJ, script.transform);
float delta = j.swing2Limit.limit - swing2Limit.limit;
JointTools.ApplyDeltaToJointLimit(ref sJ, delta, sJointAxis);
}
}
} else if (joint is ConfigurableJoint) {
var j = joint as ConfigurableJoint;
SoftJointLimit lowAngularXLimit = j.lowAngularXLimit;
SoftJointLimit highAngularXLimit = j.highAngularXLimit;
SoftJointLimit angularYLimit = j.angularYLimit;
SoftJointLimit angularZLimit = j.angularZLimit;
ConfigurableJointInspector.DrawJoint(j);
if (symmetricJoint != null && symmetricJoint is ConfigurableJoint) {
var sJ = symmetricJoint as ConfigurableJoint;
ConfigurableJointInspector.DrawJoint(sJ, false, 0.5f);
// Low X
if (lowAngularXLimit.limit != j.lowAngularXLimit.limit) {
Undo.RecordObject(sJ, "Change Joint Limits");
Vector3 lowXAxisWorld = JointTools.GetLowXAxisWorld(j);
Vector3 lowXAxisWorldS = JointTools.GetLowXAxisWorld(sJ);
Vector3 lowXAxisWorldMirror = SymmetryTools.Mirror(lowXAxisWorld, script.transform);
bool low = Vector3.Dot(lowXAxisWorldMirror, lowXAxisWorldS) < 0f;
JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Primary, sJ, script.transform);
float delta = j.lowAngularXLimit.limit - lowAngularXLimit.limit;
JointTools.ApplyXDeltaToJointLimit(ref sJ, delta, sJointAxis, low);
}
// High X
if (highAngularXLimit.limit != j.highAngularXLimit.limit) {
Undo.RecordObject(sJ, "Change Joint Limits");
Vector3 highXAxisWorld = JointTools.GetHighXAxisWorld(j);
Vector3 highXAxisWorldS = JointTools.GetHighXAxisWorld(sJ);
Vector3 highXAxisWorldMirror = SymmetryTools.Mirror(highXAxisWorld, script.transform);
bool low = Vector3.Dot(highXAxisWorldMirror, highXAxisWorldS) > 0f;
JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Primary, sJ, script.transform);
float delta = j.highAngularXLimit.limit - highAngularXLimit.limit;
JointTools.ApplyXDeltaToJointLimit(ref sJ, -delta, sJointAxis, low);
}
// Y
if (angularYLimit.limit != j.angularYLimit.limit) {
Undo.RecordObject(sJ, "Change Joint Limits");
JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Secondary, sJ, script.transform);
float delta = j.angularYLimit.limit - angularYLimit.limit;
JointTools.ApplyDeltaToJointLimit(ref sJ, delta, sJointAxis);
}
// Z
if (angularZLimit.limit != j.angularZLimit.limit) {
Undo.RecordObject(sJ, "Change Joint Limits");
JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Tertiary, sJ, script.transform);
float delta = j.angularZLimit.limit - angularZLimit.limit;
JointTools.ApplyDeltaToJointLimit(ref sJ, delta, sJointAxis);
}
}
}
}
}
if (!Application.isPlaying) {
foreach (Collider c in colliders) {
c.enabled = script.mode == RagdollEditor.Mode.Colliders;
}
}
// HANDLES
Color color = new Color(0.2f, 0.9f, 0.5f);
Handles.color = color;
if (Event.current.type == EventType.MouseUp) isDragging = false;
if (Event.current.type == EventType.MouseDown) isDragging = false;
if (script.mode == RagdollEditor.Mode.Colliders) {
// Select/move scale colliders
for (int i = 0; i < colliders.Length; i++) {
if (colliders[i] == script.selectedCollider) {
// Moving and scaling selected colliders
switch(Tools.current) {
case Tool.Move:
Vector3 oldPosition = ColliderTools.GetColliderCenterWorld(colliders[i]);
Vector3 newPosition = Handles.PositionHandle(oldPosition, colliders[i].transform.rotation);
if (newPosition != oldPosition) {
if (!isDragging) {
Undo.RecordObjects(SymmetryTools.GetColliderPair(colliders[i], symmetricCollider), "Move Colliders");
isDragging = true;
}
ColliderTools.SetColliderCenterWorld(colliders[i], symmetricCollider, newPosition, script.transform);
}
break;
case Tool.Scale:
Vector3 position = ColliderTools.GetColliderCenterWorld(colliders[i]);
Vector3 oldSize = ColliderTools.GetColliderSize(colliders[i]);
Vector3 oldSizeS = ColliderTools.GetColliderSize(symmetricCollider);
Vector3 newSize = Handles.ScaleHandle(oldSize, position, colliders[i].transform.rotation, HandleUtility.GetHandleSize(position));
if (newSize != oldSize) {
if (!isDragging) {
Undo.RecordObjects(SymmetryTools.GetColliderPair(colliders[i], symmetricCollider), "Scale Colliders");
isDragging = true;
}
ColliderTools.SetColliderSize(colliders[i], symmetricCollider, newSize, oldSize, oldSizeS, script.transform);
}
Handles.color = color;
break;
}
// Dot on selected collider
if (Tools.current != Tool.Scale) {
Handles.color = new Color(0.8f, 0.8f, 0.8f);
Vector3 center = ColliderTools.GetColliderCenterWorld(colliders[i]);
float size = GetHandleSize(center);
Inspector.CubeCap(0, center, colliders[i].transform.rotation, size);
Handles.color = color;
}
} else {
// Selecting colliders
Vector3 center = ColliderTools.GetColliderCenterWorld(colliders[i]);
float size = GetHandleSize(center);
if (Inspector.DotButton(center, Quaternion.identity, size * 0.5f, size * 0.5f)) {
Undo.RecordObject(script, "Change RagdollEditor Selection");
script.selectedCollider = colliders[i];
}
}
}
} else {
// Select joints
for (int i = 0; i < rigidbodies.Length; i++) {
if (rigidbodies[i] == script.selectedRigidbody) {
// Dots on selected joints
Handles.color = new Color(0.8f, 0.8f, 0.8f);
Vector3 center = rigidbodies[i].transform.position;
float size = GetHandleSize(center);
Inspector.CubeCap(0, center, rigidbodies[i].transform.rotation, size);
Handles.color = color;
} else {
// Selecting joints
Vector3 center = rigidbodies[i].transform.position;
float size = GetHandleSize(center);
if (Inspector.DotButton(center, Quaternion.identity, size * 0.5f, size * 0.5f)) {
Undo.RecordObject(script, "Change RagdollEditor Selection");
script.selectedRigidbody = rigidbodies[i];
}
}
}
}
Handles.color = Color.white;
}
private static float GetHandleSize(Vector3 position) {
float s = HandleUtility.GetHandleSize(position) * 0.1f;
return Mathf.Lerp(s, 0.025f, 0.2f);
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1f61264d173e24310b255e76adcfff81
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,94 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion.Dynamics {
// Tools for symmetric operations
public class SymmetryTools: Editor {
public static Rigidbody GetSymmetric(Rigidbody r, Rigidbody[] R, Transform root) {
Vector3 localPos = root.InverseTransformPoint(r.position);
Rigidbody closest = null;
float closestDistance = 0.01f;
foreach (Rigidbody r2 in R) {
if (r != r2) {
Vector3 localPos2 = root.InverseTransformPoint(r2.position);
localPos2.x = -localPos2.x;
float dist = Vector3.Distance(localPos, localPos2);
if (dist < closestDistance) {
closest = r2;
closestDistance = dist;
}
}
}
return closest;
}
public static Collider GetSymmetric(Collider c, Collider[] C, Transform root) {
Vector3 localPos = root.InverseTransformPoint(c.transform.position);
Collider closest = null;
float closestDistance = 0.01f;
foreach (Collider c2 in C) {
if (c != c2) {
Vector3 localPos2 = root.InverseTransformPoint(c2.transform.position);
localPos2.x = -localPos2.x;
float dist = Vector3.Distance(localPos, localPos2);
if (dist < closestDistance) {
closest = c2;
closestDistance = dist;
}
}
}
return closest;
}
public static Vector3 MirrorDelta(Transform r, Transform s, Transform root, Vector3 delta) {
Vector3 dXW = r.right * delta.x;
Vector3 dYW = r.up * delta.y;
Vector3 dZW = r.forward * delta.z;
Vector3 dXWM = Mirror(dXW, root);
Vector3 dYWM = Mirror(dYW, root);
Vector3 dZWM = Mirror(dZW, root);
Vector3 deltaS = Vector3.zero;
deltaS = DeltaSize(deltaS, s, dXWM, delta.x);
deltaS = DeltaSize(deltaS, s, dYWM, delta.y);
deltaS = DeltaSize(deltaS, s, dZWM, delta.z);
return deltaS;
}
public static Vector3 Mirror(Vector3 v, Transform root) {
Vector3 local = root.InverseTransformVector(v);
return root.TransformVector(-local.x, local.y, local.z);
}
public static Vector3 DeltaSize(Vector3 size, Transform t, Vector3 direction, float delta) {
Axis axis = AxisTools.GetAxisToDirection(t, direction);
switch(axis) {
case Axis.X: size.x += delta; break;
case Axis.Y: size.y += delta; break;
case Axis.Z: size.z += delta; break;
}
return size;
}
public static Collider[] GetColliderPair(Collider r, Collider s) {
if (s == null) return new Collider[1] {r};
return new Collider[2] {r, s};
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: dd9c3cde48ab14fb2991ac46cf73af84
timeCreated: 1444653494
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: dab395325550b7642aab381552be816e
folderAsset: yes
timeCreated: 1478090994
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,22 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion {
// Just making sure the camera controller updates last
[CustomEditor(typeof(CameraController))]
public class CameraControllerInspector : Editor {
private CameraController script { get { return target as CameraController; }}
private MonoScript monoScript;
void OnEnable() {
if (!Application.isPlaying) {
monoScript = MonoScript.FromMonoBehaviour(script);
int currentExecutionOrder = MonoImporter.GetExecutionOrder(monoScript);
if (currentExecutionOrder != 10200) MonoImporter.SetExecutionOrder(monoScript, 10200);
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b4af31e5f2e82444d80e3b3020689f59
timeCreated: 1444227100
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 2ecaf76b180974576a00c022bf77d0b6
folderAsset: yes
timeCreated: 1436260609
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,26 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace RootMotion {
/*
* Custom inspector for BipedReferences
* */
public class BipedReferencesInspector: Inspector {
/*
* Draws the default property, returns true if modified
* */
public static bool AddModifiedInspector(SerializedProperty prop) {
EditorGUILayout.PropertyField(prop, true);
if (prop.isExpanded) EditorGUILayout.Space();
// If references have changed reinitiate the bipedIK.
if (prop.serializedObject.ApplyModifiedProperties()) return true;
return false;
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 5880965ffd5754534ac6d4c1fce8bb73
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,41 @@
using UnityEngine;
using System.Collections;
using UnityEditor;
namespace RootMotion {
[CustomEditor(typeof(Comments))]
public class CommentsInspector : Editor {
private Comments script { get { return target as Comments; }}
private GUIStyle style = new GUIStyle();
// Black and white
//private static Color pro = new Color(0.7f, 0.7f, 0.7f, 1f);
//private static Color free = new Color(0, 0, 0, 1);
// Colors
private static Color pro = new Color(0.5f, 0.7f, 0.3f, 1f);
private static Color free = new Color(0.2f, 0.3f, 0.1f, 1f);
public override void OnInspectorGUI() {
if (serializedObject == null) return;
style.wordWrap = true;
style.normal.textColor = EditorGUIUtility.isProSkin? pro: free;
serializedObject.Update();
EditorGUILayout.Space();
string text = EditorGUILayout.TextArea(script.text, style);
if (text != script.text) {
Undo.RecordObject(script, "Edit Comments");
script.text = text;
}
EditorGUILayout.Space();
serializedObject.ApplyModifiedProperties();
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: c93e61235cb3cad45aec1688c1990eff
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,323 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace RootMotion {
/*
* Inspector contains helper methods for creating undoable custom inspectors with enforced layout, tooltips and styling
* */
public class Inspector {
#region InspectorGUI tools
public const int indent = 16;
public delegate void DrawArrayElement(SerializedProperty prop, bool editHierarchy);
public delegate void DrawArrayElementLabel(SerializedProperty prop, bool editHierarchy);
public delegate void OnAddToArray(SerializedProperty prop);
private static string arrayName;
private static SerializedProperty property;
private static SerializedProperty element;
public static string GetArrayName(SerializedProperty array, string emptyName, string propertyName = "") {
if (array.arraySize < 1) return emptyName;
property = propertyName == ""? array.GetArrayElementAtIndex(0): array.GetArrayElementAtIndex(0).FindPropertyRelative(propertyName);
return GetObjectReferenceName(property, emptyName);
}
public static string GetObjectReferenceName(SerializedProperty prop, string emptyName) {
if (prop.objectReferenceValue == null) return emptyName;
return prop.objectReferenceValue.name;
}
public static void AddArray(SerializedProperty prop, GUIContent guiContent, bool editHierarchy, bool changeOrder, DrawArrayElement drawArrayElement = null, OnAddToArray onAddToArray = null, DrawArrayElementLabel drawArrayElementLabel = null, bool showHeading = true) {
int resetIndent = EditorGUI.indentLevel;
// Array heading
if (showHeading) {
GUILayout.BeginHorizontal();
GUILayout.Space(EditorGUI.indentLevel * indent);
if (drawArrayElement == null) {
GUILayout.Label(guiContent.text + " (" + prop.arraySize.ToString() + ")", GUILayout.Width(150));
} else {
EditorGUILayout.PropertyField(prop, new GUIContent(guiContent.text + " (" + prop.arraySize.ToString() + ")", string.Empty), false, GUILayout.Width(150));
}
GUILayout.EndHorizontal();
}
int deleteIndex = -1;
if (drawArrayElement == null || !showHeading) prop.isExpanded = true;
// Draw Array elements
if (prop.isExpanded) {
for(int i = 0; i < prop.arraySize; i++) {
GUILayout.BeginHorizontal(); // Main
GUILayout.Space(((EditorGUI.indentLevel + 1) * indent));
GUILayout.BeginVertical();
element = prop.GetArrayElementAtIndex(i);
// Label
GUILayout.BeginHorizontal();
if (editHierarchy && GUILayout.Button(new GUIContent("-", "Remove"), changeOrder? EditorStyles.miniButtonLeft: EditorStyles.miniButton, GUILayout.Width(20))){
deleteIndex = i;
}
if (changeOrder) {
if (GUILayout.Button(new GUIContent("<", "Move up"), editHierarchy? EditorStyles.miniButtonMid: EditorStyles.miniButtonLeft, GUILayout.Width(20))) {
int moveTo = i == 0? prop.arraySize - 1: i - 1;
prop.MoveArrayElement(i, moveTo);
prop.isExpanded = true;
}
if (GUILayout.Button(new GUIContent(">", "Move down"), EditorStyles.miniButtonRight, GUILayout.Width(20))) {
int moveTo = i == prop.arraySize - 1? 0: i + 1;
prop.MoveArrayElement(i, moveTo);
prop.isExpanded = true;
}
}
// Calling the DrawArrayElementLabel delegate
if (drawArrayElementLabel != null) {
drawArrayElementLabel(element, editHierarchy);
}
GUILayout.EndHorizontal(); // End Label
// Array Element
GUILayout.BeginVertical();
if (element.isExpanded && drawArrayElement != null) {
drawArrayElement(element, editHierarchy);
}
GUILayout.EndVertical();
GUILayout.Space(5);
GUILayout.EndVertical(); // End Style
GUILayout.EndHorizontal(); // End Main
}
// Deleting array elements
if (deleteIndex != -1) prop.DeleteArrayElementAtIndex(deleteIndex);
// Adding array elements
GUILayout.BeginHorizontal();
GUILayout.Space(((EditorGUI.indentLevel + 1) * indent) + 4);
GUILayout.BeginVertical();
if (editHierarchy && GUILayout.Button(new GUIContent("+", "Add"), EditorStyles.miniButton, GUILayout.Width(20))) {
prop.arraySize ++;
if (onAddToArray != null) onAddToArray(prop.GetArrayElementAtIndex(prop.arraySize - 1));
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
EditorGUI.indentLevel = resetIndent;
}
public static void AddContent(SerializedContent content, bool addChildren = false, params GUILayoutOption[] options) {
EditorGUILayout.PropertyField(content.prop, content.guiContent, addChildren, options);
}
public static void AddClampedFloat(SerializedContent content, float min = 0f, float max = 1f, params GUILayoutOption[] options) {
AddClampedFloat(content.prop, content.guiContent, min, max, options);
}
public static void AddClampedInt(SerializedContent content, int min = int.MinValue, int max = int.MaxValue, params GUILayoutOption[] options) {
AddClampedInt(content.prop, content.guiContent, min, max, options);
}
public static void AddClampedFloat(SerializedProperty prop, GUIContent guiContent, float min = 0f, float max = 1f, params GUILayoutOption[] options) {
EditorGUILayout.PropertyField(prop, guiContent, options);
prop.floatValue = Mathf.Clamp(prop.floatValue, min, max);
}
public static void AddClampedInt(SerializedProperty prop, GUIContent guiContent, int min = int.MinValue, int max = int.MaxValue, params GUILayoutOption[] options) {
EditorGUILayout.PropertyField(prop, guiContent, options);
prop.intValue = Mathf.Clamp(prop.intValue, min, max);
}
public static void AddObjectReference(SerializedProperty prop, GUIContent guiContent, bool editHierarchy, int labelWidth, bool alignToEdge = true) {
if (alignToEdge) GUILayout.BeginHorizontal();
EditorGUILayout.LabelField(guiContent, GUILayout.MinWidth(labelWidth));
if (editHierarchy) {
EditorGUILayout.PropertyField(prop, GUIContent.none);
} else {
UnityEngine.Object obj = prop.objectReferenceValue;
EditorGUILayout.LabelField(new GUIContent(obj != null? obj.name: "None"));
}
if (alignToEdge) GUILayout.EndHorizontal();
}
public static void AddObjectReference(SerializedProperty prop, GUIContent guiContent, bool editHierarchy, int labelWidth, int propWidth, bool alignToEdge = true) {
//if (alignToEdge) GUILayout.BeginHorizontal();
EditorGUILayout.LabelField(guiContent, GUILayout.Width(labelWidth));
if (editHierarchy) {
EditorGUILayout.PropertyField(prop, GUIContent.none, GUILayout.Width(propWidth));
} else {
UnityEngine.Object obj = prop.objectReferenceValue;
EditorGUILayout.LabelField(new GUIContent(obj != null? obj.name: "None"), GUILayout.Width(propWidth));
}
//if (alignToEdge) GUILayout.EndHorizontal();
}
#endregion InspectorGUI tools
#region SceneGUI tools
public static bool Button(string name, string toolTip, Object undoObject, params GUILayoutOption[] options) {
bool button = GUILayout.Button(new GUIContent(name, toolTip), options);
if (button && !Application.isPlaying) Undo.RecordObject(undoObject, name);
return button;
}
public static Object AddObject(Object input, string name, string toolTip, System.Type type, bool allowSceneObjects, Object undoObject, params GUILayoutOption[] options) {
Object newValue = EditorGUILayout.ObjectField(new GUIContent(name, toolTip), input, type, allowSceneObjects, options);
return RecordObject(input, newValue, name, undoObject);
}
public static System.Enum AddEnum(System.Enum input, string name, string toolTip, Object undoObject, params GUILayoutOption[] options) {
System.Enum newValue = EditorGUILayout.EnumPopup(new GUIContent(name, toolTip), input, options);
if (newValue.ToString() != input.ToString() && !Application.isPlaying) Undo.RecordObject(undoObject, name);
return newValue;
}
public static void AddHorizontalSlider(ref float input, float leftValue, float rightValue, string name, string toolTip, Object undoObject, int labelWidth, int minWidth) {
EditorGUILayout.BeginHorizontal();
GUILayout.Label(new GUIContent(name, toolTip), GUILayout.Width(labelWidth));
input = RecordObjectFloat(input, GUILayout.HorizontalSlider(input, leftValue, rightValue, GUILayout.MinWidth(minWidth)), name, undoObject);
input = Mathf.Clamp(RecordObjectFloat(input, EditorGUILayout.FloatField(string.Empty, input, GUILayout.Width(75)), name, undoObject), leftValue, rightValue);
EditorGUILayout.EndHorizontal();
}
public static void AddFloat(ref float input, string name, string toolTip, Object undoObject, float min = -Mathf.Infinity, float max = Mathf.Infinity, params GUILayoutOption[] options) {
input = Mathf.Clamp(RecordObjectFloat(input, EditorGUILayout.FloatField(new GUIContent(name, toolTip), input, options), name, undoObject), min, max);
}
public static void AddInt(ref int input, string name, string toolTip, Object undoObject, int min = -int.MaxValue, int max = int.MaxValue, params GUILayoutOption[] options) {
input = Mathf.Clamp((int)RecordObjectFloat((float)input, (float)EditorGUILayout.IntField(new GUIContent(name, toolTip), input, options), name, undoObject), min, max);
}
public static void AddBool(ref bool input, string name, string toolTip, Object undoObject) {
bool newValue = EditorGUILayout.Toggle(new GUIContent(name, toolTip), input);
if (newValue != input && !Application.isPlaying) {
Undo.RecordObject(undoObject, name);
}
input = newValue;
}
public static void AddVector3(ref Vector3 input, string name, Object undoObject, params GUILayoutOption[] options) {
Vector3 newValue = EditorGUILayout.Vector3Field(name, input, options);
if (newValue != input && !Application.isPlaying) {
Undo.RecordObject(undoObject, name);
}
input = newValue;
}
private static float RecordObjectFloat(float input, float newValue, string name, Object undoObject) {
if (newValue != input && !Application.isPlaying) Undo.RecordObject(undoObject, name);
return newValue;
}
private static Object RecordObject(Object input, Object newValue, string name, Object undoObject) {
if (newValue != input && !Application.isPlaying) Undo.RecordObject(undoObject, name);
return newValue;
}
#endregion SceneGUI tools
#region Platform dependent
public static void SphereCap(int controlID, Vector3 position, Quaternion rotation, float size) {
#if UNITY_5_6_OR_NEWER
Handles.SphereHandleCap(controlID, position, rotation, size, EventType.Repaint);
#else
Handles.SphereCap(controlID, position, rotation, size);
#endif
}
public static void CubeCap(int controlID, Vector3 position, Quaternion rotation, float size) {
#if UNITY_5_6_OR_NEWER
Handles.CubeHandleCap(controlID, position, rotation, size, EventType.Repaint);
#else
Handles.CubeCap(controlID, position, rotation, size);
#endif
}
public static void ConeCap(int controlID, Vector3 position, Quaternion rotation, float size) {
#if UNITY_5_6_OR_NEWER
Handles.ConeHandleCap(controlID, position, rotation, size, EventType.Repaint);
#else
Handles.ConeCap(controlID, position, rotation, size);
#endif
}
public static void ArrowCap(int controlID, Vector3 position, Quaternion rotation, float size) {
#if UNITY_5_6_OR_NEWER
Handles.ArrowHandleCap(controlID, position, rotation, size, EventType.Repaint);
#else
Handles.ArrowCap(controlID, position, rotation, size);
#endif
}
public static void CircleCap(int controlID, Vector3 position, Quaternion rotation, float size) {
#if UNITY_5_6_OR_NEWER
Handles.CircleHandleCap(controlID, position, rotation, size, EventType.Repaint);
#else
Handles.CircleCap(controlID, position, rotation, size);
#endif
}
public static void DotCap(int controlID, Vector3 position, Quaternion rotation, float size) {
#if UNITY_5_6_OR_NEWER
Handles.DotHandleCap(controlID, position, rotation, size, EventType.Repaint);
#else
Handles.DotCap(controlID, position, rotation, size);
#endif
}
public static bool DotButton(Vector3 position, Quaternion direction, float size, float pickSize) {
#if UNITY_5_6_OR_NEWER
return Handles.Button(position, direction, size, pickSize, Handles.DotHandleCap);
#else
return Handles.Button(position, direction, size, pickSize, Handles.DotCap);
#endif
}
public static bool SphereButton(Vector3 position, Quaternion direction, float size, float pickSize) {
#if UNITY_5_6_OR_NEWER
return Handles.Button(position, direction, size, pickSize, Handles.SphereHandleCap);
#else
return Handles.Button(position, direction, size, pickSize, Handles.SphereCap);
#endif
}
public static float ScaleValueHandleSphere(float value, Vector3 position, Quaternion rotation, float size, float snap) {
#if UNITY_5_6_OR_NEWER
return Handles.ScaleValueHandle(value, position, rotation, size, Handles.SphereHandleCap, snap);
#else
return Handles.ScaleValueHandle(value, position, rotation, size, Handles.SphereCap, snap);
#endif
}
#endregion Platform dependent
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: c18519ac3faf848ca878cd0509c4ce8c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,65 @@
using UnityEditor;
using UnityEngine;
namespace RootMotion
{
// Custom drawer for the LargeHeader attribute
[CustomPropertyDrawer(typeof(InspectorComment))]
public class InspectorCommentDrawer : DecoratorDrawer
{
// Used to calculate the height of the box
public static Texture2D lineTex = null;
private GUIStyle style;
InspectorComment comment { get { return ((InspectorComment)attribute); } }
// Get the height of the element
public override float GetHeight()
{
style = GetStyle();
return style.CalcHeight(new GUIContent(comment.name), EditorGUIUtility.currentViewWidth) + 10f;
//return base.GetHeight() * 1.5f;
}
// Override the GUI drawing for this attribute
public override void OnGUI(Rect pos)
{
// Get the color the line should be
Color color = Color.white;
switch (comment.color.ToString().ToLower())
{
case "white": color = Color.white; break;
case "red": color = Color.red; break;
case "blue": color = Color.blue; break;
case "green": color = Color.green; break;
case "gray": color = Color.gray; break;
case "grey": color = Color.grey; break;
case "black": color = Color.black; break;
}
color *= 0.5f;
style = GetStyle();
GUI.color = color;
Rect labelRect = pos;
//labelRect.y += 10;
EditorGUI.LabelField(labelRect, new GUIContent(comment.name), style);
GUI.color = Color.white;
}
private GUIStyle GetStyle()
{
var style = new GUIStyle(GUI.skin.label);
style.fontSize = 10;
style.fontStyle = FontStyle.Normal;
style.wordWrap = true;
style.alignment = TextAnchor.LowerLeft;
return style;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: c87de0c0b96012c43b2684edd36e3289
timeCreated: 1533045048
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,54 @@
using UnityEditor;
using UnityEngine;
namespace RootMotion {
// Custom drawer for the LargeHeader attribute
[CustomPropertyDrawer (typeof (LargeHeader))]
public class LargeHeaderDrawer : DecoratorDrawer
{
// Used to calculate the height of the box
public static Texture2D lineTex = null;
private GUIStyle style;
LargeHeader largeHeader { get { return ((LargeHeader) attribute); } }
// Get the height of the element
public override float GetHeight ()
{
return base.GetHeight () * 2f;
}
// Override the GUI drawing for this attribute
public override void OnGUI (Rect pos)
{
// Get the color the line should be
Color color = Color.white;
switch (largeHeader.color.ToString().ToLower())
{
case "white": color = Color.white; break;
case "red": color = Color.red; break;
case "blue": color = Color.blue; break;
case "green": color = Color.green; break;
case "gray": color = Color.gray; break;
case "grey": color = Color.grey; break;
case "black": color = Color.black; break;
}
color *= 0.7f;
style = new GUIStyle(GUI.skin.label);
style.fontSize = 16;
style.fontStyle = FontStyle.Normal;
style.alignment = TextAnchor.LowerLeft;
GUI.color = color;
Rect labelRect = pos;
//labelRect.y += 10;
EditorGUI.LabelField(labelRect, largeHeader.name, style);
GUI.color = Color.white;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 070e28ee88d2b41128ff9e7520f48015
timeCreated: 1452022291
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,19 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace RootMotion {
/*
* Serialized content is used for caching serialized properties and their respective GUIContent and enforcing unified GUI layout.
* */
public struct SerializedContent {
public SerializedProperty prop;
public GUIContent guiContent;
public SerializedContent(SerializedProperty prop, GUIContent guiContent) {
this.prop = prop;
this.guiContent = guiContent;
}
}
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: fa9bdb02a53b1450c8f474d42de57950
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 96b187132b9a544c8a08d5b29323cc10
folderAsset: yes
timeCreated: 1429874947
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,762 @@
/*! \mainpage
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/on7wAz0fsGg" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<br>Welcome to PuppetMaster, an advanced character physics tool for Unity!
\section contains PuppetMaster Contains
- Tools for animating ragdolls of any kind
- Automated, easy to use ragdoll generator for all biped characters
- Ragdoll Editor - enabling you to intuitively edit colliders and joints in the Scene View.
- Joint Inspectors - visualizing and editing Character and Configurable Joints in the Scene View
\section technicaloverview Technical Overview
- Does NOT require Unity Pro
- Works with Humanoid, Generic and Legacy characters.
- Written in C#, all scripts are namespaced under %RootMotion and %RootMotion.Dynamics to avoid any naming conflicts with Your existing assets.
- Tested on Standalone, Web Player, IOS and Android
- Custom undoable inspectors and scene view handles
- Warning system to safeguard from null references and invalid setups (will not overflow your console with warnings)
- Optimized for great performance
- Modular, easily extendable. Compose your own custom character rigs
- User manual, HTML documentation, fully documented code
- Demo scenes and example scripts for all components
- Tested on a wide range of characters
*/
/*! \page page1 Creating Ragdolls
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/y-luLRVmL7E?list=PLVxSIA1OaTOuE2SB9NUbckQ9r2hTg4mvL" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>BipedRagdollCreator</b>
<br>
PuppetMaster contains a very easy to use visual ragdoll creation tool for biped characters (can actually be used on any character with at least 4 limbs) called BipedRagdollCreator.
When the BipedRagdollCreator.cs component is enabled on a character, the ragdoll components will be destroyed and recreated each time you change the references or options.
This enables for fast and intuitive live editing.
<b>Getting started</b>
- Drag a character model to the scene and attach the BipedRagdollCreator.cs component. Biped bone references will be filled in automatically if it is a Humanoid character. In other cases, they can be filled in manually.
- Click on "Create a Ragdoll" to start live-updating and editing the ragdoll. You should then see the Rigidbody, Collider and Joint components added to the character.
- Note that with all adjustments to the parameters of BipedRagdollCreator the ragdoll components will be deleted and recreated, so do not make any references to them until the BipedRagdollCreator has been removed.
- Only ConfigurableJoints are supported by the PuppetMaster at this time so use "Configurable" as "Joints".
- Once you are happy with the basic Collider and Joint types and other settings in the "Options", click on "Start Editing Manually" to make final manual adjustments using the RagdollEditor. This will remove the BipedRagdollCreator component.
<b>Component variables:</b>
- <b>references</b> - references to the biped bones.
- <b>weight</b> - the total weight of the character. Will be distributed biometrically between the ragdoll Rigidbodies.
- <b>spine</b> - toggle the spine bone included in the ragdoll.
- <b>chest</b> - toggle the chest bone included in the ragdoll.
- <b>hands</b> - toggle the hand bones included in the ragdoll.
- <b>feet</b> - toggle the foot bones included in the ragdoll.
- <b>joints</b> - build the ragdoll with ConfigurableJoints or CharacterJoints? NB! PuppetMaster can use only ConfigurableJoints.
- <b>jointRange</b> - multiplies joint limit ranges.
- <b>colliderLengthOverlap</b> - determines how much the colliders overlap each other, supports also negative values.
- <b>torsoColliders</b> - use BoxColliders or CapsuleColliders for the body part.
- <b>headCollider</b> - use BoxCollider or CapsuleCollider for the body part.
- <b>armColliders</b> - use BoxColliders or CapsuleColliders for the body part.
- <b>handColliders</b> - use BoxColliders or CapsuleColliders for the body part.
- <b>legColliders</b> - use BoxColliders or CapsuleColliders for the body part.
- <b>footColliders</b> - use BoxColliders or CapsuleColliders for the body part.
\image html BipedRagdollCreator2.png
<b>Creating ragdolls in runtime:</b>
\code
[Tooltip("The character prefab/FBX.")]
public GameObject prefab;
void Start() {
// Instantiate the character
GameObject instance = GameObject.Instantiate(prefab);
// Find bones (Humanoids)
BipedRagdollReferences r = BipedRagdollReferences.FromAvatar(instance.GetComponent<Animator>());
// How would you like your ragdoll?
BipedRagdollCreator.Options options = BipedRagdollCreator.AutodetectOptions(r);
// Edit options here if you need to
//options.headCollider = RagdollCreator.ColliderType.Box;
//options.weight *= 2f;
//options.joints = RagdollCreator.JointType.Character;
// Create the ragdoll
BipedRagdollCreator.Create(r, options);
Debug.Log("A ragdoll was successfully created.");
}
void Update() {
// If bone proportions have changed, just clear and recreate:
//BipedRagdollCreator.ClearBipedRagdoll(r); //ClearAll if you have changed references
//BipedRagdollCreator.Create(r, options);
}
\endcode
*/
/*! \page page2 Editing Ragdolls
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/y-luLRVmL7E?list=PLVxSIA1OaTOuE2SB9NUbckQ9r2hTg4mvL" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>RagdollEditor</b>
<br>
RagdollEditor is an intuitive visualized and Scene View tool for editing Colliders, Joints and Rigidbody settings. Symmetry is supported for collider position, size and joint limit editing. All actions with the RagdollEditor are undoable.
\image html RagdollEditorScene.png
<b>Getting started</b>
- Add the RagdollEditor.cs component to the root of the ragdoll.
- Click on the green buttons on the Colliders/Joints to select them.
- Use the Move/Scale handles to edit the Colliders and Joints in the Scene View.
- Remove the component when you are done.
<b>Component interface:</b>
- <b>Mass Multiplier</b> - multiplies the mass of all the Rigidbodies with the value.
- <b>Set All Kinematic</b> - set all Rigidbodies kinematic.
- <b>Set All Non-Kinematic</b> - set all Rigidbodies non-kinematic.
- <b>Disable Preprocessing</b> - uncheck 'enablePreprocessing' on all Joints. This can make the ragdoll more stable under certain circumstances.
- <b>Enable Preprocessing</b> - check 'enablePreprocessing' on all Joints.
\image html RagdollEditor.png
<b>Collider tool:</b>
- <b>Select GameObject</b> - changes Unity selection to the currently edited Collider's GameObject
- <b>Edit Mode</b> - switch to Joint editing mode.
- <b>Symmetry</b> - enables symmetric editing. Symmetry works for the closest Collider (within a threshold) on the other side of the ZY plane (local space of the GameObject of RagdollEditor).
- <b>Convert To Capsule Collider</b> - converts the selected collider to CapsuleCollider.
- <b>Convert To Sphere Collider</b> - converts the selected collider to SphereCollider.
- <b>Rotate Collider</b> - rotates the collider size vector orthogonally.
\image html RagdollEditorColliders.png
<b>Joint tool:</b>
- <b>Select GameObject</b> - changes Unity selection to the currently edited Joint's GameObject
- <b>Edit Mode</b> - switch to Collider editing mode.
- <b>Symmetry</b> - enables symmetric editing. Symmetry works for the closest Joint (within a threshold) on the other side of the ZY plane (local space of the GameObject of RagdollEditor).
- <b>Connected Body</b> - select or change the connectedBody of the selected Joint.
- <b>Switch Yellow/Green</b> - switches the respective Joint axes.
- <b>Switch Yellow/Blue</b> - switches the respective Joint axes.
- <b>Switch Green/blue</b> - switches the respective Joint axes.
- <b>Invert Yellow</b> - inverts Joint.axis.
\image html RagdollEditorJoints.png
*/
/*! \page page3 PuppetMaster Overview
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/on7wAz0fsGg" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<br>
<b>Terminology</b>
<br>
PuppetMaster uses a <b>"Dual Rig"</b> that consists of the normal animated character (from hereby: <b>"Target"</b>) and the simplified ragdoll structure (<b>"Puppet"</b>).
The main purpose of PuppetMaster is to make the Puppet ragdoll physically follow the motion and animation of the animated Target character.
It will do so by two means, first is articulating the joints (<b>"Muscles"</b>), the other is pinning the rigidbodies to their targets using AddForce commands (<b>"Pins"</b>).
The classes that control the behaviour of the Muscles and handle their strength, pinning and other properties are called <b>"Puppet Behaviours"</b>.
The dual rig and the Behaviours will share a common parent GameObject (<b>"Root"</b>) that serves as a container for the PuppetMaster character rig.
The kinematic Target character will be mapped to the dynamic Puppet ragdoll by the means of <b>"Mapping"</b>, which can also be smoothly blended in and out for the entire character or for each Muscle separately.
<b>Dual Rig</b>
<br>
\image html DualRigExplained.png
The main advantage of using a dual rig over a single character setup is performance. It is much less expensive mostly due to not having the necessity of performing costly transformations with objects that have Colliders attached.
The performance win becomes even greater when having to do IK/FK procedures on the target pose. The PuppetMaster can be smoothly blended to run in Kinematic or Disabled mode. The former will simply make the ragdoll kinematic and match it with the target, the latter will completely deactivate the ragdoll when you don't need it.
The dual rig also allows for choosing between flat or tree hierarchy modes for the ragdoll (click "Flat/Tree Hierarhcy" from the PuppetMaster's context menu) and will allow for sharing ragdolls between multiple characters in a future release of PuppetMaster.
The PuppetMaster will automatically set up the dual rig for you when provided with a reference to a traditional ragdoll character.
<b>Target</b>
<br>
\image html Target.png
The Target can be thought of as the normal animated character that you would see in any game, it usually has a character controller and any other gameplay components attached.
Each frame, PuppetMaster will read the pose of the Target and feed it to the Muscles of the Puppet for following.
After physics has solved, the Target will be mapped to the pose of the Puppet based on the mapping settings and stay there until animation overwrites it the next frame.
<b>Puppet</b>
<br>
\image html Puppet.png
The simplified ragdoll structure (Puppet) is essentially a duplicate of the Target, but with ragdoll Components attached and all other Components and GameObjects unrelated to physics stripped.
The PuppetMaster requires for the ragdoll to be set up using ConfigurableJoints only. Any other Joint can be converted to a ConfigurableJoint by selecting the (root) GameObject and clicking on "GameObject/Convert to ConfigurableJoints" from the menu bar.
The Puppet ragdoll can be set up in tree or flat hierarchy modes (click "Flat/Tree Hierarhcy" from the PuppetMaster's context menu).
<b>Muscles</b>
<br>
\image html Muscles.png
The PuppetMaster will turn each ConfigurableJoint of the Puppet into a Muscle that maintains a reference to it's animated target and automatically calculates Joint target rotations, pinning forces and other values.
When the Puppet is unpinned, the ragdoll will follow the animation in muscle space and the result is physically authentic and accurate.
When pinned, the pinning forces will move the ragdoll bones to the world space position of their targets, they can be imagined as spring joints pulling each ragdoll bone towards their animated target.
Pinning is therefore an unnatural force that can be managed to make the ragdoll simulate game character motion that physically would be almost unachievable.
The Muscles are listed in the PuppetMaster's inspector, each having individual properties, enabling you to specify the physical behaviour of each Muscle or Muscle Group.
<b>Modes</b>
<br>
\image html Modes.png
The PuppetMaster can run in 3 Modes. <b>Active</b> is the active ragdoll mode that makes the Puppet physically follow it's Target by employing the muscle forces, pins or both at the same time. The Puppet is able to collide with and be affected by objects in the scene.
The <b>Kinematic</b> mode makes the Rigidbodies of the Puppet kinematic and the Muscles will not be used anymore. The Puppet is still able to collide with objects and receive raycast hits.
The <b>Disabled</b> mode completely deactivates the Puppet along with it's Rigidbodies and Colliders. In Disabled mode the PuppetMaster will not have any effect on the performance. All modes can be blended in/out smoothly in respect to the "Blend Time" parameter.
<b>Puppet Behaviours</b>
<br>
\image html Behaviours2.png
The Puppet Behaviours are classes that inherit from the abstract BehaviourBase.cs and that's main idea is to provide a pattern for developing functionalities that dynamically adjust muscle and pin weights, strength and other properties or make kinematic adjustments to the target pose.
The most important Puppet Behaviour is the BehaviourPuppet.cs that handles the pinning of Puppets to target animation, releasing those pins in case of collision and re-tightening them when getting up from the ground.
The Puppet Behaviours can be switched, for example when the BehaviourPuppet looses balance, it can theoretically switch to BehaviourCatchFall or BehaviourWindmill (both missing from the initial release, but will be developed in the future).
The Puppet Behaviours are designed so tha they would not contain a single external object reference. That means they can be simply duplicated and moved to another Puppet.
*/
/*! \page page4 PuppetMaster Setup
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/mIN9bxJgfOU?list=PLVxSIA1OaTOuE2SB9NUbckQ9r2hTg4mvL" frameborder="0" allowfullscreen></iframe>\endhtmlonly
To set up a character with ragdoll components as a Puppet, the easiest way is to simply add the PuppetMaster component to it and click on the "Set Up PuppetMaster" button.
That will make a duplicate of the character and set the duplicate up as the Puppet while the selected instance will become the Target. Both will be parented to a new GameObject that is the root container for the entire character rig.
A GameObject with the character's name + " Behaviours" will also be added. All Puppet Behaviours (BehaviourPuppet, BehaviourFall...) should be parented to it.
Alternately you can assign another character hierarchy to become the Target. PuppetMaster supports sharing ragdolls between multiple characters as long as the positions of the muscles match with their targets.
Rotations can be different, so you can even use another rig with different bone orientations.
"Character Controller Layer" and "Ragdoll Layer" will be applied to the Target and Puppet respectively to avoid collisions between the character controller and the ragdoll colliders.
Make sure collisions between the two layers are disabled in the Edit/Project Settings/Physics/Layer Collision Matrix.
\image html PuppetMasterSetup.png
<b>Creating puppets in run-time</b>
<br>
The procedure and code for setting up puppets in run-time is demonstrated in the "Creating Puppets In Runtime" demo scene and CreatePuppetInRuntime.cs script.
It requires for the character to be already set up with ragdoll components.
\code
Transform ragdoll = GameObject.Instantiate(ragdollPrefab, transform.position, transform.rotation) as Transform;
ragdoll.name = instanceName;
// This will duplicate the "ragdoll" instance, remove the ragdoll components from the original and use it as the animated target, setting the duplicate up as a puppet.
PuppetMaster.SetUp(ragdoll, characterControllerLayer, ragdollLayer);
// or...
//PuppetMaster.SetUp(target, ragdoll, characterControllerLayer, ragdollLayer);
// or if you want the "ragdoll" instance to become the puppet, not the target:
//PuppetMaster.SetUpTo(target, characterControllerLayer, ragdollLayer);
Debug.Log("A ragdoll was successfully converted to a Puppet.");
\endcode
*/
/*! \page page5 PuppetMaster Component
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/LYusqeqHAUc" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>Simulation</b>
- <b>state</b> - sets/sets the state of the puppet (Alive, Dead or Frozen). Frozen means the ragdoll will be deactivated once it comes to stop in dead state.
- <b>stateSettings</b> - settings for killing and freezing the puppet.
<BR><b>killDuration</b> - how much does it take to weigh out muscle weight to deadMuscleWeight?
<BR><b>deadMuscleWeight</b> - the muscle weight mlp while the puppet is Dead.
<BR><b>deadMuscleDamper</b> - the muscle damper add while the puppet is Dead.
<BR><b>maxFreezeSqrVelocity</b> - the max square velocity of the ragdoll bones for freezing the puppet.
<BR><b>freezePermanently</b> - if true, PuppetMaster, all it's behaviours and the ragdoll will be destroyed when the puppet is frozen.
<BR><b>enableAngularLimitsOnKill</b> - if true, will enable angular limits when killing the puppet.
<BR><b>enableInternalCollisionsOnKill</b> - if true, will enable internal collisions when killing the puppet.
- <b>mode</b> - Active mode means all muscles are active and the character is physically simulated. Kinematic mode sets rigidbody.isKinematic to true for all the muscles and simply updates their position/rotation to match the target's. Disabled mode disables the ragdoll. Switching modes is done by simply changing this value, blending in/out will be handled automatically by the PuppetMaster.
- <b>blendTime</b> - the time of blending when switching from Active to Kinematic/Disabled or from Kinematic/Disabled to Active. Switching from Kinematic to Disabled or vice versa will be done instantly.
- <b>fixTargetTransforms</b> - if true, will fix the target character's Transforms to their default local positions and rotations in each update cycle to avoid drifting from additive reading-writing. Use this only if the target contains unanimated bones.
- <b>solverIterationCount</b> - Rigidbody.solverIterationCount for the muscles of this Puppet.
- <b>visualizeTargetPose</b> - if true, will draw the target's pose as green lines in the Scene view. This runs in the Editor only. If you wish to profile PuppetMaster, switch this off.
<b>Master Weights</b>
- <b>mappingWeight</b> - the weight of mapping the animated character to the ragdoll pose.
- <b>pinWeight</b> - the weight of pinning the muscles to the position of their animated targets using simple AddForce.
- <b>muscleWeight</b> - the normalized strength of the muscles.
<b>Joint and Muscle Settings</b>
- <b>muscleSpring</b> - the positionSpring of the ConfigurableJoints' Slerp Drive.
- <b>muscleDamper</b> - the positionDamper of the ConfigurableJoints' Slerp Drive.
- <b>pinPow</b> - adjusts the slope of the pinWeight curve. Has effect only while interpolating pinWeight from 0 to 1 and back.
- <b>pinDistanceFalloff</b> - reduces pinning force the farther away the target is. Bigger value loosens the pinning, resulting in sloppier behaviour.
- <b>updateJointAnchors</b> - when the target has animated bones between the muscle bones, the joint anchors need to be updated in every update cycle because the muscles' targets move relative to each other in position space. This gives much more accurate results, but is computationally expensive so consider leaving it off.
- <b>supportTranslationAnimation</b> - enable this if any of the target's bones has translation animation.
- <b>angularLimits</b> - should the joints use angular limits? If the PuppetMaster fails to match the target's pose, it might be because the joint limits are too stiff and do not allow for such motion. Uncheck this to see if the limits are clamping the range of your puppet's animation. Since the joints are actuated, most PuppetMaster simulations will not actually require using joint limits at all.
- <b>internalCollisions</b> - should the muscles collide with each other? Consider leaving this off while the puppet is pinned for performance and better accuracy. Since the joints are actuated, most PuppetMaster simulations will not actually require internal collisions at all.
<b>Individual Muscle Settings:</b>
- <b>joint</b> - the ConfigurableJoint used by this muscle.
- <b>target</b> - the target Transform that this muscle tries to follow.
- <b>props</b> - the main properties of the muscle.
<BR><b>group</b> - which body part does this muscle belong to? This might be used by some behaviours (BehaviourPuppet).
<BR><b>mappingWeight</b> - the weight (multiplier) of mapping this muscle's target to the muscle.
<BR><b>pinWeight</b> - the weight (multiplier) of pinning this muscle to it's target's position using a simple AddForce command.
<BR><b>muscleWeight</b> - the muscle strength (multiplier).
<BR><b>muscleDamper</b> - multiplier of the positionDamper of the ConfigurableJoints' Slerp Drive.
<BR><b>mapPosition</b> - if true, will map the target to the world space position of the muscle. Normally this should be true for only the root muscle (the hips).
\image html PuppetMaster.png
*/
/*! \page page6 Props
PuppetMaster includes a helpful tool for attaching, detatching and managing physical props - the <b>PropMuscle</b> and <b>PuppetMasterProp</b> classes.
PropMuscle is a special type of muscle that the PuppetMasterProp objects can be attached to.
For an example of prop usage, please see the "Prop" and "Melee" demo scenes.
<b>Getting Started:</b>
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/Bkw1gmrDr1I" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>Prop Setup:</b>
Because of the dual rig structure, the prop needs to be set up so that it's root GameObject is the Muscle with the Rigidbody and ConfigurableJoint components and parented to it the Target along with it's mesh and renderer(s).
When the prop is picked up, the prop will be split up so that the "Mesh Root" will be parented to the Target root hierarchy and the rest of the prop with colliders to the Prop Muscle. When the prop is dropped, original hierarchy will be restored.
When the prop is picked up, the Rigidbody component on it will be destroyed as the PropMuscle already has a Rigidbody. The colliders of the prop will act as compound colliders for the PropMuscle Rigidbody. When the prop is dropped, the original Rigidbody will be restored.
\image html Prop.png
\image html PropScene.png
<br>
<b>PropMuscle component:</b>
PropMuscle is a special type of muscle, which all prop objects can be attached to. You can create a PropMuscle in the Editor by selecting the PuppetMaster GameObject and clicking on "Add Prop Muscle" on the bottom of the PuppetMaster component.
Click on the blue button in the scene representing the PropMuscle and move/rotate it to where you need it to be.
If your puppet does not have hand muscles and the PropMuscle was attached to the forearm muscle, find the Prop Muscle Target GameObject in the Target Root hierarchy and parent it to the hand bone.
- <b>Remove This Prop Muscle</b> - destroy this PropMuscle object.
- <b>currentProp</b> - the PuppetMasterProp currently held by this Prop Muscle. To pick up a prop, just assign it as propMuscle.currentProp. To drop, set propMuscle.currentProp to null. Replacing this value with another prop drops any previously held props.
- <b>additionalPinOffset</b> - offset of the additional pin from this Prop Muscle in local space.
- <b>Add/Remove Additional Pin</b> - adds or removes the additional pin object. Additional Pins help to pin this prop muscle to animation from another point. Without it, the prop muscle would be actuated by Muscle Spring only, which is likely not enough to follow fast swinging animations. Move the additional pin by 'Additional Pin Offset' towards the end of the prop (tip of the sword).
\image html PropMuscle.png
Picking up, dropping and switching props with the PropMuscle is done by simply changing the propMuscle.currentProp value. When you assign a prop to it by propMuscle.currentProp = myProp, any props held by the PropMuscle will be dropped and the new myProp will be attached instead.
If you set currentProp to null, any props held by the PropMuscle will be dropped and the PropMuscle itself deactivated.
\code
// Dropping props
propMuscle.currentProp = null;
// Dropping any props held, picking up myProp
propMuscle.currentProp = myProp;
\endcode
When a prop is attached to the PropMuscle, it's localPosition and localRotation are set to zero/identity, so the best practice to adjust prop holding pivot would be to parent the prop to the PropMuscle, set localPosition/Rotation to zero and adjust the positions of the mesh and colliders until they fit perfectly at hand.
<br>
<b>PuppetMasterProp component:</b>
- <b>meshRoot</b> - Mesh Root will be parented to Prop Muscle's target when this prop is picked up. To make sure the mesh and the colliders match up, Mesh Root's localPosition/Rotation must be zero.
- <b>muscleProps</b> - the muscle properties that will be applied to the Prop Muscle when this prop is picked up.
- <b>internalCollisionIgnores</b> - defines which muscles or muscle groups internal collisions will always be ignored with regardless of PuppetMaster.internalCollisions state.
- <b>animatedTargetChildren</b> - list of animated bones parented to this muscle's Target, except for the bones that are targets or target children of any child muscles. This is used for stopping animation on those bones when the muscle has been disconnected using PuppetMaster.DisconnectMuscleRecursive(). For example if you disconnected the spine02 muscle, you would want to have spine03 and clavicles in this list to stop them from animating.
- <b>forceLayers</b> - if true, this prop's layer will be forced to PuppetMaster layer and target's layer forced to PuppetMaster's Target Root's layer when the prop is picked up.
- <b>mass</b> - mass of the prop while picked up. When dropped, mass of the original Rigidbody will be used.
- <b>propType</b> - this has no other purpose but helping you distinguish props by PropRoot.currentProp.propType.
- <b>pickedUpMaterial</b> - if assigned, sets prop colliders to this PhysicMaterial when picked up. If no materials assigned here, will maintain the original PhysicMaterial.
- <b>additionalPinOffsetAdd</b> - adds this to Prop Muscle's 'Additional Pin Offset' when this prop is picked up.
- <b>additionalPinWeight</b> - the pin weight of the additional pin. Increasing this weight will make the prop follow animation better, but will increase jitter when colliding with objects.
- <b>additionalPinMass</b> - multiplies the mass of the additional pin by this value when this prop is picked up. The Rigidbody on this prop will be destroyed on pick-up and reattached on drop, so it's mass is not used while picked up.
\image html PuppetMasterProp.png
<br>
<b>Melee Props:</b>
Lengthy melee props are a huge challenge to the PuppetMaster. Swinging them rapidly requires a lot of muscle force and solver iterations to fight the inertia and keep the ragdoll chain intact.
The longer the chain of Joints linked together, the more inaccurate/unstable the simulation and unfortunatelly those melee props tend to be exactly at the ends of very long Joint chains (pelvis/spine/chest/upper arm/forearm/hand/sword).
Besides that, as the props are swinged, they have a lot of linear and angular velocity, a very thin collider and therefore can easily skip the victim when it's collider happens to be at the position between two fixed frames.
It usually takes quite a lot of tweaking and some tricks to get the melee props working right. PropMuscles have the "Additional Pin" functionality which can be used to add another pinning point to the prop, helping to better pin it to high angular velocity animation.
- make the collider thicker when hitting to decrease collider skipping.
- use Continuous/Continuous Dynamic collision detection modes to reduce skipping, this however has a big performance cost.
- reduce the fixed timestep.
- use the "Additional Pin" (Prop.cs).
- adjust the position of the "Additional Pin" and "Additional Pin Target" along the prop.
- reduce PuppetMaster.pinDistanceFalloff.
- increase PuppetMaster.muscleSpring and solverIterationCount.
- disable PuppetMaster.internalCollisions to prevent the big prop collider from colliding with the Puppet.
- get rid of the hand Muscle to make the joint chain shorter.
<b>PropMelee Component:</b> (this component will be made more generic in PuppetMaster 0.4).
- <b>capsuleCollider</b> - switches the collider to a Capsule when the prop is picked up. Capsules collide more smoothly and with less jitter.
- <b>boxCollider</b> - switches back to this BoxCollider when dropped.
- <b>actionColliderRadiusMlp</b> - multiplies the radius of the Capsule when PropMelee.StartAction(float duration) is called.
- <b>actionAdditionalPinWeight</b> - temporarily set (increase) the pin weight of the additional pin when PropMelee.StartAction(float duration) is called.
- <b>actionMassMlp</b> - temporarily increase the mass of the Rigidbody when PropMelee.StartAction(float duration) is called.
- <b>COMOffset</b> - offset to the default center of mass of the Rigidbody (might improve prop handling).
\image html PuppetMasterPropMelee.png
*/
/*! \page page7 Inverse Kinematics
PuppetMaster can be used together with Unity's own built-in Animator IK as well as Final IK.
The former is limited to Humanoids only and can be used to alter the target pose programmatically before the PuppetMaster reads it for following.
Final IK opens up much more possibilities such as modifying the pose with full body IK or applying an IK pass on top of the physical simulation for cosmetic corrections or accurate aiming.
<b>Final IK:</b>
To use PuppetMaster with Final IK, import both packages to the project, then import also "Plugins/RootMotion/PuppetMaster/_Integration/Final-IK.unitypackage".
The package comes with scenes and scripts demonstrating the application of IK both before and after PuppetMaster solves.
<b>IK Before Physics:</b>
We might be interested in using IK to change the Target pose for various reasons, for example keeping balance, aiming, grabbing, protecting from incoming collisions or even procedural locomotion.
When using Unity's built-in IK solution, it will be automatically applied on top of the animation in the Mecanim update cycle.
The components of Final IK will also update by default before PuppetMaster reads.
If you need them to be updated in a specific order, you can use the IKBeforePhysics.cs component
or disable them and update their solvers manually using the PuppetMaster.OnRead delegate:
\code
public PuppetMaster puppetMaster;
public IK[] IKComponents;
void Start() {
// Register to get a call from PuppetMaster
puppetMaster.OnRead += OnRead;
// Take control of updating IK solvers
foreach (IK ik in IKComponents) ik.enabled = false;
}
void OnRead() {
if (!enabled) return;
// Solve IK before PuppetMaster reads the pose of the character
foreach (IK ik in IKComponents) ik.GetIKSolver().Update();
}
// Cleaning up the delegates
void OnDestroy() {
if (puppetMaster != null) {
puppetMaster.OnRead -= OnRead;
}
}
\endcode
<b>IK After Physics:</b>
Each frame PuppetMaster is done solving and mapping the Target character to the ragdoll, we have a chance to make minor adjustments (that don't change the physics anymore) to the character pose.
This can be useful for example when making sure hands are perfectly fixed to some points or doing aiming correction with AimIK.
Unity's built-in IK can not be applied after PuppetMaster has mapped the Target character to the ragdoll pose.
Final IK components can be updated whenever necessary and in this case we need to do it in the PuppetMaster.OnWrite delegate:
\code
public PuppetMaster puppetMaster;
public IK[] IKComponents;
void Start() {
// Register to get some calls from PuppetMaster
puppetMaster.OnWrite += OnWrite;
// Take control of updating IK solvers
foreach (IK ik in IKComponents) ik.enabled = false;
}
// PuppetMaster calls this when it is done mapping the animated character to the ragdoll so if we can apply our kinematic adjustments to it now
void OnWrite() {
if (!enabled) return;
// Solve IK after PuppetMaster writes the solved pose on the animated character.
foreach (IK ik in IKComponents) ik.GetIKSolver().Update();
}
// Cleaning up the delegates
void OnDestroy() {
if (puppetMaster != null) {
puppetMaster.OnWrite -= OnWrite;
}
}
\endcode
*/
/*! \page page8 Performance
* @todo Description of optimization techniques, PuppetMasterSettings.cs.
<b>Tips for improving the performance</b>
<br>
- Decrease PuppetMaster "Solver Iteration Count" (changes Rigidbody.solverIterationCount for all the muscles) to the minimum that you can work with. Less solver iterations makes the muscles weaker so you might have to increase PuppetMaster "Muscle Spring".
- "Fix Target Transforms" should be switched off when your character is animated at all times.
- "Visualize Target Pose" costs some performance in the Editor, but not in the built game.
- Leaving "Update Joint Anchors" off improves performance with the cost of simulation accuracy.
- "Angular Limits" and "Internal Collisions" reduce the workload on the physics engine when disabled.
- When using BehaviourPuppet, increase PuppetMaster "Collision Threshold". It determines how strong the collisions must be in order to be processed by the BehaviourPuppet, however, increasing the value will make the puppet's behaviour jerkier on collision.
- Reduce the number of muscles. Do you absolutely need 3 spine muscles or the feet or hand muscles?
- Reducing "Default Contact Offset" in the Physics settings reduces expensive OnCollisionStay broadcasts when using BehaviourPuppet.
- Increase the "Fixed Timestep" in Project Settings/Time to the maximum tolerable value.
- Keep your puppets away from each other. Less collisions means much less work for both the Physics engine and the PuppetMaster.
- Set PuppetMaster mode to "Disabled" for puppets when they don't need any physics simulation.
- Set PuppetMaster mode to "Kinematic" for puppets that only need the colliders for collision detection or raycasting.
- When you do not need to use any Puppet Behaviours nor get a call in case of collisions, comment out the OnCollisionEnter/Stay/Exit functions in MuscleCollisionBroadcaster.cs.
- PuppetMaster can also run a flat hierarchy ragdoll. Just right-click on the PuppetMaster header and select "Flatten Muscle Hierarchy" from the context menu.
* */
/*! \page page9 Behaviours
The Puppet Behaviours are classes that inherit from the abstract BehaviourBase.cs and that's main idea is to provide a pattern for developing functionalities that dynamically adjust muscle and pin weights, strength and other properties or make kinematic adjustments to the target pose.
The most important Puppet Behaviour is the BehaviourPuppet.cs that handles the pinning of Puppets to target animation, releasing those pins in case of collision and re-tightening them when getting up from the ground.
The Puppet Behaviours can be switched, for example when the BehaviourPuppet looses balance, it can theoretically switch to BehaviourCatchFall or BehaviourWindmill (both missing from the initial release, but will be developed in the future).
The Puppet Behaviours are designed so tha they would not contain a single external object reference. That means they can be simply duplicated and moved to another Puppet.
\image html Behaviours2.png
<b>Switching Behaviours:</b>
When working with multiple Behaviours, keep only the one that is supposed to run first enabled in the Editor.
For example when you have the BehaviourPuppet and BehaviourFall, keep the former enabled and the latter disabled if you wish for the Puppet to start from normal animated state, not falling.
Switching between behaviours by code must be done by calling <b>BehaviourBase.Activate();</b> on the Behaviour you wish to switch to. All other Behaviours will be disabled.
<b>Events</b>
Behaviours trigger events on certain occasions (such as losing balance). They can be used to get a message through to your own scripts or switching behaviours.
- <b>switchToBehaviour</b> - another Puppet Behaviour to switch to on this event. This must be the exact Type of the the Behaviour, careful with spelling.
- <b>animations</b> - animations to cross-fade to on this event. This is separate from the UnityEvent below because UnityEvents can't handle calls with more than one parameter such as Animator.CrossFade.
- <b>unityEvent</b> - the UnityEvent to invoke on this event.
\image html PuppetEvent.png
<b>Sub-Behaviours:</b>
Sub-behaviours are reusable self-contained chunks of functionaly that can be easily shared between multiple Puppet Behaviours.
For example SubBehaviourCOM is a module that automatically calculates and updates center of mass related information for the Puppet - data such as center or pressure, direction and angle of the COM vector and detect if the Puppet is grounded or not.
This prevents the necessity to duplicate code for all the Behaviours that need to make COM calculations.
To see how to use a sub-behaviour like that, take a look at the section below and the BehaviourTemplate.cs class.
<b>Creating Custom Behaviours:</b>
PuppetMaster has been built from start up with customization and extendibility in mind.
To create reusable behaviours of your own, make a class that extends the BehaviourBase abstract class or just make a copy or BehaviourTemplate.cs
and start adding functionality following the pattern at hand.
*/
/*! \page page10 BehaviourPuppet
The BehaviourPuppet handles pinning and unpinning puppets when they collide with objects or are hit via code, also automates getting up from an unbalanced state.
\image html Puppet.gif
<b>Getting Started</b>
- Copy the entire gameobject of the BehaviourPuppet from the demo character in "Melee" scene to your own Puppet (parent to the Behaviours root).
- Collision resistance depends on many things, also the mass of your Rigidbodies, if the Puppet is too easy or difficult to unbalance, tweak the "Collision Resistance" value first.
<b>Troubleshooting</b>
- <b>The Puppet never falls over, has "snake feet"</b> - decrease "Collision Resistance".
- <b>The Puppet loses balance on slightest contact</b> - increase "Collision Resistance" and/or "Regain Pin Speed". Increase "Knock Out Distance".
- <b>The Puppet tries to get up, but repeatedly fails</b> - increase "Get Up Collision Resistance" and/or "Get Up Regain Pin Speed Mlp" and/or "Get Up Knock Out Distance".
- <b>The Puppet's muscles are too stiff when unbalanced</b> - decrease "Unpinned Muscle Weight Mlp".
- <b>The Puppet doesn't lose balance when hit hard to the legs</b> - find the group override for the "Hips" and "Leg" and the "Foot" group. Increasing "Unping Parents", "Unpin Children" and "Unpin Group" makes the collisions propagate more heavily to the other body parts. Also try decreasing "Knock Out Distance".
<b>Collision And Recovery</b>
- <b>normalMode</b> - how does the puppet behave when currently not in contact with anything? Active mode keeps the PuppetMaster Active and mapped at all times. Unmapped blends out mapping to maintain 100% animation quality. Kenamatic keeps the PuppetMaster in Kinematic mode until there is a collision.
- <b>mappingBlendSpeed</b> - the speed of blending in mapping in case of contact when in Unmapped normal mode.
- <b>activateOnStaticCollisions</b> - if false, static colliders will not activate the puppet when they collide with the muscles. Note that the static colliders need to have a kinematic Rigidbody attached for this to work. Used only in Kinematic normal mode.
- <b>activateOnImpulse</b> - minimum collision impulse for activating the puppet. Used only in Kinematic normal mode.
- <b>groundLayers</b> - the layers that the character controller will be grounded to when unpinned or getting up.
- <b>collisionLayers</b> - the layers that will unpin the Puppet on collision.
- <b>collisionThreshold</b> - an optimization. The minimum square magnitude of the impulse that will be processed.
- <b>collisionResistance</b> - smaller value means more unpinning from collisions so the characters get knocked out more easily. If using a curve, the value will be evaluated by each muscle's target velocity magnitude. This can be used to make collision resistance higher while the character moves or animates faster.
- <b>collisionResistanceMultipliers</b> - used for multiplying the value of collision resistance based on the layer that collided with the Puppet.
- <b>maxCollisions</b> - and optimization. The maximum number of collisions that will be processed per physics step. Helps to avoid peaks.
- <b>regainPinSpeed</b> - how fast will the muscles of this group regain their pin weight?
- <b>muscleRelativeToPinWeight</b> - Muscle weight multiplier relative to pin weight. It can be used to make muscles weaker/stronger when they are more/less unpinned while in the normal Puppet state.
- <b>boostFalloff</b> - Boosting is a term used for making muscles temporarily immune to collisions and/or deal more damage to the muscles of other characters. That is done by increasing Muscle.State.immunity and Muscle.State.impulseMlp. For example when you set muscle.state.immunity to 1, boostFalloff will determine how fast this value will fall back to normal (0). Use BehaviourPuppet.BoostImmunity() and BehaviourPuppet.BoostImpulseMlp() for boosting from your own scripts. It is helpful for making the puppet stronger and deliever more punch while playing a melee hitting/kicking animation.
<b>Muscle Group Properties</b>
- <b>defaults</b> - the default muscle properties. If there are no 'Group Overrides', this will be used for all muscles.
<BR><b>unpinParents</b> - how much will collisions with muscles of this group unpin parent muscles?
<BR><b>unpinChildren</b> - how much will collisions with muscles of this group unpin child muscles?
<BR><b>unpinGroup</b> - how much will collisions with muscles of this group unpin muscles of the same group?
<BR><b>minMappingWeight</b> - if 1, muscles of this group will always be mapped to the ragdoll.
<BR><b>maxMappingWeight</b> - if 0, muscles of this group will not be mapped to the ragdoll pose even if they are unpinned.
<BR><b>disableColliders</b> - if true, muscles of this group will have their colliders disabled while in puppet state (not unbalanced nor getting up).
<BR><b>regainPinSpeed</b> - how fast will muscles of this group regain their pin weight (multiplier)?
<BR><b>collisionResistance</b> - smaller value means more unpinning from collisions (multiplier).
<BR><b>knockOutDistance</b> - if the distance from the muscle to it's target is larger than this value, the character will be knocked out.
<BR><b>puppetMaterial</b> - the PhysicsMaterial applied to the muscles while the character is in Puppet or GetUp state. Using a lower friction material reduces the risk of muscles getting stuck and pulled out of their joints.
<BR><b>unpinnedMaterial</b> - the PhysicsMaterial applied to the muscles while the character is in Unpinned state.
- <b>groupOverrides</b> - overriding default muscle properties for some muscle groups (for example making the feet stiffer or the hands looser).
<b>Losing Balance</b>
- <b>knockOutDistance</b> - if the distance from the muscle to it's target is larger than this value, the character will be knocked out.
- <b>unpinnedMuscleWeightMlp</b> - smaller value makes the muscles weaker when the puppet is knocked out.
- <b>dropProps</b> - if true, all muscles of the 'Prop' group will be detached from the puppet when it loses balance.
<b>Getting Up</b>
- <b>canGetUp</b> - if true, GetUp state will be triggerred automatically after 'Get Up Delay' and when the velocity of the hip muscle is less than 'Max Get Up Velocity'.
- <b>getUpDelay</b> - minimum delay for getting up after loosing balance. After that time has passed, will wait for the velocity of the hip muscle to come down below 'Max Get Up Velocity' and then switch to the GetUp state.
- <b>blendToAnimationTime</b> - the duration of blending the animation target from the ragdoll pose to the getting up animation once the GetUp state has been triggered.
- <b>maxGetUpVelocity</b> - will not get up before the velocity of the hip muscle has come down to this value.
- <b>minGetUpDuration</b> - will not get up before this amount of time has passed since loosing balance.
- <b>getUpCollisionResistanceMlp</b> - collision resistance multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.
- <b>getUpRegainPinSpeedMlp</b> - regain pin weight speed multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.
- <b>getUpKnockOutDistanceMlp</b> - knock out distance multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.
- <b>getUpOffsetProne</b> - offset of the target character (in character rotation space) from the hip bone when initiating getting up animation from a prone pose. Tweak this value if your character slides a bit when starting to get up.
- <b>getUpOffsetSupine</b> - offset of the target character (in character rotation space) from the hip bone when initiating getting up animation from a supine pose. Tweak this value if your character slides a bit when starting to get up.
<b>Events</b>
- <b>onGetUpProne</b> - called when the character starts getting up from a prone pose (facing down).
- <b>onGetUpSupine</b> - called when the character starts getting up from a supine pose (facing up).
- <b>onLoseBalance</b> - called when the character is knocked out (loses balance). Doesn't matter from which state.
- <b>onLoseBalanceFromPuppet</b> - called when the character is knocked out (loses balance) only from the normal Puppet state.
- <b>onLoseBalanceFromGetUp</b> - called when the character is knocked out (loses balance) only from the GetUp state.
- <b>onRegainBalance</b> - called when the character has fully recovered and switched to the Puppet state.
\image html BehaviourPuppet.png
* */
/*! \page page11 BehaviourFall
BehaviourFall simply blends between two animation clips in a blend tree depending on the height of the ragdoll from the ground.
As seen from the gif below, when the ragdoll is high above the ground surface, a writhering animation is played, but when it falls down, a protective pose is blended in.
\image html Falling.gif
BehaviourFall requires for the Animator of the character to have a blend tree set up like in the image below.
You can copy the blend tree from the AnimatorController in the "Falling" demo scene.
\image html BehaviourFallAnimator.png
<b>Component Variables</b>
- <b>stateName</b> - Animation State to crossfade to when this behaviour is activated.
- <b>transitionDuration</b> - the duration of crossfading to stateName. Value is in seconds.
- <b>layer</b> - layer index containing the destination state. If no layer is specified or layer is -1, the first state that is found with the given name or hash will be played.
- <b>fixedTime</b> - start time of the current destination state. Value is in seconds. If no explicit fixedTime is specified or fixedTime value is float.NegativeInfinity, the state will either be played from the start if it's not already playing, or will continue playing from its current time and no transition will happen.
- <b>raycastLayers</b> - the layers that will be raycasted against to find colliding objects.
- <b>blendParameter</b> - the parameter in the Animator that blends between catch fall and writhe animations.
- <b>writheHeight</b> - the height of the pelvis from the ground at which will blend to writhe animation.
- <b>writheYVelocity</b> - the vertical velocity of the pelvis at which will blend to writhe animation.
- <b>blendSpeed</b> - the speed of blendig between the two falling animations.
- <b>canEnd</b> - if false, this behaviour will never end.
- <b>minTime</b> - the minimum time since this behaviour activated before it can end.
- <b>maxEndVelocity</b> - if the velocity of the pelvis falls below this value, can end the behaviour.
- <b>onEnd</b> - event triggered when all end conditions are met.
\image html BehaviourFall.png
* */
/*! \page page12 Baker
Baker is a universal tool for recording Humanoid, Generic and Legacy animation clips. Baker.cs is an abstract base class extended by HumanoidBaker.cs and GenericBaker.cs.
<BR>
<b>Baker allows you to:</b>
- Edit animation clips
- bake IK into animation
- combine animation layers
- bake InteractionSystem interactions
- bake ragdoll physics
- blend ragdoll physics with animation (PuppetMaster)
- bake Timeline
- fix Humanoid retargeting problems (hand, foot positions)
- bake outsourced Humanoid animation to specific character model to avoid using Foot IK for performance
- bake motion capture
- reduce animation memory footprint with Baker's advanced keyframe reduction tools
<b>Getting started:</b>
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/uakZqX1hju0" frameborder="0" allowfullscreen></iframe>\endhtmlonly
- Add the HumanoidBaker or GenericBaker component to the same GameObject as your character's Animator.
- Click on the button beneath "Save To Folder" to choose a folder for the baked animation clips.
- Play the scene.
- Click on the bake button.
<b>Animation Clips Mode</b>
<BR>AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController.
<BR>Set the Baker to "Animation Clips" mode and add some animation clips to the "Animation Clips" array. "Append Name" is a string that will be added to each clip's name for the saved clip. For example if your animation clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
<b>Animation States Mode</b>
<BR>AnimationStates mode can be used to bake a batch of Mecanim Animation States. This is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim.
<BR>Set the Baker to "Animation States" mode and add the Animation State names (only from the base layer) you wish to bake to the "Animation States" array. "Append Name" is a string that will be added to each state's name for the saved clip. For example if your animation state names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
<b>Playable Director Mode</b>
<BR>Bakes a PlayableDirector with a Timeline asset. Set the Baker to "Playable Director" mode and make sure the GameObject has a valid PlayableDirector.
<b>Realtime Mode</b>
<BR>Useful for baking an arbitrary range of animation, such as ragdoll simulation or an InteractionSystem interaction, in real-time.
\code
using RootMotion;
public class MyBakingTool {
public Baker baker;
public float bakeDuration = 5f;
void Start()
{
baker.mode = Baker.Mode.Realtime;
StartCoroutine(BakeDuration(bakeDuration));
}
private IEnumerator BakeDuration(float duration)
{
baker.StartBaking();
yield return new WaitForSeconds(duration);
baker.StopBaking();
}
}
\endcode
<b>Keyframe Reduction</b>
<BR> While developing a mobile game and running low on RAM, the quality of your animation will suffer a lot should you try to increase the keyframe reduction error thresholds in animation import settings.
The most noticable problem will be with the feet starting to float around in idle animations as there are not enough keyframes to make them appear properly planted. Idle animations are also usually the longest and most memory consuming.
Unity actually already contains a solution for this problem, but it is simply not implemented in the keyframe reduction options. That solution is the humanoid "Foot IK" system ("Foot IK" toggle in the Animator, previewable by enabling the "IK" toggle in the Animation Preview Window), that is normally used for fixing Humanoid retargeting problems.
Foot IK works by storing position and rotation channels of the foot bottoms from the original animation clip, then running a pass of IK on the legs of the retargeted character (that has different leg bone lenghts) to properly plant the feet.
Unity keyfame reduction options do not allow you to define different parameters for those IK curves and so they will be reduced just the same as the muscle channels, causing the feet to float even if you had "Foot IK" enabled.
Baker allows you define "Key Reduction Error" and "IK Key Reduction Error" separately, hence apply extreme key reduction to muscle channels that take most of the memory while maintaining normal reduction for the IK channels.
It also allows you to bake muscle channels at a lower frame rate than the IK channels by increasing the value of "Muscle Frame Rate Div". Those options can help you achieve better animation quality for a memory cost that is multiple times lower.
The same technique can be used for hand IK, making sure your 2-handed prop animations do not suffer from keyframe reduction.
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/sH7OnpOQCg8" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>Changing AnimationClipSettings</b>
<BR> When you first bake an animation clip, Baker will apply the default settings. If you modified the settings of the animation clip manually and baked again, Baker will maintain those modified settings so you will not have to apply them again.
<b>HumanoidBaker variables</b>
- <b>frameRate</b> - in AnimationClips, AnimationStates or PlayableDirector mode - the frame rate at which the animation clip will be sampled. In Realtime mode - the frame rate at which the pose will be sampled. With the latter, the frame rate is not guaranteed if the player is not able to reach it.
- <b>keyReductionError</b> - maximum allowed error for keyframe reduction.
- <b>IKKeyReductionError</b> - max keyframe reduction error for the Root.Q/T, LeftFoot IK and RightFoot IK channels. Having a larger error value for 'Key Reduction Error' and a smaller one for this enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.
- <b>muscleFrameRateDiv</b> - frame rate divider for the muscle curves. If you had 'Frame Rate' set to 30, and this value set to 3, the muscle curves will be baked at 10 fps. Only the Root Q/T and Hand and Foot IK curves will be baked at 30. This enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.
- <b>bakeHandIK</b> - should the hand IK curves be added to the animation? Disable this if the original hand positions are not important when using the clip on another character via Humanoid retargeting.
- <b>mode</b> - AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController. AnimationStates mode is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim. PlayableDirector mode bakes a Timeline. Realtime mode is for continuous baking of gameplay, ragdoll phsysics or PuppetMaster dynamics.
- <b>loop</b> - sets the baked animation clip to loop time and matches the last frame keys with the first. Note that when overwriting a previously baked clip, AnimationClipSettings will be copied from the existing clip.
- <b>animationClips</b> - AnimationClips to bake.
- <b>animationStates</b> - the name of the AnimationStates (must be on the base layer) to bake in the Animator (Right-click on this component header and select 'Find Animation States' to have Baker fill those in automatically, required that state names match with the names of the clips used in them).
- <b>appendName</b> - string that will be added to each clip or animation state name for the saved clip. For example if your animation state/clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
- <b>saveToFolder</b> - the folder to save the baked AnimationClips to.
\image html HumanoidBakerComponent.png
<b>GenericBaker variables</b>
- <b>frameRate</b> - in AnimationClips, AnimationStates or PlayableDirector mode - the frame rate at which the animation clip will be sampled. In Realtime mode - the frame rate at which the pose will be sampled. With the latter, the frame rate is not guaranteed if the player is not able to reach it.
- <b>keyReductionError</b> - maximum allowed error for keyframe reduction.
- <b>markAsLegacy</b> - if true, produced AnimationClips will be marked as Legacy and usable with the Legacy animation system.
- <b>root</b> - root Transform of the hierarchy to bake.
- <b>rootNode</b> - root node used for root motion.
- <b>ignoreList</b> - list of Transforms to ignore, rotation curves will not be baked for these Transforms.
- <b>bakePositionList</b> - localPosition curves will be baked for these Transforms only. If you are baking a character, the pelvis bone should be added to this array.
- <b>mode</b> - AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController. AnimationStates mode is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim. PlayableDirector mode bakes a Timeline. Realtime mode is for continuous baking of gameplay, ragdoll phsysics or PuppetMaster dynamics.
- <b>loop</b> - sets the baked animation clip to loop time and matches the last frame keys with the first. Note that if you are overwriting a previously baked clip, AnimationClipSettings will be copied from the existing clip.
- <b>animationClips</b> - AnimationClips to bake.
- <b>animationStates</b> - the name of the AnimationStates (must be on the base layer) to bake in the Animator (Right-click on this component header and select 'Find Animation States' to have Baker fill those in automatically, required that state names match with the names of the clips used in them).
- <b>appendName</b> - string that will be added to each clip or animation state name for the saved clip. For example if your animation state/clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
- <b>saveToFolder</b> - the folder to save the baked AnimationClips to.
\image html GenericBakerComponent.png
<b>Script References:</b>
- <a href="http://www.root-motion.com/finalikdox/html/class_root_motion_1_1_humanoid_baker.html">HumanoidBaker</a>
- <a href="http://www.root-motion.com/finalikdox/html/class_root_motion_1_1_generic_baker.html">GenericBaker</a>
*/
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 7dd9c3221309c480d990fa8a4cb04dc9
timeCreated: 1443523392
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: bb15b348b0d61a14f83b5ae527112c60
folderAsset: yes
timeCreated: 1444732416
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

@@ -0,0 +1,57 @@
fileFormatVersion: 2
guid: 5f77f33a83efd35429c7eb5dc9474f43
timeCreated: 1444738226
licenseType: Store
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 0
linearTexture: 0
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 8
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: 4
maxTextureSize: 128
textureSettings:
filterMode: -1
aniso: 16
mipBias: -1
wrapMode: 1
nPOTScale: 1
lightmap: 0
rGBM: 0
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 1
textureType: 5
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Some files were not shown because too many files have changed in this diff Show More