Animation.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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. /// Handles animation playback. Takes one or multiple animation clips as input and evaluates them every animation update
  14. /// tick depending on set properties.The evaluated data is used by the core thread for skeletal animation, by the sim
  15. /// thread for updating attached scene objects and bones (if skeleton is attached), or the data is made available for
  16. /// manual queries in the case of generic animation.
  17. /// </summary>
  18. public class Animation : Component
  19. {
  20. private NativeAnimation _native;
  21. [SerializeField] private SerializableData serializableData = new SerializableData();
  22. private FloatCurvePropertyInfo[] floatProperties;
  23. private List<SceneObjectMappingInfo> mappingInfo = new List<SceneObjectMappingInfo>();
  24. private AnimationClip primaryClip;
  25. private Renderable animatedRenderable;
  26. private State state = State.Inactive;
  27. /// <summary>
  28. /// Contains mapping for a suffix used by property paths used for curve identifiers, to their index and type.
  29. /// </summary>
  30. internal static readonly Dictionary<string, PropertySuffixInfo> PropertySuffixInfos = new Dictionary
  31. <string, PropertySuffixInfo>
  32. {
  33. {".x", new PropertySuffixInfo(0, true)},
  34. {".y", new PropertySuffixInfo(1, true)},
  35. {".z", new PropertySuffixInfo(2, true)},
  36. {".w", new PropertySuffixInfo(3, true)},
  37. {".r", new PropertySuffixInfo(0, false)},
  38. {".g", new PropertySuffixInfo(1, false)},
  39. {".b", new PropertySuffixInfo(2, false)},
  40. {".a", new PropertySuffixInfo(3, false)}
  41. };
  42. /// <summary>
  43. /// Returns the non-component version of Animation that is wrapped by this component.
  44. /// </summary>
  45. internal NativeAnimation Native
  46. {
  47. get { return _native; }
  48. }
  49. /// <summary>
  50. /// Determines the default clip to play as soon as the component is enabled. If more control over playing clips is
  51. /// needed use the <see cref="Play"/>, <see cref="Blend1D"/>, <see cref="Blend2D"/> and <see cref="CrossFade"/>
  52. /// methods to queue clips for playback manually, and <see cref="SetState"/> method for modify their states
  53. /// individually.
  54. /// </summary>
  55. public AnimationClip DefaultClip
  56. {
  57. get { return serializableData.defaultClip; }
  58. set
  59. {
  60. serializableData.defaultClip = value;
  61. if (value != null)
  62. {
  63. switch (state)
  64. {
  65. case State.Active:
  66. _native.Play(value);
  67. break;
  68. }
  69. }
  70. }
  71. }
  72. /// <summary>
  73. /// Determines the wrap mode for all active animations. Wrap mode determines what happens when animation reaches the
  74. /// first or last frame.
  75. /// <see cref="AnimWrapMode"/>
  76. /// </summary>
  77. public AnimWrapMode WrapMode
  78. {
  79. get { return serializableData.wrapMode; }
  80. set
  81. {
  82. serializableData.wrapMode = value;
  83. switch (state)
  84. {
  85. case State.Active:
  86. _native.WrapMode = value;
  87. break;
  88. }
  89. }
  90. }
  91. /// <summary>
  92. /// Determines the speed for all animations. The default value is 1.0f. Use negative values to play-back in reverse.
  93. /// </summary>
  94. public float Speed
  95. {
  96. get { return serializableData.speed; }
  97. set
  98. {
  99. serializableData.speed = value;
  100. switch (state)
  101. {
  102. case State.Active:
  103. _native.Speed = value;
  104. break;
  105. }
  106. }
  107. }
  108. /// <summary>
  109. /// Checks if any animation clips are currently playing.
  110. /// </summary>
  111. public bool IsPlaying
  112. {
  113. get
  114. {
  115. switch (state)
  116. {
  117. case State.Active:
  118. return _native.IsPlaying();
  119. default:
  120. return false;
  121. }
  122. }
  123. }
  124. /// <summary>
  125. /// Sets bounds that will be used for animation and mesh culling. Only relevant if <see cref="UseBounds"/> is set
  126. /// to true.
  127. /// </summary>
  128. public AABox Bounds
  129. {
  130. get { return serializableData.bounds; }
  131. set
  132. {
  133. serializableData.bounds = value;
  134. if (serializableData.useBounds)
  135. {
  136. if (animatedRenderable != null && animatedRenderable.Native != null)
  137. animatedRenderable.Native.OverrideBounds = value;
  138. AABox bounds = serializableData.bounds;
  139. Matrix4 parentTfrm;
  140. if (SceneObject.Parent != null)
  141. parentTfrm = SceneObject.Parent.WorldTransform;
  142. else
  143. parentTfrm = Matrix4.Identity;
  144. bounds.TransformAffine(parentTfrm);
  145. switch (state)
  146. {
  147. case State.Active:
  148. _native.Bounds = bounds;
  149. break;
  150. }
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// Determines should animation bounds be used for visibility determination (culling). If false the bounds of the
  156. /// mesh attached to the relevant <see cref="Renderable"/> component will be used instead.
  157. /// </summary>
  158. public bool UseBounds
  159. {
  160. get { return serializableData.useBounds; }
  161. set
  162. {
  163. serializableData.useBounds = value;
  164. UpdateBounds();
  165. }
  166. }
  167. /// <summary>
  168. /// If true, the animation will not be evaluated when it is out of view.
  169. /// </summary>
  170. public bool Cull
  171. {
  172. get { return serializableData.cull; }
  173. set
  174. {
  175. serializableData.cull = value;
  176. switch (state)
  177. {
  178. case State.Active:
  179. _native.Cull = value;
  180. break;
  181. }
  182. }
  183. }
  184. /// <summary>
  185. /// Plays the specified animation clip.
  186. /// </summary>
  187. /// <param name="clip">Clip to play.</param>
  188. public void Play(AnimationClip clip)
  189. {
  190. switch (state)
  191. {
  192. case State.Active:
  193. _native.Play(clip);
  194. break;
  195. }
  196. }
  197. /// <summary>
  198. /// Plays the specified animation clip on top of the animation currently playing in the main layer. Multiple such
  199. /// clips can be playing at once, as long as you ensure each is given its own layer. Each animation can also have a
  200. /// weight that determines how much it influences the main animation.
  201. /// </summary>
  202. /// <param name="clip">Clip to additively blend. Must contain additive animation curves.</param>
  203. /// <param name="weight">Determines how much of an effect will the blended animation have on the final output.
  204. /// In range [0, 1].</param>
  205. /// <param name="fadeLength">Applies the blend over a specified time period, increasing the weight as the time
  206. /// passes. Set to zero to blend immediately. In seconds.</param>
  207. /// <param name="layer">Layer to play the clip in. Multiple additive clips can be playing at once in separate layers
  208. /// and each layer has its own weight.</param>
  209. public void BlendAdditive(AnimationClip clip, float weight, float fadeLength, int layer)
  210. {
  211. switch (state)
  212. {
  213. case State.Active:
  214. _native.BlendAdditive(clip, weight, fadeLength, layer);
  215. break;
  216. }
  217. }
  218. /// <summary>
  219. /// Blends multiple animation clips between each other using linear 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. Clip positions must be sorted from lowest to highest.
  224. /// </param>
  225. /// <param name="t">Parameter that controls the blending, in range [0, 1]. t = 0 means left animation has full
  226. /// influence, t = 1 means right animation has full influence.</param>
  227. public void Blend1D(Blend1DInfo info, float t)
  228. {
  229. switch (state)
  230. {
  231. case State.Active:
  232. _native.Blend1D(info, t);
  233. break;
  234. }
  235. }
  236. /// <summary>
  237. /// Blend four animation clips between each other using bilinear interpolation. Unlike normal animations these
  238. /// animations are not advanced with the progress of time, and is instead expected the user manually changes the
  239. /// <see cref="t"/> parameter.
  240. /// </summary>
  241. /// <param name="info">Information about the clips to blend.</param>
  242. /// <param name="t">Parameter that controls the blending, in range [(0, 0), (1, 1)]. t = (0, 0) means top left
  243. /// animation has full influence, t = (0, 1) means top right animation has full influence,
  244. /// t = (1, 0) means bottom left animation has full influence, t = (1, 1) means bottom right
  245. /// animation has full influence.
  246. /// </param>
  247. public void Blend2D(Blend2DInfo info, Vector2 t)
  248. {
  249. switch (state)
  250. {
  251. case State.Active:
  252. _native.Blend2D(info, t);
  253. break;
  254. }
  255. }
  256. /// <summary>
  257. /// Fades the specified animation clip in, while fading other playing animation out, over the specified time period.
  258. /// </summary>
  259. /// <param name="clip">Clip to fade in.</param>
  260. /// <param name="fadeLength">Determines the time period over which the fade occurs. In seconds.</param>
  261. public void CrossFade(AnimationClip clip, float fadeLength)
  262. {
  263. switch (state)
  264. {
  265. case State.Active:
  266. _native.CrossFade(clip, fadeLength);
  267. break;
  268. }
  269. }
  270. /// <summary>
  271. /// Stops playing all animations on the provided layer.
  272. /// </summary>
  273. /// <param name="layer">Layer on which to stop animations on.</param>
  274. public void Stop(int layer)
  275. {
  276. switch (state)
  277. {
  278. case State.Active:
  279. _native.Stop(layer);
  280. break;
  281. }
  282. }
  283. /// <summary>
  284. /// Stops playing all animations.
  285. /// </summary>
  286. public void StopAll()
  287. {
  288. switch (state)
  289. {
  290. case State.Active:
  291. _native.StopAll();
  292. break;
  293. }
  294. }
  295. /// <summary>
  296. /// Retrieves detailed information about a currently playing animation clip.
  297. /// </summary>
  298. /// <param name="clip">Clip to retrieve the information for.</param>
  299. /// <param name="state">Animation clip state containing the requested information. Only valid if the method returns
  300. /// true.</param>
  301. /// <returns>True if the state was found (animation clip is playing), false otherwise.</returns>
  302. public bool GetState(AnimationClip clip, out AnimationClipState state)
  303. {
  304. switch (this.state)
  305. {
  306. case State.Active:
  307. case State.EditorActive:
  308. return _native.GetState(clip, out state);
  309. default:
  310. state = new AnimationClipState();
  311. return false;
  312. }
  313. }
  314. /// <summary>
  315. /// Changes the state of a playing animation clip. If animation clip is not currently playing the state change is
  316. /// ignored.
  317. /// </summary>
  318. /// <param name="clip">Clip to change the state for.</param>
  319. /// <param name="state">New state of the animation (e.g. changing the time for seeking).</param>
  320. public void SetState(AnimationClip clip, AnimationClipState state)
  321. {
  322. switch (this.state)
  323. {
  324. case State.Active:
  325. case State.EditorActive:
  326. _native.SetState(clip, state);
  327. break;
  328. }
  329. }
  330. /// <summary>
  331. /// Allows the caller to play an animation clip during edit mode. This form of animation playback is limited as
  332. /// you have no control over clip properties, and features like blending, cross fade or animation events are not
  333. /// supported.
  334. ///
  335. /// Caller will need to manually call <see cref="UpdateFloatProperties"/> in order to apply evaluated animation data
  336. /// to relevant float properties (if required).
  337. ///
  338. /// Caller will also need to manually call <see cref="RefreshClipMappings"/> whenever the curves internal to the
  339. /// animation clip change. This should be called before the call to <see cref="UpdateFloatProperties"/>.
  340. /// </summary>
  341. /// <param name="clip">Animation clip to play.</param>
  342. /// <param name="startTime">Time to start playing at, in seconds.</param>
  343. /// <param name="freeze">If true, only the frame at the specified time will be shown, without advancing the
  344. /// animation.</param>
  345. internal void EditorPlay(AnimationClip clip, float startTime, bool freeze = false)
  346. {
  347. switch (state)
  348. {
  349. case State.Inactive:
  350. SwitchState(State.EditorActive);
  351. break;
  352. }
  353. switch (state)
  354. {
  355. case State.EditorActive:
  356. AnimationClipState clipState = AnimationClipState.Create();
  357. clipState.time = startTime;
  358. clipState.speed = freeze ? 0.0f : 1.0f;
  359. SetState(clip, clipState);
  360. RefreshClipMappings();
  361. break;
  362. }
  363. }
  364. /// <summary>
  365. /// Stops playback of animation whose playback what started using <see cref="EditorPlay"/>.
  366. /// </summary>
  367. internal void EditorStop()
  368. {
  369. switch (state)
  370. {
  371. case State.EditorActive:
  372. SwitchState(State.Inactive);
  373. break;
  374. }
  375. }
  376. /// <summary>
  377. /// Returns the current time of the currently playing editor animation clip.
  378. /// </summary>
  379. /// <returns>Time in seconds.</returns>
  380. internal float EditorGetTime()
  381. {
  382. switch (state)
  383. {
  384. case State.EditorActive:
  385. AnimationClip clip = _native.GetClip(0);
  386. AnimationClipState clipState;
  387. if (clip != null && GetState(clip, out clipState))
  388. return clipState.time;
  389. return 0.0f;
  390. }
  391. return 0.0f;
  392. }
  393. /// <summary>
  394. /// Rebuilds internal curve -> property mapping about the currently playing animation clip. This mapping allows the
  395. /// animation component to know which property to assign which values from an animation curve. This Should be called
  396. /// whenever playback for a new clip starts, or when clip curves change.
  397. /// </summary>
  398. internal void RefreshClipMappings()
  399. {
  400. primaryClip = _native.GetClip(0);
  401. RebuildFloatProperties(primaryClip);
  402. UpdateSceneObjectMapping();
  403. }
  404. /// <summary>
  405. /// Updates generic float properties on relevant objects, based on the most recently evaluated animation curve
  406. /// values.
  407. /// </summary>
  408. internal void UpdateFloatProperties()
  409. {
  410. // Apply values from generic float curves
  411. if (floatProperties != null)
  412. {
  413. foreach (var entry in floatProperties)
  414. {
  415. float curveValue;
  416. if (_native.GetGenericCurveValue(entry.curveIdx, out curveValue))
  417. entry.setter(curveValue);
  418. }
  419. }
  420. }
  421. /// <summary>
  422. /// Searches the scene object hierarchy to find a property at the given path.
  423. /// </summary>
  424. /// <param name="root">Root scene object to which the path is relative to.</param>
  425. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  426. ///
  427. /// Path elements prefixed with "!" signify names of child scene objects (first one relative to
  428. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  429. ///
  430. /// Path element prefixed with ":" signify names of components. If a path doesn't have a
  431. /// component element, it is assumed the field is relative to the scene object itself (only
  432. /// "Translation", "Rotation" and "Scale fields are supported in such case). Only one component
  433. /// path element per path is allowed.
  434. ///
  435. /// Path entries with no prefix are considered regular script object fields. Each path must have
  436. /// at least one such entry. Last field entry can optionally have a suffix separated from the
  437. /// path name with ".". This suffix is not parsed internally, but will be returned as
  438. /// <paramref name="suffix"/>.
  439. ///
  440. /// Path examples:
  441. /// :MyComponent/myInt (path to myInt variable on a component attached to this object)
  442. /// !childSO/:MyComponent/myInt (path to myInt variable on a child scene object)
  443. /// !childSO/Translation (path to the scene object translation)
  444. /// :MyComponent/myVector.z (path to the z component of myVector on this object)
  445. /// </param>
  446. /// <param name="suffix">Suffix of the last field entry, if it has any. Contains the suffix separator ".".</param>
  447. /// <returns>If found, property object you can use for setting and getting the value from the property, otherwise
  448. /// null.</returns>
  449. internal static SerializableProperty FindProperty(SceneObject root, string path, out string suffix)
  450. {
  451. suffix = null;
  452. if (string.IsNullOrEmpty(path) || root == null)
  453. return null;
  454. string trimmedPath = path.Trim('/');
  455. string[] entries = trimmedPath.Split('/');
  456. // Find scene object referenced by the path
  457. SceneObject so = root;
  458. int pathIdx = 0;
  459. for (; pathIdx < entries.Length; pathIdx++)
  460. {
  461. string entry = entries[pathIdx];
  462. if (string.IsNullOrEmpty(entry))
  463. continue;
  464. // Not a scene object, break
  465. if (entry[0] != '!')
  466. break;
  467. string childName = entry.Substring(1, entry.Length - 1);
  468. so = so.FindChild(childName);
  469. if (so == null)
  470. break;
  471. }
  472. // Child scene object couldn't be found
  473. if (so == null)
  474. return null;
  475. // Path too short, no field entry
  476. if (pathIdx >= entries.Length)
  477. return null;
  478. // Check if path is referencing a component, and if so find it
  479. Component component = null;
  480. {
  481. string entry = entries[pathIdx];
  482. if (entry[0] == ':')
  483. {
  484. string componentName = entry.Substring(1, entry.Length - 1);
  485. Component[] components = so.GetComponents();
  486. component = Array.Find(components, x => x.GetType().Name == componentName);
  487. // Cannot find component with specified type
  488. if (component == null)
  489. return null;
  490. }
  491. }
  492. // Look for a field within a component
  493. if (component != null)
  494. {
  495. pathIdx++;
  496. if (pathIdx >= entries.Length)
  497. return null;
  498. SerializableObject componentObj = new SerializableObject(component);
  499. StringBuilder pathBuilder = new StringBuilder();
  500. for (; pathIdx < entries.Length - 1; pathIdx++)
  501. pathBuilder.Append(entries[pathIdx] + "/");
  502. // Check last path entry for suffix and remove it
  503. int suffixIdx = entries[pathIdx].LastIndexOf(".");
  504. if (suffixIdx != -1)
  505. {
  506. string entryNoSuffix = entries[pathIdx].Substring(0, suffixIdx);
  507. suffix = entries[pathIdx].Substring(suffixIdx, entries[pathIdx].Length - suffixIdx);
  508. pathBuilder.Append(entryNoSuffix);
  509. }
  510. else
  511. pathBuilder.Append(entries[pathIdx]);
  512. return componentObj.FindProperty(pathBuilder.ToString());
  513. }
  514. else // Field is one of the builtin ones on the SceneObject itself
  515. {
  516. if ((pathIdx + 1) < entries.Length)
  517. return null;
  518. string entry = entries[pathIdx];
  519. if (entry == "Position")
  520. {
  521. SerializableProperty property = new SerializableProperty(
  522. SerializableProperty.FieldType.Vector3,
  523. typeof(Vector3),
  524. () => so.LocalPosition,
  525. (x) => so.LocalPosition = (Vector3)x);
  526. return property;
  527. }
  528. else if (entry == "Rotation")
  529. {
  530. SerializableProperty property = new SerializableProperty(
  531. SerializableProperty.FieldType.Vector3,
  532. typeof(Vector3),
  533. () => so.LocalRotation.ToEuler(),
  534. (x) => so.LocalRotation = Quaternion.FromEuler((Vector3)x));
  535. return property;
  536. }
  537. else if (entry == "Scale")
  538. {
  539. SerializableProperty property = new SerializableProperty(
  540. SerializableProperty.FieldType.Vector3,
  541. typeof(Vector3),
  542. () => so.LocalScale,
  543. (x) => so.LocalScale = (Vector3)x);
  544. return property;
  545. }
  546. return null;
  547. }
  548. }
  549. /// <summary>
  550. /// Searches the scene object hierarchy to find a child scene object using the provided path.
  551. /// </summary>
  552. /// <param name="root">Root scene object to which the path is relative to.</param>
  553. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  554. ///
  555. /// Path elements signify names of child scene objects (first one relative to
  556. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  557. /// Elements must be prefixed with "!" in order to match the path format of
  558. /// <see cref="FindProperty"/>.</param>
  559. /// <returns>Child scene object if found, or null otherwise.</returns>
  560. internal static SceneObject FindSceneObject(SceneObject root, string path)
  561. {
  562. if (string.IsNullOrEmpty(path) || root == null)
  563. return null;
  564. string trimmedPath = path.Trim('/');
  565. string[] entries = trimmedPath.Split('/');
  566. // Find scene object referenced by the path
  567. SceneObject so = root;
  568. int pathIdx = 0;
  569. for (; pathIdx < entries.Length; pathIdx++)
  570. {
  571. string entry = entries[pathIdx];
  572. if (string.IsNullOrEmpty(entry))
  573. continue;
  574. // Not a scene object, break
  575. if (entry[0] != '!')
  576. break;
  577. string childName = entry.Substring(1, entry.Length - 1);
  578. so = so.FindChild(childName);
  579. if (so == null)
  580. break;
  581. }
  582. return so;
  583. }
  584. private void OnInitialize()
  585. {
  586. NotifyFlags = TransformChangedFlags.Transform;
  587. }
  588. private void OnEnable()
  589. {
  590. switch (state)
  591. {
  592. case State.Inactive:
  593. SwitchState(State.Active);
  594. break;
  595. case State.EditorActive:
  596. SwitchState(State.Inactive);
  597. SwitchState(State.Active);
  598. break;
  599. }
  600. }
  601. private void OnDisable()
  602. {
  603. switch (state)
  604. {
  605. case State.Active:
  606. case State.EditorActive:
  607. SwitchState(State.Inactive);
  608. break;
  609. }
  610. }
  611. private void OnDestroy()
  612. {
  613. switch (state)
  614. {
  615. case State.Active:
  616. case State.EditorActive:
  617. SwitchState(State.Inactive);
  618. break;
  619. }
  620. }
  621. private void OnUpdate()
  622. {
  623. switch (state)
  624. {
  625. case State.Active:
  626. AnimationClip newPrimaryClip = _native.GetClip(0);
  627. if (newPrimaryClip != primaryClip)
  628. RefreshClipMappings();
  629. UpdateFloatProperties();
  630. break;
  631. }
  632. }
  633. private void OnTransformChanged(TransformChangedFlags flags)
  634. {
  635. if (!SceneObject.Active)
  636. return;
  637. if ((flags & (TransformChangedFlags.Transform)) != 0)
  638. UpdateBounds(false);
  639. }
  640. /// <summary>
  641. /// Changes the state of the animation state machine. Doesn't check for valid transitions.
  642. /// </summary>
  643. /// <param name="state">New state of the animation.</param>
  644. private void SwitchState(State state)
  645. {
  646. this.state = state;
  647. switch (state)
  648. {
  649. case State.Active:
  650. if (_native != null)
  651. _native.Destroy();
  652. _native = new NativeAnimation();
  653. _native.OnEventTriggered += EventTriggered;
  654. animatedRenderable = SceneObject.GetComponent<Renderable>();
  655. // Restore saved values after reset
  656. _native.WrapMode = serializableData.wrapMode;
  657. _native.Speed = serializableData.speed;
  658. _native.Cull = serializableData.cull;
  659. UpdateBounds();
  660. if (serializableData.defaultClip != null)
  661. _native.Play(serializableData.defaultClip);
  662. primaryClip = _native.GetClip(0);
  663. if (primaryClip != null)
  664. RebuildFloatProperties(primaryClip);
  665. SetBoneMappings();
  666. UpdateSceneObjectMapping();
  667. if (animatedRenderable != null)
  668. animatedRenderable.RegisterAnimation(this);
  669. break;
  670. case State.EditorActive:
  671. if (_native != null)
  672. _native.Destroy();
  673. _native = new NativeAnimation();
  674. animatedRenderable = SceneObject.GetComponent<Renderable>();
  675. UpdateBounds();
  676. SetBoneMappings();
  677. if (animatedRenderable != null)
  678. animatedRenderable.RegisterAnimation(this);
  679. break;
  680. case State.Inactive:
  681. if (animatedRenderable != null)
  682. animatedRenderable.UnregisterAnimation();
  683. if (_native != null)
  684. {
  685. _native.Destroy();
  686. _native = null;
  687. }
  688. primaryClip = null;
  689. mappingInfo.Clear();
  690. floatProperties = null;
  691. break;
  692. }
  693. }
  694. /// <summary>
  695. /// Finds any curves that affect a transform of a specific scene object, and ensures that animation properly updates
  696. /// those transforms. This does not include curves referencing bones.
  697. /// </summary>
  698. private void UpdateSceneObjectMapping()
  699. {
  700. List<SceneObjectMappingInfo> newMappingInfos = new List<SceneObjectMappingInfo>();
  701. foreach(var entry in mappingInfo)
  702. {
  703. if (entry.isMappedToBone)
  704. newMappingInfos.Add(entry);
  705. else
  706. _native.UnmapSceneObject(entry.sceneObject);
  707. }
  708. if (primaryClip != null)
  709. {
  710. SceneObject root = SceneObject;
  711. Action<NamedVector3Curve[]> findMappings = x =>
  712. {
  713. foreach (var curve in x)
  714. {
  715. if (curve.Flags.HasFlag(AnimationCurveFlags.ImportedCurve))
  716. continue;
  717. SceneObject currentSO = FindSceneObject(root, curve.Name);
  718. bool found = false;
  719. for (int i = 0; i < newMappingInfos.Count; i++)
  720. {
  721. if (newMappingInfos[i].sceneObject == currentSO)
  722. {
  723. found = true;
  724. break;
  725. }
  726. }
  727. if (!found)
  728. {
  729. SceneObjectMappingInfo newMappingInfo = new SceneObjectMappingInfo();
  730. newMappingInfo.isMappedToBone = false;
  731. newMappingInfo.sceneObject = currentSO;
  732. newMappingInfos.Add(newMappingInfo);
  733. _native.MapCurveToSceneObject(curve.Name, currentSO);
  734. }
  735. }
  736. };
  737. AnimationCurves curves = primaryClip.Curves;
  738. findMappings(curves.PositionCurves);
  739. findMappings(curves.RotationCurves);
  740. findMappings(curves.ScaleCurves);
  741. }
  742. mappingInfo = newMappingInfos;
  743. }
  744. /// <summary>
  745. /// Registers a new bone component, creating a new transform mapping from the bone name to the scene object
  746. /// the component is attached to.
  747. /// </summary>
  748. /// <param name="bone">Bone component to register.</param>
  749. internal void AddBone(Bone bone)
  750. {
  751. switch (state)
  752. {
  753. case State.Active:
  754. SceneObject currentSO = bone.SceneObject;
  755. SceneObjectMappingInfo newMapping = new SceneObjectMappingInfo();
  756. newMapping.sceneObject = currentSO;
  757. newMapping.isMappedToBone = true;
  758. newMapping.bone = bone;
  759. mappingInfo.Add(newMapping);
  760. _native.MapCurveToSceneObject(bone.Name, newMapping.sceneObject);
  761. break;
  762. }
  763. }
  764. /// <summary>
  765. /// Unregisters a bone component, removing the bone -> scene object mapping.
  766. /// </summary>
  767. /// <param name="bone">Bone to unregister.</param>
  768. internal void RemoveBone(Bone bone)
  769. {
  770. switch (state)
  771. {
  772. case State.Active:
  773. for (int i = 0; i < mappingInfo.Count; i++)
  774. {
  775. if (mappingInfo[i].bone == bone)
  776. {
  777. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  778. mappingInfo.RemoveAt(i);
  779. i--;
  780. }
  781. }
  782. break;
  783. }
  784. }
  785. /// <summary>
  786. /// Called whenever the bone the <see cref="Bone"/> component points to changed.
  787. /// </summary>
  788. /// <param name="bone">Bone component to modify.</param>
  789. internal void NotifyBoneChanged(Bone bone)
  790. {
  791. switch (state)
  792. {
  793. case State.Active:
  794. for (int i = 0; i < mappingInfo.Count; i++)
  795. {
  796. if (mappingInfo[i].bone == bone)
  797. {
  798. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  799. _native.MapCurveToSceneObject(bone.Name, mappingInfo[i].sceneObject);
  800. break;
  801. }
  802. }
  803. break;
  804. }
  805. }
  806. /// <summary>
  807. /// Finds any scene objects that are mapped to bone transforms. Such object's transforms will be affected by
  808. /// skeleton bone animation.
  809. /// </summary>
  810. private void SetBoneMappings()
  811. {
  812. mappingInfo.Clear();
  813. SceneObjectMappingInfo rootMapping = new SceneObjectMappingInfo();
  814. rootMapping.sceneObject = SceneObject;
  815. rootMapping.isMappedToBone = true;
  816. mappingInfo.Add(rootMapping);
  817. _native.MapCurveToSceneObject("", rootMapping.sceneObject);
  818. Bone[] childBones = FindChildBones();
  819. foreach (var entry in childBones)
  820. AddBone(entry);
  821. }
  822. /// <summary>
  823. /// Searches child scene objects for <see cref="Bone"/> components and returns any found ones.
  824. /// </summary>
  825. private Bone[] FindChildBones()
  826. {
  827. Stack<SceneObject> todo = new Stack<SceneObject>();
  828. todo.Push(SceneObject);
  829. List<Bone> bones = new List<Bone>();
  830. while (todo.Count > 0)
  831. {
  832. SceneObject currentSO = todo.Pop();
  833. Bone bone = currentSO.GetComponent<Bone>();
  834. if (bone != null)
  835. {
  836. bone.SetParent(this, true);
  837. bones.Add(bone);
  838. }
  839. int childCount = currentSO.GetNumChildren();
  840. for (int i = 0; i < childCount; i++)
  841. {
  842. SceneObject child = currentSO.GetChild(i);
  843. if (child.GetComponent<Animation>() != null)
  844. continue;
  845. todo.Push(child);
  846. }
  847. }
  848. return bones.ToArray();
  849. }
  850. /// <summary>
  851. /// Re-applies the bounds to the internal animation object, and the relevant renderable object if one exists.
  852. /// </summary>
  853. internal void UpdateBounds(bool updateRenderable = true)
  854. {
  855. NativeRenderable renderable = null;
  856. if (updateRenderable && animatedRenderable != null)
  857. renderable = animatedRenderable.Native;
  858. if (serializableData.useBounds)
  859. {
  860. if (renderable != null)
  861. {
  862. renderable.UseOverrideBounds = true;
  863. renderable.OverrideBounds = serializableData.bounds;
  864. }
  865. if (_native != null)
  866. {
  867. AABox bounds = serializableData.bounds;
  868. Matrix4 parentTfrm;
  869. if (SceneObject.Parent != null)
  870. parentTfrm = SceneObject.Parent.WorldTransform;
  871. else
  872. parentTfrm = Matrix4.Identity;
  873. bounds.TransformAffine(parentTfrm);
  874. _native.Bounds = bounds;
  875. }
  876. }
  877. else
  878. {
  879. if (renderable != null)
  880. renderable.UseOverrideBounds = false;
  881. if (_native != null)
  882. {
  883. AABox bounds = new AABox();
  884. if (animatedRenderable != null)
  885. bounds = animatedRenderable.Bounds.Box;
  886. _native.Bounds = bounds;
  887. }
  888. }
  889. }
  890. /// <summary>
  891. /// Registers an <see cref="Renderable"/> component with the animation. When registered the animation will use the
  892. /// renderable's bounds for culling, and the animation override bounds will be applied to the renderable.
  893. /// </summary>
  894. /// <param name="renderable">Component that was added</param>
  895. internal void RegisterRenderable(Renderable renderable)
  896. {
  897. animatedRenderable = renderable;
  898. UpdateBounds();
  899. }
  900. /// <summary>
  901. /// Removes renderable from the animation component. <see cref="RegisterRenderable"/>.
  902. /// </summary>
  903. internal void UnregisterRenderable()
  904. {
  905. animatedRenderable = null;
  906. }
  907. /// <summary>
  908. /// Builds a list of properties that will be animated using float animation curves.
  909. /// </summary>
  910. /// <param name="clip">Clip to retrieve the float animation curves from.</param>
  911. private void RebuildFloatProperties(AnimationClip clip)
  912. {
  913. if (clip == null)
  914. {
  915. floatProperties = null;
  916. return;
  917. }
  918. AnimationCurves curves = clip.Curves;
  919. List<FloatCurvePropertyInfo> newFloatProperties = new List<FloatCurvePropertyInfo>();
  920. for (int i = 0; i < curves.FloatCurves.Length; i++)
  921. {
  922. string suffix;
  923. SerializableProperty property = FindProperty(SceneObject, curves.FloatCurves[i].Name, out suffix);
  924. if (property == null)
  925. continue;
  926. int elementIdx = 0;
  927. if (!string.IsNullOrEmpty(suffix))
  928. {
  929. PropertySuffixInfo suffixInfo;
  930. if (PropertySuffixInfos.TryGetValue(suffix, out suffixInfo))
  931. elementIdx = suffixInfo.elementIdx;
  932. }
  933. Action<float> setter = null;
  934. Type internalType = property.InternalType;
  935. switch (property.Type)
  936. {
  937. case SerializableProperty.FieldType.Vector2:
  938. if (internalType == typeof(Vector2))
  939. {
  940. setter = f =>
  941. {
  942. Vector2 value = property.GetValue<Vector2>();
  943. value[elementIdx] = f;
  944. property.SetValue(value);
  945. };
  946. }
  947. break;
  948. case SerializableProperty.FieldType.Vector3:
  949. if (internalType == typeof(Vector3))
  950. {
  951. setter = f =>
  952. {
  953. Vector3 value = property.GetValue<Vector3>();
  954. value[elementIdx] = f;
  955. property.SetValue(value);
  956. };
  957. }
  958. break;
  959. case SerializableProperty.FieldType.Vector4:
  960. if (internalType == typeof(Vector4))
  961. {
  962. setter = f =>
  963. {
  964. Vector4 value = property.GetValue<Vector4>();
  965. value[elementIdx] = f;
  966. property.SetValue(value);
  967. };
  968. }
  969. else if (internalType == typeof(Quaternion))
  970. {
  971. setter = f =>
  972. {
  973. Quaternion value = property.GetValue<Quaternion>();
  974. value[elementIdx] = f;
  975. property.SetValue(value);
  976. };
  977. }
  978. break;
  979. case SerializableProperty.FieldType.Color:
  980. if (internalType == typeof(Color))
  981. {
  982. setter = f =>
  983. {
  984. Color value = property.GetValue<Color>();
  985. value[elementIdx] = f;
  986. property.SetValue(value);
  987. };
  988. }
  989. break;
  990. case SerializableProperty.FieldType.Bool:
  991. setter = f =>
  992. {
  993. bool value = f > 0.0f;
  994. property.SetValue(value);
  995. };
  996. break;
  997. case SerializableProperty.FieldType.Int:
  998. setter = f =>
  999. {
  1000. int value = (int)f;
  1001. property.SetValue(value);
  1002. };
  1003. break;
  1004. case SerializableProperty.FieldType.Float:
  1005. setter = f =>
  1006. {
  1007. property.SetValue(f);
  1008. };
  1009. break;
  1010. }
  1011. if (setter == null)
  1012. continue;
  1013. FloatCurvePropertyInfo propertyInfo = new FloatCurvePropertyInfo();
  1014. propertyInfo.curveIdx = i;
  1015. propertyInfo.setter = setter;
  1016. newFloatProperties.Add(propertyInfo);
  1017. }
  1018. floatProperties = newFloatProperties.ToArray();
  1019. }
  1020. /// <summary>
  1021. /// Called whenever an animation event triggers.
  1022. /// </summary>
  1023. /// <param name="clip">Clip that the event originated from.</param>
  1024. /// <param name="name">Name of the event.</param>
  1025. private void EventTriggered(AnimationClip clip, string name)
  1026. {
  1027. // Event should be in format "ComponentType/MethodName"
  1028. if (string.IsNullOrEmpty(name))
  1029. return;
  1030. string[] nameEntries = name.Split('/');
  1031. if (nameEntries.Length != 2)
  1032. return;
  1033. string typeName = nameEntries[0];
  1034. string methodName = nameEntries[1];
  1035. Component[] components = SceneObject.GetComponents();
  1036. for (int i = 0; i < components.Length; i++)
  1037. {
  1038. if (components[i].GetType().Name == typeName)
  1039. {
  1040. components[i].Invoke(methodName);
  1041. break;
  1042. }
  1043. }
  1044. }
  1045. /// <summary>
  1046. /// Holds all data the animation component needs to persist through serialization.
  1047. /// </summary>
  1048. [SerializeObject]
  1049. private class SerializableData
  1050. {
  1051. public AnimationClip defaultClip;
  1052. public AnimWrapMode wrapMode = AnimWrapMode.Loop;
  1053. public float speed = 1.0f;
  1054. public AABox bounds;
  1055. public bool useBounds;
  1056. public bool cull = true;
  1057. }
  1058. /// <summary>
  1059. /// Contains information about a property animated by a generic animation curve.
  1060. /// </summary>
  1061. private class FloatCurvePropertyInfo
  1062. {
  1063. public int curveIdx;
  1064. public Action<float> setter;
  1065. }
  1066. /// <summary>
  1067. /// Information about a suffix used in a property path.
  1068. /// </summary>
  1069. internal struct PropertySuffixInfo
  1070. {
  1071. public PropertySuffixInfo(int elementIdx, bool isVector)
  1072. {
  1073. this.elementIdx = elementIdx;
  1074. this.isVector = isVector;
  1075. }
  1076. public int elementIdx;
  1077. public bool isVector;
  1078. }
  1079. /// <summary>
  1080. /// Information about scene objects bound to a specific animation curve.
  1081. /// </summary>
  1082. internal struct SceneObjectMappingInfo
  1083. {
  1084. public SceneObject sceneObject;
  1085. public bool isMappedToBone;
  1086. public Bone bone;
  1087. }
  1088. /// <summary>
  1089. /// Possible states the animation component can be in.
  1090. /// </summary>
  1091. private enum State
  1092. {
  1093. /// <summary>
  1094. /// Animation object isn't constructed.
  1095. /// </summary>
  1096. Inactive,
  1097. /// <summary>
  1098. /// Animation object is constructed and fully functional.
  1099. /// </summary>
  1100. Active,
  1101. /// <summary>
  1102. /// Animation object is constructed and functional with limited funcionality for editor purposes.
  1103. /// </summary>
  1104. EditorActive
  1105. }
  1106. }
  1107. /// <summary>
  1108. /// Determines how an animation clip behaves when it reaches the end.
  1109. /// </summary>
  1110. public enum AnimWrapMode // Note: Must match C++ enum AnimWrapMode
  1111. {
  1112. /// <summary>
  1113. /// Loop around to the beginning/end when the last/first frame is reached.
  1114. /// </summary>
  1115. Loop,
  1116. /// <summary>
  1117. /// Clamp to end/beginning, keeping the last/first frame active.
  1118. /// </summary>
  1119. Clamp
  1120. }
  1121. /// <summary>
  1122. /// Represents an animation clip used in 1D blending. Each clip has a position on the number line.
  1123. /// </summary>
  1124. public class BlendClipInfo
  1125. {
  1126. public AnimationClip clip;
  1127. public float position;
  1128. }
  1129. /// <summary>
  1130. /// Defines a 1D blend where two animation clips are blended between each other using linear interpolation.
  1131. /// </summary>
  1132. public class Blend1DInfo
  1133. {
  1134. public Blend1DInfo()
  1135. { }
  1136. public Blend1DInfo(int numClips)
  1137. {
  1138. clips = new BlendClipInfo[numClips];
  1139. }
  1140. public BlendClipInfo[] clips;
  1141. }
  1142. /// <summary>
  1143. /// Defines a 2D blend where two animation clips are blended between each other using bilinear interpolation.
  1144. /// </summary>
  1145. public class Blend2DInfo
  1146. {
  1147. public AnimationClip topLeftClip;
  1148. public AnimationClip topRightClip;
  1149. public AnimationClip botLeftClip;
  1150. public AnimationClip botRightClip;
  1151. }
  1152. /// <summary>
  1153. /// Contains information about a currently playing animation clip.
  1154. /// </summary>
  1155. [StructLayout(LayoutKind.Sequential), SerializeObject]
  1156. public struct AnimationClipState // Note: Must match C++ struct AnimationClipState
  1157. {
  1158. /// <summary>
  1159. /// Layer the clip is playing on. Multiple clips can be played simulatenously on different layers.
  1160. /// </summary>
  1161. public int layer;
  1162. /// <summary>
  1163. /// Current time the animation is playing from.
  1164. /// </summary>
  1165. public float time;
  1166. /// <summary>
  1167. /// Speed at which the animation is playing.
  1168. /// </summary>
  1169. public float speed;
  1170. /// <summary>
  1171. /// Determines how much of an influence does the clip have on the final pose.
  1172. /// </summary>
  1173. public float weight;
  1174. /// <summary>
  1175. /// Determines what happens to other animation clips when a new clip starts playing.
  1176. /// </summary>
  1177. public AnimWrapMode wrapMode;
  1178. /// <summary>
  1179. /// Creates a new clip state, with default values initialized.
  1180. /// </summary>
  1181. /// <returns>New animation clip state.</returns>
  1182. public static AnimationClipState Create()
  1183. {
  1184. AnimationClipState state = new AnimationClipState();
  1185. state.speed = 1.0f;
  1186. state.weight = 1.0f;
  1187. state.wrapMode = AnimWrapMode.Loop;
  1188. return state;
  1189. }
  1190. }
  1191. /** @} */
  1192. }