CinemachineStateDrivenCameraEditor.cs 20 KB

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