Animation.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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. /// Samples an animation clip at the specified time, displaying only that particular frame without further playback.
  272. /// </summary>
  273. /// <param name="clip">Animation clip to sample.</param>
  274. /// <param name="time">Time to sample the clip at.</param>
  275. public void Sample(AnimationClip clip, float time)
  276. {
  277. switch (state)
  278. {
  279. case State.Active:
  280. case State.EditorActive:
  281. _native.Sample(clip, time);
  282. break;
  283. }
  284. }
  285. /// <summary>
  286. /// Stops playing all animations on the provided layer.
  287. /// </summary>
  288. /// <param name="layer">Layer on which to stop animations on.</param>
  289. public void Stop(int layer)
  290. {
  291. switch (state)
  292. {
  293. case State.Active:
  294. _native.Stop(layer);
  295. break;
  296. }
  297. }
  298. /// <summary>
  299. /// Stops playing all animations.
  300. /// </summary>
  301. public void StopAll()
  302. {
  303. switch (state)
  304. {
  305. case State.Active:
  306. _native.StopAll();
  307. break;
  308. }
  309. }
  310. /// <summary>
  311. /// Retrieves detailed information about a currently playing animation clip.
  312. /// </summary>
  313. /// <param name="clip">Clip to retrieve the information for.</param>
  314. /// <param name="state">Animation clip state containing the requested information. Only valid if the method returns
  315. /// true.</param>
  316. /// <returns>True if the state was found (animation clip is playing), false otherwise.</returns>
  317. public bool GetState(AnimationClip clip, out AnimationClipState state)
  318. {
  319. switch (this.state)
  320. {
  321. case State.Active:
  322. case State.EditorActive:
  323. return _native.GetState(clip, out state);
  324. default:
  325. state = new AnimationClipState();
  326. return false;
  327. }
  328. }
  329. /// <summary>
  330. /// Changes the state of a playing animation clip. If animation clip is not currently playing the state change is
  331. /// ignored.
  332. /// </summary>
  333. /// <param name="clip">Clip to change the state for.</param>
  334. /// <param name="state">New state of the animation (e.g. changing the time for seeking).</param>
  335. public void SetState(AnimationClip clip, AnimationClipState state)
  336. {
  337. switch (this.state)
  338. {
  339. case State.Active:
  340. case State.EditorActive:
  341. _native.SetState(clip, state);
  342. break;
  343. }
  344. }
  345. /// <summary>
  346. /// Changes a weight of a single morph channel, determining how much of it to apply on top of the base mesh.
  347. /// </summary>
  348. /// <param name="name">Name of the morph channel to modify the weight for. This depends on the mesh the animation
  349. /// is currently animating.</param>
  350. /// <param name="weight">Weight that determines how much of the channel to apply to the mesh, in range[0, 1].
  351. /// </param>
  352. public void SetMorphChannelWeight(string name, float weight)
  353. {
  354. switch (state)
  355. {
  356. case State.Active:
  357. if (animatedRenderable == null)
  358. return;
  359. Mesh mesh = animatedRenderable.Mesh;
  360. if (mesh == null)
  361. return;
  362. MorphShapes morphShapes = mesh.MorphShapes;
  363. if (morphShapes == null)
  364. return;
  365. MorphChannel[] channels = morphShapes.Channels;
  366. for (int i = 0; i < channels.Length; i++)
  367. {
  368. if (channels[i].Name == name)
  369. {
  370. _native.SetMorphChannelWeight(i, weight);
  371. break;
  372. }
  373. }
  374. break;
  375. }
  376. }
  377. /// <summary>
  378. /// Allows the caller to play an animation clip during edit mode. This form of animation playback is limited as
  379. /// you have no control over clip properties, and features like blending, cross fade or animation events are not
  380. /// supported.
  381. ///
  382. /// Caller will need to manually call <see cref="UpdateFloatProperties"/> in order to apply evaluated animation data
  383. /// to relevant float properties (if required).
  384. ///
  385. /// Caller will also need to manually call <see cref="RefreshClipMappings"/> whenever the curves internal to the
  386. /// animation clip change. This should be called before the call to <see cref="UpdateFloatProperties"/>.
  387. /// </summary>
  388. /// <param name="clip">Animation clip to play.</param>
  389. /// <param name="startTime">Time to start playing at, in seconds.</param>
  390. /// <param name="freeze">If true, only the frame at the specified time will be shown, without advancing the
  391. /// animation.</param>
  392. internal void EditorPlay(AnimationClip clip, float startTime, bool freeze = false)
  393. {
  394. switch (state)
  395. {
  396. case State.Inactive:
  397. SwitchState(State.EditorActive);
  398. break;
  399. }
  400. switch (state)
  401. {
  402. case State.EditorActive:
  403. if (freeze)
  404. Sample(clip, startTime);
  405. else
  406. {
  407. AnimationClipState clipState = AnimationClipState.Create();
  408. clipState.time = startTime;
  409. SetState(clip, clipState);
  410. }
  411. RefreshClipMappings();
  412. break;
  413. }
  414. }
  415. /// <summary>
  416. /// Stops playback of animation whose playback what started using <see cref="EditorPlay"/>.
  417. /// </summary>
  418. internal void EditorStop()
  419. {
  420. switch (state)
  421. {
  422. case State.EditorActive:
  423. SwitchState(State.Inactive);
  424. break;
  425. }
  426. }
  427. /// <summary>
  428. /// Returns the current time of the currently playing editor animation clip.
  429. /// </summary>
  430. /// <returns>Time in seconds.</returns>
  431. internal float EditorGetTime()
  432. {
  433. switch (state)
  434. {
  435. case State.EditorActive:
  436. AnimationClip clip = _native.GetClip(0);
  437. AnimationClipState clipState;
  438. if (clip != null && GetState(clip, out clipState))
  439. return clipState.time;
  440. return 0.0f;
  441. }
  442. return 0.0f;
  443. }
  444. /// <summary>
  445. /// Rebuilds internal curve -> property mapping about the currently playing animation clip. This mapping allows the
  446. /// animation component to know which property to assign which values from an animation curve. This Should be called
  447. /// whenever playback for a new clip starts, or when clip curves change.
  448. /// </summary>
  449. internal void RefreshClipMappings()
  450. {
  451. primaryClip = _native.GetClip(0);
  452. RebuildFloatProperties(primaryClip);
  453. UpdateSceneObjectMapping();
  454. }
  455. /// <summary>
  456. /// Updates generic float properties on relevant objects, based on the most recently evaluated animation curve
  457. /// values.
  458. /// </summary>
  459. internal void UpdateFloatProperties()
  460. {
  461. // Apply values from generic float curves
  462. if (floatProperties != null)
  463. {
  464. foreach (var entry in floatProperties)
  465. {
  466. float curveValue;
  467. if (_native.GetGenericCurveValue(entry.curveIdx, out curveValue))
  468. entry.setter(curveValue);
  469. }
  470. }
  471. }
  472. /// <summary>
  473. /// Searches the scene object hierarchy to find a property at the given path.
  474. /// </summary>
  475. /// <param name="root">Root scene object to which the path is relative to.</param>
  476. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  477. ///
  478. /// Path elements prefixed with "!" signify names of child scene objects (first one relative to
  479. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  480. ///
  481. /// Path element prefixed with ":" signify names of components. If a path doesn't have a
  482. /// component element, it is assumed the field is relative to the scene object itself (only
  483. /// "Translation", "Rotation" and "Scale fields are supported in such case). Only one component
  484. /// path element per path is allowed.
  485. ///
  486. /// Path entries with no prefix are considered regular script object fields. Each path must have
  487. /// at least one such entry. Last field entry can optionally have a suffix separated from the
  488. /// path name with ".". This suffix is not parsed internally, but will be returned as
  489. /// <paramref name="suffix"/>.
  490. ///
  491. /// Path examples:
  492. /// :MyComponent/myInt (path to myInt variable on a component attached to this object)
  493. /// !childSO/:MyComponent/myInt (path to myInt variable on a child scene object)
  494. /// !childSO/Translation (path to the scene object translation)
  495. /// :MyComponent/myVector.z (path to the z component of myVector on this object)
  496. /// </param>
  497. /// <param name="suffix">Suffix of the last field entry, if it has any. Contains the suffix separator ".".</param>
  498. /// <returns>If found, property object you can use for setting and getting the value from the property, otherwise
  499. /// null.</returns>
  500. internal static SerializableProperty FindProperty(SceneObject root, string path, out string suffix)
  501. {
  502. suffix = null;
  503. if (string.IsNullOrEmpty(path) || root == null)
  504. return null;
  505. string trimmedPath = path.Trim('/');
  506. string[] entries = trimmedPath.Split('/');
  507. // Find scene object referenced by the path
  508. SceneObject so = root;
  509. int pathIdx = 0;
  510. for (; pathIdx < entries.Length; pathIdx++)
  511. {
  512. string entry = entries[pathIdx];
  513. if (string.IsNullOrEmpty(entry))
  514. continue;
  515. // Not a scene object, break
  516. if (entry[0] != '!')
  517. break;
  518. string childName = entry.Substring(1, entry.Length - 1);
  519. so = so.FindChild(childName);
  520. if (so == null)
  521. break;
  522. }
  523. // Child scene object couldn't be found
  524. if (so == null)
  525. return null;
  526. // Path too short, no field entry
  527. if (pathIdx >= entries.Length)
  528. return null;
  529. // Check if path is referencing a component, and if so find it
  530. Component component = null;
  531. {
  532. string entry = entries[pathIdx];
  533. if (entry[0] == ':')
  534. {
  535. string componentName = entry.Substring(1, entry.Length - 1);
  536. Component[] components = so.GetComponents();
  537. component = Array.Find(components, x => x.GetType().Name == componentName);
  538. // Cannot find component with specified type
  539. if (component == null)
  540. return null;
  541. }
  542. }
  543. // Look for a field within a component
  544. if (component != null)
  545. {
  546. pathIdx++;
  547. if (pathIdx >= entries.Length)
  548. return null;
  549. SerializableObject componentObj = new SerializableObject(component);
  550. StringBuilder pathBuilder = new StringBuilder();
  551. for (; pathIdx < entries.Length - 1; pathIdx++)
  552. pathBuilder.Append(entries[pathIdx] + "/");
  553. // Check last path entry for suffix and remove it
  554. int suffixIdx = entries[pathIdx].LastIndexOf(".");
  555. if (suffixIdx != -1)
  556. {
  557. string entryNoSuffix = entries[pathIdx].Substring(0, suffixIdx);
  558. suffix = entries[pathIdx].Substring(suffixIdx, entries[pathIdx].Length - suffixIdx);
  559. pathBuilder.Append(entryNoSuffix);
  560. }
  561. else
  562. pathBuilder.Append(entries[pathIdx]);
  563. return componentObj.FindProperty(pathBuilder.ToString());
  564. }
  565. else // Field is one of the builtin ones on the SceneObject itself
  566. {
  567. if ((pathIdx + 1) < entries.Length)
  568. return null;
  569. string entry = entries[pathIdx];
  570. if (entry == "Position")
  571. {
  572. SerializableProperty property = new SerializableProperty(
  573. SerializableProperty.FieldType.Vector3,
  574. typeof(Vector3),
  575. () => so.LocalPosition,
  576. (x) => so.LocalPosition = (Vector3)x);
  577. return property;
  578. }
  579. else if (entry == "Rotation")
  580. {
  581. SerializableProperty property = new SerializableProperty(
  582. SerializableProperty.FieldType.Vector3,
  583. typeof(Vector3),
  584. () => so.LocalRotation.ToEuler(),
  585. (x) => so.LocalRotation = Quaternion.FromEuler((Vector3)x));
  586. return property;
  587. }
  588. else if (entry == "Scale")
  589. {
  590. SerializableProperty property = new SerializableProperty(
  591. SerializableProperty.FieldType.Vector3,
  592. typeof(Vector3),
  593. () => so.LocalScale,
  594. (x) => so.LocalScale = (Vector3)x);
  595. return property;
  596. }
  597. return null;
  598. }
  599. }
  600. /// <summary>
  601. /// Searches the scene object hierarchy to find a child scene object using the provided path.
  602. /// </summary>
  603. /// <param name="root">Root scene object to which the path is relative to.</param>
  604. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  605. ///
  606. /// Path elements signify names of child scene objects (first one relative to
  607. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  608. /// Elements must be prefixed with "!" in order to match the path format of
  609. /// <see cref="FindProperty"/>.</param>
  610. /// <returns>Child scene object if found, or null otherwise.</returns>
  611. internal static SceneObject FindSceneObject(SceneObject root, string path)
  612. {
  613. if (string.IsNullOrEmpty(path) || root == null)
  614. return null;
  615. string trimmedPath = path.Trim('/');
  616. string[] entries = trimmedPath.Split('/');
  617. // Find scene object referenced by the path
  618. SceneObject so = root;
  619. int pathIdx = 0;
  620. for (; pathIdx < entries.Length; pathIdx++)
  621. {
  622. string entry = entries[pathIdx];
  623. if (string.IsNullOrEmpty(entry))
  624. continue;
  625. // Not a scene object, break
  626. if (entry[0] != '!')
  627. break;
  628. string childName = entry.Substring(1, entry.Length - 1);
  629. so = so.FindChild(childName);
  630. if (so == null)
  631. break;
  632. }
  633. return so;
  634. }
  635. private void OnInitialize()
  636. {
  637. NotifyFlags = TransformChangedFlags.Transform;
  638. }
  639. private void OnEnable()
  640. {
  641. switch (state)
  642. {
  643. case State.Inactive:
  644. SwitchState(State.Active);
  645. break;
  646. case State.EditorActive:
  647. SwitchState(State.Inactive);
  648. SwitchState(State.Active);
  649. break;
  650. }
  651. }
  652. private void OnDisable()
  653. {
  654. switch (state)
  655. {
  656. case State.Active:
  657. case State.EditorActive:
  658. SwitchState(State.Inactive);
  659. break;
  660. }
  661. }
  662. private void OnDestroy()
  663. {
  664. switch (state)
  665. {
  666. case State.Active:
  667. case State.EditorActive:
  668. SwitchState(State.Inactive);
  669. break;
  670. }
  671. }
  672. private void OnUpdate()
  673. {
  674. switch (state)
  675. {
  676. case State.Active:
  677. AnimationClip newPrimaryClip = _native.GetClip(0);
  678. if (newPrimaryClip != primaryClip)
  679. RefreshClipMappings();
  680. UpdateFloatProperties();
  681. break;
  682. }
  683. }
  684. private void OnTransformChanged(TransformChangedFlags flags)
  685. {
  686. if (!SceneObject.Active)
  687. return;
  688. if ((flags & (TransformChangedFlags.Transform)) != 0)
  689. UpdateBounds(false);
  690. }
  691. /// <summary>
  692. /// Changes the state of the animation state machine. Doesn't check for valid transitions.
  693. /// </summary>
  694. /// <param name="state">New state of the animation.</param>
  695. private void SwitchState(State state)
  696. {
  697. this.state = state;
  698. switch (state)
  699. {
  700. case State.Active:
  701. if (_native != null)
  702. _native.Destroy();
  703. _native = new NativeAnimation();
  704. _native.OnEventTriggered += EventTriggered;
  705. animatedRenderable = SceneObject.GetComponent<Renderable>();
  706. // Restore saved values after reset
  707. _native.WrapMode = serializableData.wrapMode;
  708. _native.Speed = serializableData.speed;
  709. _native.Cull = serializableData.cull;
  710. UpdateBounds();
  711. if (serializableData.defaultClip != null)
  712. _native.Play(serializableData.defaultClip);
  713. primaryClip = _native.GetClip(0);
  714. if (primaryClip != null)
  715. RebuildFloatProperties(primaryClip);
  716. SetBoneMappings();
  717. UpdateSceneObjectMapping();
  718. if (animatedRenderable != null)
  719. animatedRenderable.RegisterAnimation(this);
  720. break;
  721. case State.EditorActive:
  722. if (_native != null)
  723. _native.Destroy();
  724. _native = new NativeAnimation();
  725. animatedRenderable = SceneObject.GetComponent<Renderable>();
  726. UpdateBounds();
  727. SetBoneMappings();
  728. if (animatedRenderable != null)
  729. animatedRenderable.RegisterAnimation(this);
  730. break;
  731. case State.Inactive:
  732. if (animatedRenderable != null)
  733. animatedRenderable.UnregisterAnimation();
  734. if (_native != null)
  735. {
  736. _native.Destroy();
  737. _native = null;
  738. }
  739. primaryClip = null;
  740. mappingInfo.Clear();
  741. floatProperties = null;
  742. break;
  743. }
  744. }
  745. /// <summary>
  746. /// Finds any curves that affect a transform of a specific scene object, and ensures that animation properly updates
  747. /// those transforms. This does not include curves referencing bones.
  748. /// </summary>
  749. private void UpdateSceneObjectMapping()
  750. {
  751. List<SceneObjectMappingInfo> newMappingInfos = new List<SceneObjectMappingInfo>();
  752. foreach(var entry in mappingInfo)
  753. {
  754. if (entry.isMappedToBone)
  755. newMappingInfos.Add(entry);
  756. else
  757. _native.UnmapSceneObject(entry.sceneObject);
  758. }
  759. if (primaryClip != null)
  760. {
  761. SceneObject root = SceneObject;
  762. Action<NamedVector3Curve[]> findMappings = x =>
  763. {
  764. foreach (var curve in x)
  765. {
  766. if (curve.Flags.HasFlag(AnimationCurveFlags.ImportedCurve))
  767. continue;
  768. SceneObject currentSO = FindSceneObject(root, curve.Name);
  769. bool found = false;
  770. for (int i = 0; i < newMappingInfos.Count; i++)
  771. {
  772. if (newMappingInfos[i].sceneObject == currentSO)
  773. {
  774. found = true;
  775. break;
  776. }
  777. }
  778. if (!found)
  779. {
  780. SceneObjectMappingInfo newMappingInfo = new SceneObjectMappingInfo();
  781. newMappingInfo.isMappedToBone = false;
  782. newMappingInfo.sceneObject = currentSO;
  783. newMappingInfos.Add(newMappingInfo);
  784. _native.MapCurveToSceneObject(curve.Name, currentSO);
  785. }
  786. }
  787. };
  788. AnimationCurves curves = primaryClip.Curves;
  789. findMappings(curves.PositionCurves);
  790. findMappings(curves.RotationCurves);
  791. findMappings(curves.ScaleCurves);
  792. }
  793. mappingInfo = newMappingInfos;
  794. }
  795. /// <summary>
  796. /// Registers a new bone component, creating a new transform mapping from the bone name to the scene object
  797. /// the component is attached to.
  798. /// </summary>
  799. /// <param name="bone">Bone component to register.</param>
  800. internal void AddBone(Bone bone)
  801. {
  802. switch (state)
  803. {
  804. case State.Active:
  805. SceneObject currentSO = bone.SceneObject;
  806. SceneObjectMappingInfo newMapping = new SceneObjectMappingInfo();
  807. newMapping.sceneObject = currentSO;
  808. newMapping.isMappedToBone = true;
  809. newMapping.bone = bone;
  810. mappingInfo.Add(newMapping);
  811. _native.MapCurveToSceneObject(bone.Name, newMapping.sceneObject);
  812. break;
  813. }
  814. }
  815. /// <summary>
  816. /// Unregisters a bone component, removing the bone -> scene object mapping.
  817. /// </summary>
  818. /// <param name="bone">Bone to unregister.</param>
  819. internal void RemoveBone(Bone bone)
  820. {
  821. switch (state)
  822. {
  823. case State.Active:
  824. for (int i = 0; i < mappingInfo.Count; i++)
  825. {
  826. if (mappingInfo[i].bone == bone)
  827. {
  828. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  829. mappingInfo.RemoveAt(i);
  830. i--;
  831. }
  832. }
  833. break;
  834. }
  835. }
  836. /// <summary>
  837. /// Called whenever the bone the <see cref="Bone"/> component points to changed.
  838. /// </summary>
  839. /// <param name="bone">Bone component to modify.</param>
  840. internal void NotifyBoneChanged(Bone bone)
  841. {
  842. switch (state)
  843. {
  844. case State.Active:
  845. for (int i = 0; i < mappingInfo.Count; i++)
  846. {
  847. if (mappingInfo[i].bone == bone)
  848. {
  849. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  850. _native.MapCurveToSceneObject(bone.Name, mappingInfo[i].sceneObject);
  851. break;
  852. }
  853. }
  854. break;
  855. }
  856. }
  857. /// <summary>
  858. /// Finds any scene objects that are mapped to bone transforms. Such object's transforms will be affected by
  859. /// skeleton bone animation.
  860. /// </summary>
  861. private void SetBoneMappings()
  862. {
  863. mappingInfo.Clear();
  864. SceneObjectMappingInfo rootMapping = new SceneObjectMappingInfo();
  865. rootMapping.sceneObject = SceneObject;
  866. rootMapping.isMappedToBone = true;
  867. mappingInfo.Add(rootMapping);
  868. _native.MapCurveToSceneObject("", rootMapping.sceneObject);
  869. Bone[] childBones = FindChildBones();
  870. foreach (var entry in childBones)
  871. AddBone(entry);
  872. }
  873. /// <summary>
  874. /// Searches child scene objects for <see cref="Bone"/> components and returns any found ones.
  875. /// </summary>
  876. private Bone[] FindChildBones()
  877. {
  878. Stack<SceneObject> todo = new Stack<SceneObject>();
  879. todo.Push(SceneObject);
  880. List<Bone> bones = new List<Bone>();
  881. while (todo.Count > 0)
  882. {
  883. SceneObject currentSO = todo.Pop();
  884. Bone bone = currentSO.GetComponent<Bone>();
  885. if (bone != null)
  886. {
  887. bone.SetParent(this, true);
  888. bones.Add(bone);
  889. }
  890. int childCount = currentSO.GetNumChildren();
  891. for (int i = 0; i < childCount; i++)
  892. {
  893. SceneObject child = currentSO.GetChild(i);
  894. if (child.GetComponent<Animation>() != null)
  895. continue;
  896. todo.Push(child);
  897. }
  898. }
  899. return bones.ToArray();
  900. }
  901. /// <summary>
  902. /// Re-applies the bounds to the internal animation object, and the relevant renderable object if one exists.
  903. /// </summary>
  904. internal void UpdateBounds(bool updateRenderable = true)
  905. {
  906. NativeRenderable renderable = null;
  907. if (updateRenderable && animatedRenderable != null)
  908. renderable = animatedRenderable.Native;
  909. if (serializableData.useBounds)
  910. {
  911. if (renderable != null)
  912. {
  913. renderable.UseOverrideBounds = true;
  914. renderable.OverrideBounds = serializableData.bounds;
  915. }
  916. if (_native != null)
  917. {
  918. AABox bounds = serializableData.bounds;
  919. Matrix4 parentTfrm;
  920. if (SceneObject.Parent != null)
  921. parentTfrm = SceneObject.Parent.WorldTransform;
  922. else
  923. parentTfrm = Matrix4.Identity;
  924. bounds.TransformAffine(parentTfrm);
  925. _native.Bounds = bounds;
  926. }
  927. }
  928. else
  929. {
  930. if (renderable != null)
  931. renderable.UseOverrideBounds = false;
  932. if (_native != null)
  933. {
  934. AABox bounds = new AABox();
  935. if (animatedRenderable != null)
  936. bounds = animatedRenderable.Bounds.Box;
  937. _native.Bounds = bounds;
  938. }
  939. }
  940. }
  941. /// <summary>
  942. /// Registers an <see cref="Renderable"/> component with the animation. When registered the animation will use the
  943. /// renderable's bounds for culling, and the animation override bounds will be applied to the renderable.
  944. /// </summary>
  945. /// <param name="renderable">Component that was added</param>
  946. internal void RegisterRenderable(Renderable renderable)
  947. {
  948. animatedRenderable = renderable;
  949. UpdateBounds();
  950. }
  951. /// <summary>
  952. /// Removes renderable from the animation component. <see cref="RegisterRenderable"/>.
  953. /// </summary>
  954. internal void UnregisterRenderable()
  955. {
  956. animatedRenderable = null;
  957. }
  958. /// <summary>
  959. /// Builds a list of properties that will be animated using float animation curves.
  960. /// </summary>
  961. /// <param name="clip">Clip to retrieve the float animation curves from.</param>
  962. private void RebuildFloatProperties(AnimationClip clip)
  963. {
  964. if (clip == null)
  965. {
  966. floatProperties = null;
  967. return;
  968. }
  969. AnimationCurves curves = clip.Curves;
  970. List<FloatCurvePropertyInfo> newFloatProperties = new List<FloatCurvePropertyInfo>();
  971. for (int i = 0; i < curves.FloatCurves.Length; i++)
  972. {
  973. bool isMorphCurve = curves.FloatCurves[i].Flags.HasFlag(AnimationCurveFlags.MorphWeight) ||
  974. curves.FloatCurves[i].Flags.HasFlag(AnimationCurveFlags.MorphFrame);
  975. if (isMorphCurve)
  976. continue;
  977. string suffix;
  978. SerializableProperty property = FindProperty(SceneObject, curves.FloatCurves[i].Name, out suffix);
  979. if (property == null)
  980. continue;
  981. int elementIdx = 0;
  982. if (!string.IsNullOrEmpty(suffix))
  983. {
  984. PropertySuffixInfo suffixInfo;
  985. if (PropertySuffixInfos.TryGetValue(suffix, out suffixInfo))
  986. elementIdx = suffixInfo.elementIdx;
  987. }
  988. Action<float> setter = null;
  989. Type internalType = property.InternalType;
  990. switch (property.Type)
  991. {
  992. case SerializableProperty.FieldType.Vector2:
  993. if (internalType == typeof(Vector2))
  994. {
  995. setter = f =>
  996. {
  997. Vector2 value = property.GetValue<Vector2>();
  998. value[elementIdx] = f;
  999. property.SetValue(value);
  1000. };
  1001. }
  1002. break;
  1003. case SerializableProperty.FieldType.Vector3:
  1004. if (internalType == typeof(Vector3))
  1005. {
  1006. setter = f =>
  1007. {
  1008. Vector3 value = property.GetValue<Vector3>();
  1009. value[elementIdx] = f;
  1010. property.SetValue(value);
  1011. };
  1012. }
  1013. break;
  1014. case SerializableProperty.FieldType.Vector4:
  1015. if (internalType == typeof(Vector4))
  1016. {
  1017. setter = f =>
  1018. {
  1019. Vector4 value = property.GetValue<Vector4>();
  1020. value[elementIdx] = f;
  1021. property.SetValue(value);
  1022. };
  1023. }
  1024. else if (internalType == typeof(Quaternion))
  1025. {
  1026. setter = f =>
  1027. {
  1028. Quaternion value = property.GetValue<Quaternion>();
  1029. value[elementIdx] = f;
  1030. property.SetValue(value);
  1031. };
  1032. }
  1033. break;
  1034. case SerializableProperty.FieldType.Color:
  1035. if (internalType == typeof(Color))
  1036. {
  1037. setter = f =>
  1038. {
  1039. Color value = property.GetValue<Color>();
  1040. value[elementIdx] = f;
  1041. property.SetValue(value);
  1042. };
  1043. }
  1044. break;
  1045. case SerializableProperty.FieldType.Bool:
  1046. setter = f =>
  1047. {
  1048. bool value = f > 0.0f;
  1049. property.SetValue(value);
  1050. };
  1051. break;
  1052. case SerializableProperty.FieldType.Int:
  1053. setter = f =>
  1054. {
  1055. int value = (int)f;
  1056. property.SetValue(value);
  1057. };
  1058. break;
  1059. case SerializableProperty.FieldType.Float:
  1060. setter = f =>
  1061. {
  1062. property.SetValue(f);
  1063. };
  1064. break;
  1065. }
  1066. if (setter == null)
  1067. continue;
  1068. FloatCurvePropertyInfo propertyInfo = new FloatCurvePropertyInfo();
  1069. propertyInfo.curveIdx = i;
  1070. propertyInfo.setter = setter;
  1071. newFloatProperties.Add(propertyInfo);
  1072. }
  1073. floatProperties = newFloatProperties.ToArray();
  1074. }
  1075. /// <summary>
  1076. /// Called whenever an animation event triggers.
  1077. /// </summary>
  1078. /// <param name="clip">Clip that the event originated from.</param>
  1079. /// <param name="name">Name of the event.</param>
  1080. private void EventTriggered(AnimationClip clip, string name)
  1081. {
  1082. // Event should be in format "ComponentType/MethodName"
  1083. if (string.IsNullOrEmpty(name))
  1084. return;
  1085. string[] nameEntries = name.Split('/');
  1086. if (nameEntries.Length != 2)
  1087. return;
  1088. string typeName = nameEntries[0];
  1089. string methodName = nameEntries[1];
  1090. Component[] components = SceneObject.GetComponents();
  1091. for (int i = 0; i < components.Length; i++)
  1092. {
  1093. if (components[i].GetType().Name == typeName)
  1094. {
  1095. components[i].Invoke(methodName);
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. /// <summary>
  1101. /// Holds all data the animation component needs to persist through serialization.
  1102. /// </summary>
  1103. [SerializeObject]
  1104. private class SerializableData
  1105. {
  1106. public AnimationClip defaultClip;
  1107. public AnimWrapMode wrapMode = AnimWrapMode.Loop;
  1108. public float speed = 1.0f;
  1109. public AABox bounds;
  1110. public bool useBounds;
  1111. public bool cull = true;
  1112. }
  1113. /// <summary>
  1114. /// Contains information about a property animated by a generic animation curve.
  1115. /// </summary>
  1116. private class FloatCurvePropertyInfo
  1117. {
  1118. public int curveIdx;
  1119. public Action<float> setter;
  1120. }
  1121. /// <summary>
  1122. /// Information about a suffix used in a property path.
  1123. /// </summary>
  1124. internal struct PropertySuffixInfo
  1125. {
  1126. public PropertySuffixInfo(int elementIdx, bool isVector)
  1127. {
  1128. this.elementIdx = elementIdx;
  1129. this.isVector = isVector;
  1130. }
  1131. public int elementIdx;
  1132. public bool isVector;
  1133. }
  1134. /// <summary>
  1135. /// Information about scene objects bound to a specific animation curve.
  1136. /// </summary>
  1137. internal struct SceneObjectMappingInfo
  1138. {
  1139. public SceneObject sceneObject;
  1140. public bool isMappedToBone;
  1141. public Bone bone;
  1142. }
  1143. /// <summary>
  1144. /// Possible states the animation component can be in.
  1145. /// </summary>
  1146. private enum State
  1147. {
  1148. /// <summary>
  1149. /// Animation object isn't constructed.
  1150. /// </summary>
  1151. Inactive,
  1152. /// <summary>
  1153. /// Animation object is constructed and fully functional.
  1154. /// </summary>
  1155. Active,
  1156. /// <summary>
  1157. /// Animation object is constructed and functional with limited funcionality for editor purposes.
  1158. /// </summary>
  1159. EditorActive
  1160. }
  1161. }
  1162. /// <summary>
  1163. /// Determines how an animation clip behaves when it reaches the end.
  1164. /// </summary>
  1165. public enum AnimWrapMode // Note: Must match C++ enum AnimWrapMode
  1166. {
  1167. /// <summary>
  1168. /// Loop around to the beginning/end when the last/first frame is reached.
  1169. /// </summary>
  1170. Loop,
  1171. /// <summary>
  1172. /// Clamp to end/beginning, keeping the last/first frame active.
  1173. /// </summary>
  1174. Clamp
  1175. }
  1176. /// <summary>
  1177. /// Represents an animation clip used in 1D blending. Each clip has a position on the number line.
  1178. /// </summary>
  1179. public class BlendClipInfo
  1180. {
  1181. public AnimationClip clip;
  1182. public float position;
  1183. }
  1184. /// <summary>
  1185. /// Defines a 1D blend where two animation clips are blended between each other using linear interpolation.
  1186. /// </summary>
  1187. public class Blend1DInfo
  1188. {
  1189. public Blend1DInfo()
  1190. { }
  1191. public Blend1DInfo(int numClips)
  1192. {
  1193. clips = new BlendClipInfo[numClips];
  1194. }
  1195. public BlendClipInfo[] clips;
  1196. }
  1197. /// <summary>
  1198. /// Defines a 2D blend where two animation clips are blended between each other using bilinear interpolation.
  1199. /// </summary>
  1200. public class Blend2DInfo
  1201. {
  1202. public AnimationClip topLeftClip;
  1203. public AnimationClip topRightClip;
  1204. public AnimationClip botLeftClip;
  1205. public AnimationClip botRightClip;
  1206. }
  1207. /// <summary>
  1208. /// Contains information about a currently playing animation clip.
  1209. /// </summary>
  1210. [StructLayout(LayoutKind.Sequential), SerializeObject]
  1211. public struct AnimationClipState // Note: Must match C++ struct AnimationClipState
  1212. {
  1213. /// <summary>
  1214. /// Layer the clip is playing on. Multiple clips can be played simulatenously on different layers.
  1215. /// </summary>
  1216. public int layer;
  1217. /// <summary>
  1218. /// Current time the animation is playing from.
  1219. /// </summary>
  1220. public float time;
  1221. /// <summary>
  1222. /// Speed at which the animation is playing.
  1223. /// </summary>
  1224. public float speed;
  1225. /// <summary>
  1226. /// Determines how much of an influence does the clip have on the final pose.
  1227. /// </summary>
  1228. public float weight;
  1229. /// <summary>
  1230. /// Determines what happens to other animation clips when a new clip starts playing.
  1231. /// </summary>
  1232. public AnimWrapMode wrapMode;
  1233. /// <summary>
  1234. /// Creates a new clip state, with default values initialized.
  1235. /// </summary>
  1236. /// <returns>New animation clip state.</returns>
  1237. public static AnimationClipState Create()
  1238. {
  1239. AnimationClipState state = new AnimationClipState();
  1240. state.speed = 1.0f;
  1241. state.weight = 1.0f;
  1242. state.wrapMode = AnimWrapMode.Loop;
  1243. return state;
  1244. }
  1245. }
  1246. /** @} */
  1247. }