Animation.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. namespace BansheeEngine
  8. {
  9. /** @addtogroup Animation
  10. * @{
  11. */
  12. /// <summary>
  13. /// Determines how an animation clip behaves when it reaches the end.
  14. /// </summary>
  15. public enum AnimWrapMode // Note: Must match C++ enum AnimWrapMode
  16. {
  17. /// <summary>
  18. /// Loop around to the beginning/end when the last/first frame is reached.
  19. /// </summary>
  20. Loop,
  21. /// <summary>
  22. /// Clamp to end/beginning, keeping the last/first frame active.
  23. /// </summary>
  24. Clamp
  25. }
  26. /// <summary>
  27. /// Represents an animation clip used in 1D blending. Each clip has a position on the number line.
  28. /// </summary>
  29. public class BlendClipInfo
  30. {
  31. public AnimationClip clip;
  32. public float position;
  33. }
  34. /// <summary>
  35. /// Defines a 1D blend where two animation clips are blended between each other using linear interpolation.
  36. /// </summary>
  37. public class Blend1DInfo
  38. {
  39. public BlendClipInfo[] clips;
  40. }
  41. /// <summary>
  42. /// Defines a 2D blend where two animation clips are blended between each other using bilinear interpolation.
  43. /// </summary>
  44. public class Blend2DInfo
  45. {
  46. public AnimationClip topLeftClip;
  47. public AnimationClip topRightClip;
  48. public AnimationClip botLeftClip;
  49. public AnimationClip botRightClip;
  50. }
  51. /// <summary>
  52. /// Contains information about a currently playing animation clip.
  53. /// </summary>
  54. [StructLayout(LayoutKind.Sequential), SerializeObject]
  55. public struct AnimationClipState // Note: Must match C++ struct AnimationClipState
  56. {
  57. /// <summary>
  58. /// Layer the clip is playing on. Multiple clips can be played simulatenously on different layers.
  59. /// </summary>
  60. public int layer;
  61. /// <summary>
  62. /// Current time the animation is playing from.
  63. /// </summary>
  64. public float time;
  65. /// <summary>
  66. /// Speed at which the animation is playing.
  67. /// </summary>
  68. public float speed;
  69. /// <summary>
  70. /// Determines how much of an influence does the clip have on the final pose.
  71. /// </summary>
  72. public float weight;
  73. /// <summary>
  74. /// Determines what happens to other animation clips when a new clip starts playing.
  75. /// </summary>
  76. public AnimWrapMode wrapMode;
  77. /// <summary>
  78. /// Initializes the state with default values.
  79. /// </summary>
  80. public void InitDefault()
  81. {
  82. speed = 1.0f;
  83. weight = 1.0f;
  84. wrapMode = AnimWrapMode.Loop;
  85. }
  86. }
  87. /// <summary>
  88. /// Handles animation playback. Takes one or multiple animation clips as input and evaluates them every animation update
  89. /// tick depending on set properties.The evaluated data is used by the core thread for skeletal animation, by the sim
  90. /// thread for updating attached scene objects and bones (if skeleton is attached), or the data is made available for
  91. /// manual queries in the case of generic animation.
  92. /// </summary>
  93. public class Animation : Component
  94. {
  95. private NativeAnimation _native;
  96. [SerializeField] private SerializableData serializableData = new SerializableData();
  97. private FloatCurvePropertyInfo[] floatProperties;
  98. private List<SceneObjectMappingInfo> mappingInfo = new List<SceneObjectMappingInfo>();
  99. private AnimationClip primaryClip;
  100. /// <summary>
  101. /// Contains mapping for a suffix used by property paths used for curve identifiers, to their index and type.
  102. /// </summary>
  103. internal static readonly Dictionary<string, PropertySuffixInfo> PropertySuffixInfos = new Dictionary
  104. <string, PropertySuffixInfo>
  105. {
  106. {".x", new PropertySuffixInfo(0, true)},
  107. {".y", new PropertySuffixInfo(1, true)},
  108. {".z", new PropertySuffixInfo(2, true)},
  109. {".w", new PropertySuffixInfo(3, true)},
  110. {".r", new PropertySuffixInfo(0, false)},
  111. {".g", new PropertySuffixInfo(1, false)},
  112. {".b", new PropertySuffixInfo(2, false)},
  113. {".a", new PropertySuffixInfo(3, false)}
  114. };
  115. /// <summary>
  116. /// Returns the non-component version of Animation that is wrapped by this component.
  117. /// </summary>
  118. internal NativeAnimation Native
  119. {
  120. get { return _native; }
  121. }
  122. /// <summary>
  123. /// Determines the default clip to play as soon as the component is enabled. If more control over playing clips is
  124. /// needed use the <see cref="Play"/>, <see cref="Blend1D"/>, <see cref="Blend2D"/> and <see cref="CrossFade"/>
  125. /// methods to queue clips for playback manually, and <see cref="SetState"/> method for modify their states
  126. /// individually.
  127. /// </summary>
  128. public AnimationClip DefaultClip
  129. {
  130. get { return serializableData.defaultClip; }
  131. set
  132. {
  133. serializableData.defaultClip = value;
  134. if (value != null && _native != null)
  135. _native.Play(value);
  136. }
  137. }
  138. /// <summary>
  139. /// Determines the wrap mode for all active animations. Wrap mode determines what happens when animation reaches the
  140. /// first or last frame.
  141. /// <see cref="AnimWrapMode"/>
  142. /// </summary>
  143. public AnimWrapMode WrapMode
  144. {
  145. get { return serializableData.wrapMode; }
  146. set
  147. {
  148. serializableData.wrapMode = value;
  149. if (_native != null)
  150. _native.WrapMode = value;
  151. }
  152. }
  153. /// <summary>
  154. /// Determines the speed for all animations. The default value is 1.0f. Use negative values to play-back in reverse.
  155. /// </summary>
  156. public float Speed
  157. {
  158. get { return serializableData.speed; }
  159. set
  160. {
  161. serializableData.speed = value;
  162. if (_native != null)
  163. _native.Speed = value;
  164. }
  165. }
  166. /// <summary>
  167. /// Checks if any animation clips are currently playing.
  168. /// </summary>
  169. public bool IsPlaying
  170. {
  171. get
  172. {
  173. if (_native != null)
  174. return _native.IsPlaying();
  175. return false;
  176. }
  177. }
  178. /// <summary>
  179. /// Plays the specified animation clip.
  180. /// </summary>
  181. /// <param name="clip">Clip to play.</param>
  182. public void Play(AnimationClip clip)
  183. {
  184. if (_native != null)
  185. _native.Play(clip);
  186. }
  187. /// <summary>
  188. /// Plays the specified animation clip on top of the animation currently playing in the main layer. Multiple such
  189. /// clips can be playing at once, as long as you ensure each is given its own layer. Each animation can also have a
  190. /// weight that determines how much it influences the main animation.
  191. /// </summary>
  192. /// <param name="clip">Clip to additively blend. Must contain additive animation curves.</param>
  193. /// <param name="weight">Determines how much of an effect will the blended animation have on the final output.
  194. /// In range [0, 1].</param>
  195. /// <param name="fadeLength">Applies the blend over a specified time period, increasing the weight as the time
  196. /// passes. Set to zero to blend immediately. In seconds.</param>
  197. /// <param name="layer">Layer to play the clip in. Multiple additive clips can be playing at once in separate layers
  198. /// and each layer has its own weight.</param>
  199. public void BlendAdditive(AnimationClip clip, float weight, float fadeLength, int layer)
  200. {
  201. if (_native != null)
  202. _native.BlendAdditive(clip, weight, fadeLength, layer);
  203. }
  204. /// <summary>
  205. /// Blends multiple animation clips between each other using linear interpolation. Unlike normal animations these
  206. /// animations are not advanced with the progress of time, and is instead expected the user manually changes the
  207. /// <see cref="t"/> parameter.
  208. /// </summary>
  209. /// <param name="info">Information about the clips to blend. Clip positions must be sorted from lowest to highest.
  210. /// </param>
  211. /// <param name="t">Parameter that controls the blending, in range [0, 1]. t = 0 means left animation has full
  212. /// influence, t = 1 means right animation has full influence.</param>
  213. public void Blend1D(Blend1DInfo info, float t)
  214. {
  215. if (_native != null)
  216. _native.Blend1D(info, t);
  217. }
  218. /// <summary>
  219. /// Blend four animation clips between each other using bilinear interpolation. Unlike normal animations these
  220. /// animations are not advanced with the progress of time, and is instead expected the user manually changes the
  221. /// <see cref="t"/> parameter.
  222. /// </summary>
  223. /// <param name="info">Information about the clips to blend.</param>
  224. /// <param name="t">Parameter that controls the blending, in range [(0, 0), (1, 1)]. t = (0, 0) means top left
  225. /// animation has full influence, t = (0, 1) means top right animation has full influence,
  226. /// t = (1, 0) means bottom left animation has full influence, t = (1, 1) means bottom right
  227. /// animation has full influence.
  228. /// </param>
  229. public void Blend2D(Blend2DInfo info, Vector2 t)
  230. {
  231. if (_native != null)
  232. _native.Blend2D(info, t);
  233. }
  234. /// <summary>
  235. /// Fades the specified animation clip in, while fading other playing animation out, over the specified time period.
  236. /// </summary>
  237. /// <param name="clip">Clip to fade in.</param>
  238. /// <param name="fadeLength">Determines the time period over which the fade occurs. In seconds.</param>
  239. public void CrossFade(AnimationClip clip, float fadeLength)
  240. {
  241. if (_native != null)
  242. _native.CrossFade(clip, fadeLength);
  243. }
  244. /// <summary>
  245. /// Stops playing all animations on the provided layer.
  246. /// </summary>
  247. /// <param name="layer">Layer on which to stop animations on.</param>
  248. public void Stop(int layer)
  249. {
  250. if (_native != null)
  251. _native.Stop(layer);
  252. }
  253. /// <summary>
  254. /// Stops playing all animations.
  255. /// </summary>
  256. public void StopAll()
  257. {
  258. if (_native != null)
  259. _native.StopAll();
  260. }
  261. /// <summary>
  262. /// Retrieves detailed information about a currently playing animation clip.
  263. /// </summary>
  264. /// <param name="clip">Clip to retrieve the information for.</param>
  265. /// <param name="state">Animation clip state containing the requested information. Only valid if the method returns
  266. /// true.</param>
  267. /// <returns>True if the state was found (animation clip is playing), false otherwise.</returns>
  268. public bool GetState(AnimationClip clip, out AnimationClipState state)
  269. {
  270. if (_native != null)
  271. return _native.GetState(clip, out state);
  272. state = new AnimationClipState();
  273. return false;
  274. }
  275. /// <summary>
  276. /// Searches the scene object hierarchy to find a property at the given path.
  277. /// </summary>
  278. /// <param name="root">Root scene object to which the path is relative to.</param>
  279. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  280. ///
  281. /// Path elements prefixed with "!" signify names of child scene objects (first one relative to
  282. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  283. ///
  284. /// Path element prefixed with ":" signify names of components. If a path doesn't have a
  285. /// component element, it is assumed the field is relative to the scene object itself (only
  286. /// "Translation", "Rotation" and "Scale fields are supported in such case). Only one component
  287. /// path element per path is allowed.
  288. ///
  289. /// Path entries with no prefix are considered regular script object fields. Each path must have
  290. /// at least one such entry. Last field entry can optionally have a suffix separated from the
  291. /// path name with ".". This suffix is not parsed internally, but will be returned as
  292. /// <paramref name="suffix"/>.
  293. ///
  294. /// Path examples:
  295. /// :MyComponent/myInt (path to myInt variable on a component attached to this object)
  296. /// !childSO/:MyComponent/myInt (path to myInt variable on a child scene object)
  297. /// !childSO/Translation (path to the scene object translation)
  298. /// :MyComponent/myVector.z (path to the z component of myVector on this object)
  299. /// </param>
  300. /// <param name="suffix">Suffix of the last field entry, if it has any. Contains the suffix separator ".".</param>
  301. /// <returns>If found, property object you can use for setting and getting the value from the property, otherwise
  302. /// null.</returns>
  303. internal static SerializableProperty FindProperty(SceneObject root, string path, out string suffix)
  304. {
  305. suffix = null;
  306. if (string.IsNullOrEmpty(path) || root == null)
  307. return null;
  308. string trimmedPath = path.Trim('/');
  309. string[] entries = trimmedPath.Split('/');
  310. // Find scene object referenced by the path
  311. SceneObject so = root;
  312. int pathIdx = 0;
  313. for (; pathIdx < entries.Length; pathIdx++)
  314. {
  315. string entry = entries[pathIdx];
  316. if (string.IsNullOrEmpty(entry))
  317. continue;
  318. // Not a scene object, break
  319. if (entry[0] != '!')
  320. break;
  321. string childName = entry.Substring(1, entry.Length - 1);
  322. so = so.FindChild(childName);
  323. if (so == null)
  324. break;
  325. }
  326. // Child scene object couldn't be found
  327. if (so == null)
  328. return null;
  329. // Path too short, no field entry
  330. if (pathIdx >= entries.Length)
  331. return null;
  332. // Check if path is referencing a component, and if so find it
  333. Component component = null;
  334. {
  335. string entry = entries[pathIdx];
  336. if (entry[0] == ':')
  337. {
  338. string componentName = entry.Substring(1, entry.Length - 1);
  339. Component[] components = so.GetComponents();
  340. component = Array.Find(components, x => x.GetType().Name == componentName);
  341. // Cannot find component with specified type
  342. if (component == null)
  343. return null;
  344. }
  345. }
  346. // Look for a field within a component
  347. if (component != null)
  348. {
  349. pathIdx++;
  350. if (pathIdx >= entries.Length)
  351. return null;
  352. SerializableObject componentObj = new SerializableObject(component);
  353. StringBuilder pathBuilder = new StringBuilder();
  354. for (; pathIdx < entries.Length - 1; pathIdx++)
  355. pathBuilder.Append(entries[pathIdx] + "/");
  356. // Check last path entry for suffix and remove it
  357. int suffixIdx = entries[pathIdx].LastIndexOf(".");
  358. if (suffixIdx != -1)
  359. {
  360. string entryNoSuffix = entries[pathIdx].Substring(0, suffixIdx);
  361. suffix = entries[pathIdx].Substring(suffixIdx, entries[pathIdx].Length - suffixIdx);
  362. pathBuilder.Append(entryNoSuffix);
  363. }
  364. else
  365. pathBuilder.Append(entries[pathIdx]);
  366. return componentObj.FindProperty(pathBuilder.ToString());
  367. }
  368. else // Field is one of the builtin ones on the SceneObject itself
  369. {
  370. if ((pathIdx + 1) < entries.Length)
  371. return null;
  372. string entry = entries[pathIdx];
  373. if (entry == "Position")
  374. {
  375. SerializableProperty property = new SerializableProperty(
  376. SerializableProperty.FieldType.Vector3,
  377. typeof(Vector3),
  378. () => so.LocalPosition,
  379. (x) => so.LocalPosition = (Vector3) x);
  380. return property;
  381. }
  382. else if (entry == "Rotation")
  383. {
  384. SerializableProperty property = new SerializableProperty(
  385. SerializableProperty.FieldType.Vector3,
  386. typeof(Vector3),
  387. () => so.LocalRotation.ToEuler(),
  388. (x) => so.LocalRotation = Quaternion.FromEuler((Vector3) x));
  389. return property;
  390. }
  391. else if (entry == "Scale")
  392. {
  393. SerializableProperty property = new SerializableProperty(
  394. SerializableProperty.FieldType.Vector3,
  395. typeof(Vector3),
  396. () => so.LocalScale,
  397. (x) => so.LocalScale = (Vector3) x);
  398. return property;
  399. }
  400. return null;
  401. }
  402. }
  403. /// <summary>
  404. /// Searches the scene object hierarchy to find a child scene object using the provided path.
  405. /// </summary>
  406. /// <param name="root">Root scene object to which the path is relative to.</param>
  407. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  408. ///
  409. /// Path elements signify names of child scene objects (first one relative to
  410. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  411. /// Elements must be prefixed with "!" in order to match the path format of
  412. /// <see cref="FindProperty"/>.</param>
  413. /// <returns>Child scene object if found, or null otherwise.</returns>
  414. internal static SceneObject FindSceneObject(SceneObject root, string path)
  415. {
  416. if (string.IsNullOrEmpty(path) || root == null)
  417. return null;
  418. string trimmedPath = path.Trim('/');
  419. string[] entries = trimmedPath.Split('/');
  420. // Find scene object referenced by the path
  421. SceneObject so = root;
  422. int pathIdx = 0;
  423. for (; pathIdx < entries.Length; pathIdx++)
  424. {
  425. string entry = entries[pathIdx];
  426. if (string.IsNullOrEmpty(entry))
  427. continue;
  428. // Not a scene object, break
  429. if (entry[0] != '!')
  430. break;
  431. string childName = entry.Substring(1, entry.Length - 1);
  432. so = so.FindChild(childName);
  433. if (so == null)
  434. break;
  435. }
  436. return so;
  437. }
  438. /// <summary>
  439. /// Changes the state of a playing animation clip. If animation clip is not currently playing the state change is
  440. /// ignored.
  441. /// </summary>
  442. /// <param name="clip">Clip to change the state for.</param>
  443. /// <param name="state">New state of the animation (e.g. changing the time for seeking).</param>
  444. public void SetState(AnimationClip clip, AnimationClipState state)
  445. {
  446. if (_native != null)
  447. _native.SetState(clip, state);
  448. }
  449. private void OnUpdate()
  450. {
  451. if (_native == null)
  452. return;
  453. AnimationClip newPrimaryClip = _native.GetClip(0);
  454. if (newPrimaryClip != primaryClip)
  455. {
  456. RebuildFloatProperties(newPrimaryClip);
  457. primaryClip = newPrimaryClip;
  458. UpdateSceneObjectMapping();
  459. }
  460. // Apply values from generic float curves
  461. if (floatProperties != null)
  462. {
  463. foreach (var entry in floatProperties)
  464. {
  465. float curveValue;
  466. if (_native.GetGenericCurveValue(entry.curveIdx, out curveValue))
  467. entry.setter(curveValue);
  468. }
  469. }
  470. }
  471. private void OnEnable()
  472. {
  473. RestoreNative();
  474. }
  475. private void OnDisable()
  476. {
  477. DestroyNative();
  478. }
  479. private void OnDestroy()
  480. {
  481. DestroyNative();
  482. }
  483. /// <summary>
  484. /// Creates the internal representation of the animation and restores the values saved by the component.
  485. /// </summary>
  486. private void RestoreNative()
  487. {
  488. if (_native != null)
  489. _native.Destroy();
  490. _native = new NativeAnimation();
  491. _native.OnEventTriggered += EventTriggered;
  492. // Restore saved values after reset
  493. _native.WrapMode = serializableData.wrapMode;
  494. _native.Speed = serializableData.speed;
  495. if (serializableData.defaultClip != null)
  496. _native.Play(serializableData.defaultClip);
  497. primaryClip = _native.GetClip(0);
  498. if (primaryClip != null)
  499. RebuildFloatProperties(primaryClip);
  500. SetBoneMappings();
  501. UpdateSceneObjectMapping();
  502. Renderable renderable = SceneObject.GetComponent<Renderable>();
  503. if (renderable == null)
  504. return;
  505. renderable.NativeAnimation = _native;
  506. }
  507. /// <summary>
  508. /// Destroys the internal animation representation.
  509. /// </summary>
  510. private void DestroyNative()
  511. {
  512. Renderable renderableComponent = SceneObject.GetComponent<Renderable>();
  513. if (renderableComponent != null)
  514. {
  515. NativeRenderable renderable = renderableComponent.Native;
  516. if (renderable != null)
  517. renderable.Animation = null;
  518. }
  519. if (_native != null)
  520. {
  521. _native.Destroy();
  522. _native = null;
  523. }
  524. primaryClip = null;
  525. mappingInfo.Clear();
  526. floatProperties = null;
  527. }
  528. /// <summary>
  529. /// Finds any curves that affect a transform of a specific scene object, and ensures that animation properly updates
  530. /// those transforms. This does not include curves referencing bones.
  531. /// </summary>
  532. private void UpdateSceneObjectMapping()
  533. {
  534. List<SceneObjectMappingInfo> newMappingInfos = new List<SceneObjectMappingInfo>();
  535. foreach(var entry in mappingInfo)
  536. {
  537. if (entry.isMappedToBone)
  538. newMappingInfos.Add(entry);
  539. else
  540. _native.UnmapSceneObject(entry.sceneObject);
  541. }
  542. if (primaryClip != null)
  543. {
  544. SceneObject root = SceneObject;
  545. Action<NamedVector3Curve[]> findMappings = x =>
  546. {
  547. foreach (var curve in x)
  548. {
  549. if (curve.Flags.HasFlag(AnimationCurveFlags.ImportedCurve))
  550. continue;
  551. SceneObject currentSO = FindSceneObject(root, curve.Name);
  552. bool found = false;
  553. for (int i = 0; i < newMappingInfos.Count; i++)
  554. {
  555. if (newMappingInfos[i].sceneObject == currentSO)
  556. {
  557. found = true;
  558. break;
  559. }
  560. }
  561. if (!found)
  562. {
  563. SceneObjectMappingInfo newMappingInfo = new SceneObjectMappingInfo();
  564. newMappingInfo.isMappedToBone = false;
  565. newMappingInfo.sceneObject = currentSO;
  566. newMappingInfos.Add(newMappingInfo);
  567. _native.MapCurveToSceneObject(curve.Name, currentSO);
  568. }
  569. }
  570. };
  571. AnimationCurves curves = primaryClip.Curves;
  572. findMappings(curves.PositionCurves);
  573. findMappings(curves.RotationCurves);
  574. findMappings(curves.ScaleCurves);
  575. }
  576. mappingInfo = newMappingInfos;
  577. }
  578. /// <summary>
  579. /// Registers a new bone component, creating a new transform mapping from the bone name to the scene object
  580. /// the component is attached to.
  581. /// </summary>
  582. /// <param name="bone">Bone component to register.</param>
  583. internal void AddBone(Bone bone)
  584. {
  585. if (_native == null)
  586. return;
  587. SceneObject currentSO = bone.SceneObject;
  588. SceneObjectMappingInfo newMapping = new SceneObjectMappingInfo();
  589. newMapping.sceneObject = currentSO;
  590. newMapping.isMappedToBone = true;
  591. newMapping.bone = bone;
  592. mappingInfo.Add(newMapping);
  593. _native.MapCurveToSceneObject(bone.Name, newMapping.sceneObject);
  594. }
  595. /// <summary>
  596. /// Unregisters a bone component, removing the bone -> scene object mapping.
  597. /// </summary>
  598. /// <param name="bone">Bone to unregister.</param>
  599. internal void RemoveBone(Bone bone)
  600. {
  601. if (_native == null)
  602. return;
  603. SceneObject newSO = null;
  604. for (int i = 0; i < mappingInfo.Count; i++)
  605. {
  606. if (mappingInfo[i].bone == bone)
  607. {
  608. mappingInfo.RemoveAt(i);
  609. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  610. i--;
  611. }
  612. }
  613. }
  614. /// <summary>
  615. /// Called whenever the bone the <see cref="Bone"/> component points to changed.
  616. /// </summary>
  617. /// <param name="bone">Bone component to modify.</param>
  618. internal void NotifyBoneChanged(Bone bone)
  619. {
  620. if (_native == null)
  621. return;
  622. for (int i = 0; i < mappingInfo.Count; i++)
  623. {
  624. if (mappingInfo[i].bone == bone)
  625. {
  626. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  627. _native.MapCurveToSceneObject(bone.Name, mappingInfo[i].sceneObject);
  628. break;
  629. }
  630. }
  631. }
  632. /// <summary>
  633. /// Finds any scene objects that are mapped to bone transforms. Such object's transforms will be affected by
  634. /// skeleton bone animation.
  635. /// </summary>
  636. private void SetBoneMappings()
  637. {
  638. mappingInfo.Clear();
  639. SceneObjectMappingInfo rootMapping = new SceneObjectMappingInfo();
  640. rootMapping.sceneObject = SceneObject;
  641. rootMapping.isMappedToBone = true;
  642. mappingInfo.Add(rootMapping);
  643. _native.MapCurveToSceneObject("", rootMapping.sceneObject);
  644. Bone[] childBones = FindChildBones();
  645. foreach (var entry in childBones)
  646. AddBone(entry);
  647. }
  648. /// <summary>
  649. /// Searches child scene objects for <see cref="Bone"/> components and returns any found ones.
  650. /// </summary>
  651. private Bone[] FindChildBones()
  652. {
  653. Stack<SceneObject> todo = new Stack<SceneObject>();
  654. todo.Push(SceneObject);
  655. List<Bone> bones = new List<Bone>();
  656. while (todo.Count > 0)
  657. {
  658. SceneObject currentSO = todo.Pop();
  659. Bone bone = currentSO.GetComponent<Bone>();
  660. if (bone != null)
  661. {
  662. bone.SetParent(this, true);
  663. bones.Add(bone);
  664. }
  665. int childCount = currentSO.GetNumChildren();
  666. for (int i = 0; i < childCount; i++)
  667. {
  668. SceneObject child = currentSO.GetChild(i);
  669. if (child.GetComponent<Animation>() != null)
  670. continue;
  671. todo.Push(child);
  672. }
  673. }
  674. return bones.ToArray();
  675. }
  676. /// <summary>
  677. /// Builds a list of properties that will be animated using float animation curves.
  678. /// </summary>
  679. /// <param name="clip">Clip to retrieve the float animation curves from.</param>
  680. private void RebuildFloatProperties(AnimationClip clip)
  681. {
  682. if (clip == null)
  683. {
  684. floatProperties = null;
  685. return;
  686. }
  687. AnimationCurves curves = clip.Curves;
  688. List<FloatCurvePropertyInfo> newFloatProperties = new List<FloatCurvePropertyInfo>();
  689. for (int i = 0; i < curves.FloatCurves.Length; i++)
  690. {
  691. string suffix;
  692. SerializableProperty property = FindProperty(SceneObject, curves.FloatCurves[i].Name, out suffix);
  693. if (property == null)
  694. continue;
  695. int elementIdx = 0;
  696. if (!string.IsNullOrEmpty(suffix))
  697. {
  698. PropertySuffixInfo suffixInfo;
  699. if (PropertySuffixInfos.TryGetValue(suffix, out suffixInfo))
  700. elementIdx = suffixInfo.elementIdx;
  701. }
  702. Action<float> setter = null;
  703. Type internalType = property.InternalType;
  704. switch (property.Type)
  705. {
  706. case SerializableProperty.FieldType.Vector2:
  707. if (internalType == typeof(Vector2))
  708. {
  709. setter = f =>
  710. {
  711. Vector2 value = property.GetValue<Vector2>();
  712. value[elementIdx] = f;
  713. property.SetValue(value);
  714. };
  715. }
  716. break;
  717. case SerializableProperty.FieldType.Vector3:
  718. if (internalType == typeof(Vector3))
  719. {
  720. setter = f =>
  721. {
  722. Vector3 value = property.GetValue<Vector3>();
  723. value[elementIdx] = f;
  724. property.SetValue(value);
  725. };
  726. }
  727. break;
  728. case SerializableProperty.FieldType.Vector4:
  729. if (internalType == typeof(Vector4))
  730. {
  731. setter = f =>
  732. {
  733. Vector4 value = property.GetValue<Vector4>();
  734. value[elementIdx] = f;
  735. property.SetValue(value);
  736. };
  737. }
  738. else if (internalType == typeof(Quaternion))
  739. {
  740. setter = f =>
  741. {
  742. Quaternion value = property.GetValue<Quaternion>();
  743. value[elementIdx] = f;
  744. property.SetValue(value);
  745. };
  746. }
  747. break;
  748. case SerializableProperty.FieldType.Color:
  749. if (internalType == typeof(Color))
  750. {
  751. setter = f =>
  752. {
  753. Color value = property.GetValue<Color>();
  754. value[elementIdx] = f;
  755. property.SetValue(value);
  756. };
  757. }
  758. break;
  759. case SerializableProperty.FieldType.Bool:
  760. setter = f =>
  761. {
  762. bool value = f > 0.0f;
  763. property.SetValue(value);
  764. };
  765. break;
  766. case SerializableProperty.FieldType.Int:
  767. setter = f =>
  768. {
  769. int value = (int)f;
  770. property.SetValue(value);
  771. };
  772. break;
  773. case SerializableProperty.FieldType.Float:
  774. setter = f =>
  775. {
  776. property.SetValue(f);
  777. };
  778. break;
  779. }
  780. if (setter == null)
  781. continue;
  782. FloatCurvePropertyInfo propertyInfo = new FloatCurvePropertyInfo();
  783. propertyInfo.curveIdx = i;
  784. propertyInfo.setter = setter;
  785. newFloatProperties.Add(propertyInfo);
  786. }
  787. floatProperties = newFloatProperties.ToArray();
  788. }
  789. /// <summary>
  790. /// Called whenever an animation event triggers.
  791. /// </summary>
  792. /// <param name="clip">Clip that the event originated from.</param>
  793. /// <param name="name">Name of the event.</param>
  794. private void EventTriggered(AnimationClip clip, string name)
  795. {
  796. // Event should be in format "ComponentType/MethodName"
  797. if (string.IsNullOrEmpty(name))
  798. return;
  799. string[] nameEntries = name.Split('/');
  800. if (nameEntries.Length != 2)
  801. return;
  802. string typeName = nameEntries[0];
  803. string methodName = nameEntries[1];
  804. Component[] components = SceneObject.GetComponents();
  805. for (int i = 0; i < components.Length; i++)
  806. {
  807. if (components[i].GetType().Name == typeName)
  808. {
  809. components[i].Invoke(methodName);
  810. break;
  811. }
  812. }
  813. }
  814. /// <summary>
  815. /// Holds all data the animation component needs to persist through serialization.
  816. /// </summary>
  817. [SerializeObject]
  818. private class SerializableData
  819. {
  820. public AnimationClip defaultClip;
  821. public AnimWrapMode wrapMode = AnimWrapMode.Loop;
  822. public float speed = 1.0f;
  823. }
  824. /// <summary>
  825. /// Contains information about a property animated by a generic animation curve.
  826. /// </summary>
  827. private class FloatCurvePropertyInfo
  828. {
  829. public int curveIdx;
  830. public Action<float> setter;
  831. }
  832. /// <summary>
  833. /// Information about a suffix used in a property path.
  834. /// </summary>
  835. internal struct PropertySuffixInfo
  836. {
  837. public PropertySuffixInfo(int elementIdx, bool isVector)
  838. {
  839. this.elementIdx = elementIdx;
  840. this.isVector = isVector;
  841. }
  842. public int elementIdx;
  843. public bool isVector;
  844. }
  845. /// <summary>
  846. /// Information about scene objects bound to a specific animation curve.
  847. /// </summary>
  848. internal struct SceneObjectMappingInfo
  849. {
  850. public SceneObject sceneObject;
  851. public bool isMappedToBone;
  852. public Bone bone;
  853. }
  854. }
  855. /** @} */
  856. }