CinemachineStateDrivenCameraEditor.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. #if !UNITY_2019_3_OR_NEWER
  2. #define CINEMACHINE_UNITY_ANIMATION
  3. #endif
  4. using System.Collections.Generic;
  5. using UnityEditor;
  6. using UnityEngine;
  7. using UnityEditor.Animations;
  8. namespace Cinemachine.Editor
  9. {
  10. #if CINEMACHINE_UNITY_ANIMATION
  11. [CustomEditor(typeof(CinemachineStateDrivenCamera))]
  12. internal sealed class CinemachineStateDrivenCameraEditor
  13. : CinemachineVirtualCameraBaseEditor<CinemachineStateDrivenCamera>
  14. {
  15. EmbeddeAssetEditor<CinemachineBlenderSettings> m_BlendsEditor;
  16. /// <summary>Get the property names to exclude in the inspector.</summary>
  17. /// <param name="excluded">Add the names to this list</param>
  18. protected override void GetExcludedPropertiesInInspector(List<string> excluded)
  19. {
  20. base.GetExcludedPropertiesInInspector(excluded);
  21. excluded.Add(FieldPath(x => x.m_CustomBlends));
  22. excluded.Add(FieldPath(x => x.m_Instructions));
  23. }
  24. private UnityEditorInternal.ReorderableList mChildList;
  25. private UnityEditorInternal.ReorderableList mInstructionList;
  26. protected override void OnEnable()
  27. {
  28. base.OnEnable();
  29. m_BlendsEditor = new EmbeddeAssetEditor<CinemachineBlenderSettings>(
  30. FieldPath(x => x.m_CustomBlends), this);
  31. m_BlendsEditor.OnChanged = (CinemachineBlenderSettings b) =>
  32. {
  33. InspectorUtility.RepaintGameView();
  34. };
  35. m_BlendsEditor.OnCreateEditor = (UnityEditor.Editor ed) =>
  36. {
  37. CinemachineBlenderSettingsEditor editor = ed as CinemachineBlenderSettingsEditor;
  38. if (editor != null)
  39. editor.GetAllVirtualCameras = () => { return Target.ChildCameras; };
  40. };
  41. mChildList = null;
  42. mInstructionList = null;
  43. }
  44. protected override void OnDisable()
  45. {
  46. base.OnDisable();
  47. if (m_BlendsEditor != null)
  48. m_BlendsEditor.OnDisable();
  49. }
  50. public override void OnInspectorGUI()
  51. {
  52. BeginInspector();
  53. if (mInstructionList == null)
  54. SetupInstructionList();
  55. if (mChildList == null)
  56. SetupChildList();
  57. if (Target.m_AnimatedTarget == null)
  58. EditorGUILayout.HelpBox("An Animated Target is required", MessageType.Warning);
  59. // Ordinary properties
  60. DrawHeaderInInspector();
  61. DrawPropertyInInspector(FindProperty(x => x.m_Priority));
  62. DrawTargetsInInspector(FindProperty(x => x.m_Follow), FindProperty(x => x.m_LookAt));
  63. DrawPropertyInInspector(FindProperty(x => x.m_AnimatedTarget));
  64. // Layer index
  65. EditorGUI.BeginChangeCheck();
  66. UpdateTargetStates();
  67. UpdateCameraCandidates();
  68. SerializedProperty layerProp = FindAndExcludeProperty(x => x.m_LayerIndex);
  69. int currentLayer = layerProp.intValue;
  70. int layerSelection = EditorGUILayout.Popup("Layer", currentLayer, mLayerNames);
  71. if (currentLayer != layerSelection)
  72. layerProp.intValue = layerSelection;
  73. if (EditorGUI.EndChangeCheck())
  74. {
  75. serializedObject.ApplyModifiedProperties();
  76. Target.ValidateInstructions();
  77. }
  78. DrawRemainingPropertiesInInspector();
  79. // Blends
  80. m_BlendsEditor.DrawEditorCombo(
  81. "Create New Blender Asset",
  82. Target.gameObject.name + " Blends", "asset", string.Empty,
  83. "Custom Blends", false);
  84. // Instructions
  85. EditorGUI.BeginChangeCheck();
  86. EditorGUILayout.Separator();
  87. mInstructionList.DoLayoutList();
  88. // vcam children
  89. EditorGUILayout.Separator();
  90. mChildList.DoLayoutList();
  91. if (EditorGUI.EndChangeCheck())
  92. {
  93. serializedObject.ApplyModifiedProperties();
  94. Target.ValidateInstructions();
  95. }
  96. // Extensions
  97. DrawExtensionsWidgetInInspector();
  98. }
  99. static AnimatorController GetControllerFromAnimator(Animator animator)
  100. {
  101. if (animator == null)
  102. return null;
  103. var ovr = animator.runtimeAnimatorController as AnimatorOverrideController;
  104. if (ovr)
  105. return ovr.runtimeAnimatorController as AnimatorController;
  106. return animator.runtimeAnimatorController as AnimatorController;
  107. }
  108. private string[] mLayerNames;
  109. private int[] mTargetStates;
  110. private string[] mTargetStateNames;
  111. private Dictionary<int, int> mStateIndexLookup;
  112. private void UpdateTargetStates()
  113. {
  114. // Scrape the Animator Controller for states
  115. AnimatorController ac = GetControllerFromAnimator(Target.m_AnimatedTarget);
  116. StateCollector collector = new StateCollector();
  117. collector.CollectStates(ac, Target.m_LayerIndex);
  118. mTargetStates = collector.mStates.ToArray();
  119. mTargetStateNames = collector.mStateNames.ToArray();
  120. mStateIndexLookup = collector.mStateIndexLookup;
  121. if (ac == null)
  122. mLayerNames = new string[0];
  123. else
  124. {
  125. mLayerNames = new string[ac.layers.Length];
  126. for (int i = 0; i < ac.layers.Length; ++i)
  127. mLayerNames[i] = ac.layers[i].name;
  128. }
  129. // Create the parent map in the target
  130. List<CinemachineStateDrivenCamera.ParentHash> parents
  131. = new List<CinemachineStateDrivenCamera.ParentHash>();
  132. foreach (var i in collector.mStateParentLookup)
  133. parents.Add(new CinemachineStateDrivenCamera.ParentHash(i.Key, i.Value));
  134. Target.m_ParentHash = parents.ToArray();
  135. }
  136. class StateCollector
  137. {
  138. public List<int> mStates;
  139. public List<string> mStateNames;
  140. public Dictionary<int, int> mStateIndexLookup;
  141. public Dictionary<int, int> mStateParentLookup;
  142. public void CollectStates(AnimatorController ac, int layerIndex)
  143. {
  144. mStates = new List<int>();
  145. mStateNames = new List<string>();
  146. mStateIndexLookup = new Dictionary<int, int>();
  147. mStateParentLookup = new Dictionary<int, int>();
  148. mStateIndexLookup[0] = mStates.Count;
  149. mStateNames.Add("(default)");
  150. mStates.Add(0);
  151. if (ac != null && layerIndex >= 0 && layerIndex < ac.layers.Length)
  152. {
  153. AnimatorStateMachine fsm = ac.layers[layerIndex].stateMachine;
  154. string name = fsm.name;
  155. int hash = Animator.StringToHash(name);
  156. CollectStatesFromFSM(fsm, name + ".", hash, string.Empty);
  157. }
  158. }
  159. void CollectStatesFromFSM(
  160. AnimatorStateMachine fsm, string hashPrefix, int parentHash, string displayPrefix)
  161. {
  162. ChildAnimatorState[] states = fsm.states;
  163. for (int i = 0; i < states.Length; i++)
  164. {
  165. AnimatorState state = states[i].state;
  166. int hash = AddState(Animator.StringToHash(hashPrefix + state.name),
  167. parentHash, displayPrefix + state.name);
  168. // Also process clips as pseudo-states, if more than 1 is present.
  169. // Since they don't have hashes, we can manufacture some.
  170. var clips = CollectClips(state.motion);
  171. if (clips.Count > 1)
  172. {
  173. string substatePrefix = displayPrefix + state.name + ".";
  174. foreach (AnimationClip c in clips)
  175. AddState(
  176. CinemachineStateDrivenCamera.CreateFakeHash(hash, c),
  177. hash, substatePrefix + c.name);
  178. }
  179. }
  180. ChildAnimatorStateMachine[] fsmChildren = fsm.stateMachines;
  181. foreach (var child in fsmChildren)
  182. {
  183. string name = hashPrefix + child.stateMachine.name;
  184. string displayName = displayPrefix + child.stateMachine.name;
  185. int hash = AddState(Animator.StringToHash(name), parentHash, displayName);
  186. CollectStatesFromFSM(child.stateMachine, name + ".", hash, displayName + ".");
  187. }
  188. }
  189. List<AnimationClip> CollectClips(Motion motion)
  190. {
  191. var clips = new List<AnimationClip>();
  192. AnimationClip clip = motion as AnimationClip;
  193. if (clip != null)
  194. clips.Add(clip);
  195. BlendTree tree = motion as BlendTree;
  196. if (tree != null)
  197. {
  198. ChildMotion[] children = tree.children;
  199. foreach (var child in children)
  200. clips.AddRange(CollectClips(child.motion));
  201. }
  202. return clips;
  203. }
  204. int AddState(int hash, int parentHash, string displayName)
  205. {
  206. if (parentHash != 0)
  207. mStateParentLookup[hash] = parentHash;
  208. mStateIndexLookup[hash] = mStates.Count;
  209. mStateNames.Add(displayName);
  210. mStates.Add(hash);
  211. return hash;
  212. }
  213. }
  214. private int GetStateHashIndex(int stateHash)
  215. {
  216. if (stateHash == 0)
  217. return 0;
  218. if (!mStateIndexLookup.ContainsKey(stateHash))
  219. return 0;
  220. return mStateIndexLookup[stateHash];
  221. }
  222. private string[] mCameraCandidates;
  223. private Dictionary<CinemachineVirtualCameraBase, int> mCameraIndexLookup;
  224. private void UpdateCameraCandidates()
  225. {
  226. List<string> vcams = new List<string>();
  227. mCameraIndexLookup = new Dictionary<CinemachineVirtualCameraBase, int>();
  228. vcams.Add("(none)");
  229. CinemachineVirtualCameraBase[] children = Target.ChildCameras;
  230. foreach (var c in children)
  231. {
  232. mCameraIndexLookup[c] = vcams.Count;
  233. vcams.Add(c.Name);
  234. }
  235. mCameraCandidates = vcams.ToArray();
  236. }
  237. private int GetCameraIndex(Object obj)
  238. {
  239. if (obj == null || mCameraIndexLookup == null)
  240. return 0;
  241. CinemachineVirtualCameraBase vcam = obj as CinemachineVirtualCameraBase;
  242. if (vcam == null)
  243. return 0;
  244. if (!mCameraIndexLookup.ContainsKey(vcam))
  245. return 0;
  246. return mCameraIndexLookup[vcam];
  247. }
  248. void SetupInstructionList()
  249. {
  250. mInstructionList = new UnityEditorInternal.ReorderableList(serializedObject,
  251. serializedObject.FindProperty(() => Target.m_Instructions),
  252. true, true, true, true);
  253. // Needed for accessing field names as strings
  254. CinemachineStateDrivenCamera.Instruction def = new CinemachineStateDrivenCamera.Instruction();
  255. float vSpace = 2;
  256. float hSpace = 3;
  257. float floatFieldWidth = EditorGUIUtility.singleLineHeight * 2.5f;
  258. float hBigSpace = EditorGUIUtility.singleLineHeight * 2 / 3;
  259. mInstructionList.drawHeaderCallback = (Rect rect) =>
  260. {
  261. float sharedWidth = rect.width - EditorGUIUtility.singleLineHeight
  262. - 2 * (hBigSpace + floatFieldWidth) - hSpace;
  263. rect.x += EditorGUIUtility.singleLineHeight; rect.width = sharedWidth / 2;
  264. EditorGUI.LabelField(rect, "State");
  265. rect.x += rect.width + hSpace;
  266. EditorGUI.LabelField(rect, "Camera");
  267. rect.x += rect.width + hBigSpace; rect.width = floatFieldWidth;
  268. EditorGUI.LabelField(rect, "Wait");
  269. rect.x += rect.width + hBigSpace;
  270. EditorGUI.LabelField(rect, "Min");
  271. };
  272. mInstructionList.drawElementCallback
  273. = (Rect rect, int index, bool isActive, bool isFocused) =>
  274. {
  275. SerializedProperty instProp
  276. = mInstructionList.serializedProperty.GetArrayElementAtIndex(index);
  277. float sharedWidth = rect.width - 2 * (hBigSpace + floatFieldWidth) - hSpace;
  278. rect.y += vSpace; rect.height = EditorGUIUtility.singleLineHeight;
  279. rect.width = sharedWidth / 2;
  280. SerializedProperty stateSelProp = instProp.FindPropertyRelative(() => def.m_FullHash);
  281. int currentState = GetStateHashIndex(stateSelProp.intValue);
  282. int stateSelection = EditorGUI.Popup(rect, currentState, mTargetStateNames);
  283. if (currentState != stateSelection)
  284. stateSelProp.intValue = mTargetStates[stateSelection];
  285. rect.x += rect.width + hSpace;
  286. SerializedProperty vcamSelProp = instProp.FindPropertyRelative(() => def.m_VirtualCamera);
  287. int currentVcam = GetCameraIndex(vcamSelProp.objectReferenceValue);
  288. int vcamSelection = EditorGUI.Popup(rect, currentVcam, mCameraCandidates);
  289. if (currentVcam != vcamSelection)
  290. vcamSelProp.objectReferenceValue = (vcamSelection == 0)
  291. ? null : Target.ChildCameras[vcamSelection - 1];
  292. float oldWidth = EditorGUIUtility.labelWidth;
  293. EditorGUIUtility.labelWidth = hBigSpace;
  294. rect.x += rect.width; rect.width = floatFieldWidth + hBigSpace;
  295. SerializedProperty activeAfterProp = instProp.FindPropertyRelative(() => def.m_ActivateAfter);
  296. EditorGUI.PropertyField(rect, activeAfterProp, new GUIContent(" ", activeAfterProp.tooltip));
  297. rect.x += rect.width;
  298. SerializedProperty minDurationProp = instProp.FindPropertyRelative(() => def.m_MinDuration);
  299. EditorGUI.PropertyField(rect, minDurationProp, new GUIContent(" ", minDurationProp.tooltip));
  300. EditorGUIUtility.labelWidth = oldWidth;
  301. };
  302. mInstructionList.onAddDropdownCallback = (Rect buttonRect, UnityEditorInternal.ReorderableList l) =>
  303. {
  304. var menu = new GenericMenu();
  305. menu.AddItem(new GUIContent("New State"),
  306. false, (object data) =>
  307. {
  308. ++mInstructionList.serializedProperty.arraySize;
  309. serializedObject.ApplyModifiedProperties();
  310. Target.ValidateInstructions();
  311. },
  312. null);
  313. menu.AddItem(new GUIContent("All Unhandled States"),
  314. false, (object data) =>
  315. {
  316. CinemachineStateDrivenCamera target = Target;
  317. int len = mInstructionList.serializedProperty.arraySize;
  318. for (int i = 0; i < mTargetStates.Length; ++i)
  319. {
  320. int hash = mTargetStates[i];
  321. if (hash == 0)
  322. continue;
  323. bool alreadyThere = false;
  324. for (int j = 0; j < len; ++j)
  325. {
  326. if (target.m_Instructions[j].m_FullHash == hash)
  327. {
  328. alreadyThere = true;
  329. break;
  330. }
  331. }
  332. if (!alreadyThere)
  333. {
  334. int index = mInstructionList.serializedProperty.arraySize;
  335. ++mInstructionList.serializedProperty.arraySize;
  336. SerializedProperty p = mInstructionList.serializedProperty.GetArrayElementAtIndex(index);
  337. p.FindPropertyRelative(() => def.m_FullHash).intValue = hash;
  338. }
  339. }
  340. serializedObject.ApplyModifiedProperties();
  341. Target.ValidateInstructions();
  342. },
  343. null);
  344. menu.ShowAsContext();
  345. };
  346. }
  347. void SetupChildList()
  348. {
  349. float vSpace = 2;
  350. float hSpace = 3;
  351. float floatFieldWidth = EditorGUIUtility.singleLineHeight * 2.5f;
  352. float hBigSpace = EditorGUIUtility.singleLineHeight * 2 / 3;
  353. mChildList = new UnityEditorInternal.ReorderableList(serializedObject,
  354. serializedObject.FindProperty(() => Target.m_ChildCameras),
  355. true, true, true, true);
  356. mChildList.drawHeaderCallback = (Rect rect) =>
  357. {
  358. EditorGUI.LabelField(rect, "Virtual Camera Children");
  359. GUIContent priorityText = new GUIContent("Priority");
  360. var textDimensions = GUI.skin.label.CalcSize(priorityText);
  361. rect.x += rect.width - textDimensions.x;
  362. rect.width = textDimensions.x;
  363. EditorGUI.LabelField(rect, priorityText);
  364. };
  365. mChildList.drawElementCallback
  366. = (Rect rect, int index, bool isActive, bool isFocused) =>
  367. {
  368. rect.y += vSpace; rect.height = EditorGUIUtility.singleLineHeight;
  369. rect.width -= floatFieldWidth + hBigSpace;
  370. SerializedProperty element = mChildList.serializedProperty.GetArrayElementAtIndex(index);
  371. EditorGUI.PropertyField(rect, element, GUIContent.none);
  372. float oldWidth = EditorGUIUtility.labelWidth;
  373. EditorGUIUtility.labelWidth = hBigSpace;
  374. SerializedObject obj = new SerializedObject(element.objectReferenceValue);
  375. rect.x += rect.width + hSpace; rect.width = floatFieldWidth + hBigSpace;
  376. SerializedProperty priorityProp = obj.FindProperty(() => Target.m_Priority);
  377. EditorGUI.PropertyField(rect, priorityProp, new GUIContent(" ", priorityProp.tooltip));
  378. EditorGUIUtility.labelWidth = oldWidth;
  379. obj.ApplyModifiedProperties();
  380. };
  381. mChildList.onChangedCallback = (UnityEditorInternal.ReorderableList l) =>
  382. {
  383. if (l.index < 0 || l.index >= l.serializedProperty.arraySize)
  384. return;
  385. Object o = l.serializedProperty.GetArrayElementAtIndex(
  386. l.index).objectReferenceValue;
  387. CinemachineVirtualCameraBase vcam = (o != null)
  388. ? (o as CinemachineVirtualCameraBase) : null;
  389. if (vcam != null)
  390. vcam.transform.SetSiblingIndex(l.index);
  391. };
  392. mChildList.onAddCallback = (UnityEditorInternal.ReorderableList l) =>
  393. {
  394. var index = l.serializedProperty.arraySize;
  395. var vcam = CinemachineMenu.CreateDefaultVirtualCamera();
  396. Undo.SetTransformParent(vcam.transform, Target.transform, "");
  397. vcam.transform.SetSiblingIndex(index);
  398. };
  399. mChildList.onRemoveCallback = (UnityEditorInternal.ReorderableList l) =>
  400. {
  401. Object o = l.serializedProperty.GetArrayElementAtIndex(
  402. l.index).objectReferenceValue;
  403. CinemachineVirtualCameraBase vcam = (o != null)
  404. ? (o as CinemachineVirtualCameraBase) : null;
  405. if (vcam != null)
  406. Undo.DestroyObjectImmediate(vcam.gameObject);
  407. };
  408. }
  409. }
  410. #endif
  411. }