AnimationState.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software
  13. * or otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #ifdef SPINE_UE4
  30. #include "SpinePluginPrivatePCH.h"
  31. #endif
  32. #include <spine/AnimationState.h>
  33. #include <spine/Animation.h>
  34. #include <spine/Event.h>
  35. #include <spine/AnimationStateData.h>
  36. #include <spine/Skeleton.h>
  37. #include <spine/RotateTimeline.h>
  38. #include <spine/SkeletonData.h>
  39. #include <spine/Bone.h>
  40. #include <spine/BoneData.h>
  41. #include <spine/AttachmentTimeline.h>
  42. #include <spine/DrawOrderTimeline.h>
  43. #include <spine/EventTimeline.h>
  44. #include <float.h>
  45. using namespace spine;
  46. void dummyOnAnimationEventFunc(AnimationState *state, spine::EventType type, TrackEntry *entry, Event *event = NULL) {
  47. SP_UNUSED(state);
  48. SP_UNUSED(type);
  49. SP_UNUSED(entry);
  50. SP_UNUSED(event);
  51. }
  52. TrackEntry::TrackEntry() : _animation(NULL), _next(NULL), _mixingFrom(NULL), _mixingTo(0), _trackIndex(0), _loop(false), _holdPrevious(false),
  53. _eventThreshold(0), _attachmentThreshold(0), _drawOrderThreshold(0), _animationStart(0),
  54. _animationEnd(0), _animationLast(0), _nextAnimationLast(0), _delay(0), _trackTime(0),
  55. _trackLast(0), _nextTrackLast(0), _trackEnd(0), _timeScale(1.0f), _alpha(0), _mixTime(0),
  56. _mixDuration(0), _interruptAlpha(0), _totalAlpha(0), _mixBlend(MixBlend_Replace),
  57. _listener(dummyOnAnimationEventFunc), _listenerObject(NULL) {
  58. }
  59. TrackEntry::~TrackEntry() { }
  60. int TrackEntry::getTrackIndex() { return _trackIndex; }
  61. Animation *TrackEntry::getAnimation() { return _animation; }
  62. bool TrackEntry::getLoop() { return _loop; }
  63. void TrackEntry::setLoop(bool inValue) { _loop = inValue; }
  64. bool TrackEntry::getHoldPrevious() { return _holdPrevious; }
  65. void TrackEntry::setHoldPrevious(bool inValue) { _holdPrevious = inValue; }
  66. float TrackEntry::getDelay() { return _delay; }
  67. void TrackEntry::setDelay(float inValue) { _delay = inValue; }
  68. float TrackEntry::getTrackTime() { return _trackTime; }
  69. void TrackEntry::setTrackTime(float inValue) { _trackTime = inValue; }
  70. float TrackEntry::getTrackEnd() { return _trackEnd; }
  71. void TrackEntry::setTrackEnd(float inValue) { _trackEnd = inValue; }
  72. float TrackEntry::getAnimationStart() { return _animationStart; }
  73. void TrackEntry::setAnimationStart(float inValue) { _animationStart = inValue; }
  74. float TrackEntry::getAnimationEnd() { return _animationEnd; }
  75. void TrackEntry::setAnimationEnd(float inValue) { _animationEnd = inValue; }
  76. float TrackEntry::getAnimationLast() { return _animationLast; }
  77. void TrackEntry::setAnimationLast(float inValue) {
  78. _animationLast = inValue;
  79. _nextAnimationLast = inValue;
  80. }
  81. float TrackEntry::getAnimationTime() {
  82. if (_loop) {
  83. float duration = _animationEnd - _animationStart;
  84. if (duration == 0) return _animationStart;
  85. return MathUtil::fmod(_trackTime, duration) + _animationStart;
  86. }
  87. return MathUtil::min(_trackTime + _animationStart, _animationEnd);
  88. }
  89. float TrackEntry::getTimeScale() { return _timeScale; }
  90. void TrackEntry::setTimeScale(float inValue) { _timeScale = inValue; }
  91. float TrackEntry::getAlpha() { return _alpha; }
  92. void TrackEntry::setAlpha(float inValue) { _alpha = inValue; }
  93. float TrackEntry::getEventThreshold() { return _eventThreshold; }
  94. void TrackEntry::setEventThreshold(float inValue) { _eventThreshold = inValue; }
  95. float TrackEntry::getAttachmentThreshold() { return _attachmentThreshold; }
  96. void TrackEntry::setAttachmentThreshold(float inValue) { _attachmentThreshold = inValue; }
  97. float TrackEntry::getDrawOrderThreshold() { return _drawOrderThreshold; }
  98. void TrackEntry::setDrawOrderThreshold(float inValue) { _drawOrderThreshold = inValue; }
  99. TrackEntry *TrackEntry::getNext() { return _next; }
  100. bool TrackEntry::isComplete() {
  101. return _trackTime >= _animationEnd - _animationStart;
  102. }
  103. float TrackEntry::getMixTime() { return _mixTime; }
  104. void TrackEntry::setMixTime(float inValue) { _mixTime = inValue; }
  105. float TrackEntry::getMixDuration() { return _mixDuration; }
  106. void TrackEntry::setMixDuration(float inValue) { _mixDuration = inValue; }
  107. TrackEntry *TrackEntry::getMixingFrom() { return _mixingFrom; }
  108. TrackEntry *TrackEntry::getMixingTo() { return _mixingTo; }
  109. void TrackEntry::setMixBlend(MixBlend blend) { _mixBlend = blend; }
  110. MixBlend TrackEntry::getMixBlend() { return _mixBlend; }
  111. void TrackEntry::resetRotationDirections() {
  112. _timelinesRotation.clear();
  113. }
  114. void TrackEntry::setListener(AnimationStateListener inValue) {
  115. _listener = inValue;
  116. _listenerObject = NULL;
  117. }
  118. void TrackEntry::setListener(AnimationStateListenerObject* inValue) {
  119. _listener = dummyOnAnimationEventFunc;
  120. _listenerObject = inValue;
  121. }
  122. void TrackEntry::reset() {
  123. _animation = NULL;
  124. _next = NULL;
  125. _mixingFrom = NULL;
  126. _mixingTo = NULL;
  127. setRendererObject(NULL);
  128. _timelineMode.clear();
  129. _timelineHoldMix.clear();
  130. _timelinesRotation.clear();
  131. _listener = dummyOnAnimationEventFunc;
  132. _listenerObject = NULL;
  133. }
  134. EventQueueEntry::EventQueueEntry(EventType eventType, TrackEntry *trackEntry, Event *event) :
  135. _type(eventType),
  136. _entry(trackEntry),
  137. _event(event) {
  138. }
  139. EventQueue *EventQueue::newEventQueue(AnimationState &state, Pool<TrackEntry> &trackEntryPool) {
  140. return new(__FILE__, __LINE__) EventQueue(state, trackEntryPool);
  141. }
  142. EventQueueEntry EventQueue::newEventQueueEntry(EventType eventType, TrackEntry *entry, Event *event) {
  143. return EventQueueEntry(eventType, entry, event);
  144. }
  145. EventQueue::EventQueue(AnimationState &state, Pool<TrackEntry> &trackEntryPool) : _state(state),
  146. _trackEntryPool(trackEntryPool),
  147. _drainDisabled(false) {
  148. }
  149. EventQueue::~EventQueue() {
  150. }
  151. void EventQueue::start(TrackEntry *entry) {
  152. _eventQueueEntries.add(newEventQueueEntry(EventType_Start, entry));
  153. _state._animationsChanged = true;
  154. }
  155. void EventQueue::interrupt(TrackEntry *entry) {
  156. _eventQueueEntries.add(newEventQueueEntry(EventType_Interrupt, entry));
  157. }
  158. void EventQueue::end(TrackEntry *entry) {
  159. _eventQueueEntries.add(newEventQueueEntry(EventType_End, entry));
  160. _state._animationsChanged = true;
  161. }
  162. void EventQueue::dispose(TrackEntry *entry) {
  163. _eventQueueEntries.add(newEventQueueEntry(EventType_Dispose, entry));
  164. }
  165. void EventQueue::complete(TrackEntry *entry) {
  166. _eventQueueEntries.add(newEventQueueEntry(EventType_Complete, entry));
  167. }
  168. void EventQueue::event(TrackEntry *entry, Event *event) {
  169. _eventQueueEntries.add(newEventQueueEntry(EventType_Event, entry, event));
  170. }
  171. /// Raises all events in the queue and drains the queue.
  172. void EventQueue::drain() {
  173. if (_drainDisabled) {
  174. return;
  175. }
  176. _drainDisabled = true;
  177. AnimationState &state = _state;
  178. // Don't cache _eventQueueEntries.size() so callbacks can queue their own events (eg, call setAnimation in AnimationState_Complete).
  179. for (size_t i = 0; i < _eventQueueEntries.size(); ++i) {
  180. EventQueueEntry *queueEntry = &_eventQueueEntries[i];
  181. TrackEntry *trackEntry = queueEntry->_entry;
  182. switch (queueEntry->_type) {
  183. case EventType_Start:
  184. case EventType_Interrupt:
  185. case EventType_Complete:
  186. if (!trackEntry->_listenerObject) trackEntry->_listener(&state, queueEntry->_type, trackEntry, NULL);
  187. else trackEntry->_listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL);
  188. if(!state._listenerObject) state._listener(&state, queueEntry->_type, trackEntry, NULL);
  189. else state._listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL);
  190. break;
  191. case EventType_End:
  192. if (!trackEntry->_listenerObject) trackEntry->_listener(&state, queueEntry->_type, trackEntry, NULL);
  193. else trackEntry->_listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL);
  194. if (!state._listenerObject) state._listener(&state, queueEntry->_type, trackEntry, NULL);
  195. else state._listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL);
  196. /* Fall through. */
  197. case EventType_Dispose:
  198. if (!trackEntry->_listenerObject) trackEntry->_listener(&state, EventType_Dispose, trackEntry, NULL);
  199. else trackEntry->_listenerObject->callback(&state, EventType_Dispose, trackEntry, NULL);
  200. if (!state._listenerObject) state._listener(&state, EventType_Dispose, trackEntry, NULL);
  201. else state._listenerObject->callback(&state, EventType_Dispose, trackEntry, NULL);
  202. trackEntry->reset();
  203. _trackEntryPool.free(trackEntry);
  204. break;
  205. case EventType_Event:
  206. if (!trackEntry->_listenerObject) trackEntry->_listener(&state, queueEntry->_type, trackEntry, queueEntry->_event);
  207. else trackEntry->_listenerObject->callback(&state, queueEntry->_type, trackEntry, queueEntry->_event);
  208. if (!state._listenerObject) state._listener(&state, queueEntry->_type, trackEntry, queueEntry->_event);
  209. else state._listenerObject->callback(&state, queueEntry->_type, trackEntry, queueEntry->_event);
  210. break;
  211. }
  212. }
  213. _eventQueueEntries.clear();
  214. _drainDisabled = false;
  215. }
  216. const int Subsequent = 0;
  217. const int First = 1;
  218. const int Hold = 2;
  219. const int HoldMix = 3;
  220. const int NotLast = 4;
  221. AnimationState::AnimationState(AnimationStateData *data) :
  222. _data(data),
  223. _queue(EventQueue::newEventQueue(*this, _trackEntryPool)),
  224. _animationsChanged(false),
  225. _listener(dummyOnAnimationEventFunc),
  226. _listenerObject(NULL),
  227. _timeScale(1) {
  228. }
  229. AnimationState::~AnimationState() {
  230. for (size_t i = 0; i < _tracks.size(); i++) {
  231. TrackEntry* entry = _tracks[i];
  232. if (entry) {
  233. TrackEntry* from = entry->_mixingFrom;
  234. while (from) {
  235. TrackEntry* curr = from;
  236. from = curr->_mixingFrom;
  237. delete curr;
  238. }
  239. TrackEntry* next = entry->_next;
  240. while (next) {
  241. TrackEntry* curr = next;
  242. next = curr->_next;
  243. delete curr;
  244. }
  245. delete entry;
  246. }
  247. }
  248. delete _queue;
  249. }
  250. void AnimationState::update(float delta) {
  251. delta *= _timeScale;
  252. for (size_t i = 0, n = _tracks.size(); i < n; ++i) {
  253. TrackEntry *currentP = _tracks[i];
  254. if (currentP == NULL) {
  255. continue;
  256. }
  257. TrackEntry &current = *currentP;
  258. current._animationLast = current._nextAnimationLast;
  259. current._trackLast = current._nextTrackLast;
  260. float currentDelta = delta * current._timeScale;
  261. if (current._delay > 0) {
  262. current._delay -= currentDelta;
  263. if (current._delay > 0) {
  264. continue;
  265. }
  266. currentDelta = -current._delay;
  267. current._delay = 0;
  268. }
  269. TrackEntry *next = current._next;
  270. if (next != NULL) {
  271. // When the next entry's delay is passed, change to the next entry, preserving leftover time.
  272. float nextTime = current._trackLast - next->_delay;
  273. if (nextTime >= 0) {
  274. next->_delay = 0;
  275. next->_trackTime += current._timeScale == 0 ? 0 : (nextTime / current._timeScale + delta) * next->_timeScale;
  276. current._trackTime += currentDelta;
  277. setCurrent(i, next, true);
  278. while (next->_mixingFrom != NULL) {
  279. next->_mixTime += delta;
  280. next = next->_mixingFrom;
  281. }
  282. continue;
  283. }
  284. } else if (current._trackLast >= current._trackEnd && current._mixingFrom == NULL) {
  285. // clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom.
  286. _tracks[i] = NULL;
  287. _queue->end(currentP);
  288. disposeNext(currentP);
  289. continue;
  290. }
  291. if (current._mixingFrom != NULL && updateMixingFrom(currentP, delta)) {
  292. // End mixing from entries once all have completed.
  293. TrackEntry *from = current._mixingFrom;
  294. current._mixingFrom = NULL;
  295. if (from != NULL) from->_mixingTo = NULL;
  296. while (from != NULL) {
  297. _queue->end(from);
  298. from = from->_mixingFrom;
  299. }
  300. }
  301. current._trackTime += currentDelta;
  302. }
  303. _queue->drain();
  304. }
  305. bool AnimationState::apply(Skeleton &skeleton) {
  306. if (_animationsChanged) {
  307. animationsChanged();
  308. }
  309. bool applied = false;
  310. for (size_t i = 0, n = _tracks.size(); i < n; ++i) {
  311. TrackEntry *currentP = _tracks[i];
  312. if (currentP == NULL || currentP->_delay > 0) {
  313. continue;
  314. }
  315. TrackEntry &current = *currentP;
  316. applied = true;
  317. MixBlend blend = i == 0 ? MixBlend_First : current._mixBlend;
  318. // apply mixing from entries first.
  319. float mix = current._alpha;
  320. if (current._mixingFrom != NULL) {
  321. mix *= applyMixingFrom(currentP, skeleton, blend);
  322. } else if (current._trackTime >= current._trackEnd && current._next == NULL) {
  323. mix = 0; // Set to setup pose the last time the entry will be applied.
  324. }
  325. // apply current entry.
  326. float animationLast = current._animationLast, animationTime = current.getAnimationTime();
  327. size_t timelineCount = current._animation->_timelines.size();
  328. Vector<Timeline *> &timelines = current._animation->_timelines;
  329. if ((i == 0 && mix == 1) || blend == MixBlend_Add) {
  330. for (size_t ii = 0; ii < timelineCount; ++ii)
  331. timelines[ii]->apply(skeleton, animationLast, animationTime, &_events, mix, blend, MixDirection_In);
  332. } else {
  333. Vector<int> &timelineMode = current._timelineMode;
  334. bool firstFrame = current._timelinesRotation.size() == 0;
  335. if (firstFrame) current._timelinesRotation.setSize(timelines.size() << 1, 0);
  336. Vector<float> &timelinesRotation = current._timelinesRotation;
  337. for (size_t ii = 0; ii < timelineCount; ++ii) {
  338. Timeline *timeline = timelines[ii];
  339. assert(timeline);
  340. MixBlend timelineBlend = (timelineMode[ii] & (NotLast - 1)) == Subsequent ? blend : MixBlend_Setup;
  341. RotateTimeline *rotateTimeline = NULL;
  342. if (timeline->getRTTI().isExactly(RotateTimeline::rtti)) rotateTimeline = static_cast<RotateTimeline *>(timeline);
  343. if (rotateTimeline != NULL)
  344. applyRotateTimeline(rotateTimeline, skeleton, animationTime, mix, timelineBlend, timelinesRotation, ii << 1, firstFrame);
  345. else
  346. timeline->apply(skeleton, animationLast, animationTime, &_events, mix, timelineBlend, MixDirection_In);
  347. }
  348. }
  349. queueEvents(currentP, animationTime);
  350. _events.clear();
  351. current._nextAnimationLast = animationTime;
  352. current._nextTrackLast = current._trackTime;
  353. }
  354. _queue->drain();
  355. return applied;
  356. }
  357. void AnimationState::clearTracks() {
  358. bool oldDrainDisabled = _queue->_drainDisabled;
  359. _queue->_drainDisabled = true;
  360. for (size_t i = 0, n = _tracks.size(); i < n; ++i)
  361. clearTrack(i);
  362. _tracks.clear();
  363. _queue->_drainDisabled = oldDrainDisabled;
  364. _queue->drain();
  365. }
  366. void AnimationState::clearTrack(size_t trackIndex) {
  367. if (trackIndex >= _tracks.size()) return;
  368. TrackEntry *current = _tracks[trackIndex];
  369. if (current == NULL) return;
  370. _queue->end(current);
  371. disposeNext(current);
  372. TrackEntry *entry = current;
  373. while (true) {
  374. TrackEntry *from = entry->_mixingFrom;
  375. if (from == NULL) break;
  376. _queue->end(from);
  377. entry->_mixingFrom = NULL;
  378. entry->_mixingTo = NULL;
  379. entry = from;
  380. }
  381. _tracks[current->_trackIndex] = NULL;
  382. _queue->drain();
  383. }
  384. TrackEntry *AnimationState::setAnimation(size_t trackIndex, const String &animationName, bool loop) {
  385. Animation *animation = _data->_skeletonData->findAnimation(animationName);
  386. assert(animation != NULL);
  387. return setAnimation(trackIndex, animation, loop);
  388. }
  389. TrackEntry *AnimationState::setAnimation(size_t trackIndex, Animation *animation, bool loop) {
  390. assert(animation != NULL);
  391. bool interrupt = true;
  392. TrackEntry *current = expandToIndex(trackIndex);
  393. if (current != NULL) {
  394. if (current->_nextTrackLast == -1) {
  395. // Don't mix from an entry that was never applied.
  396. _tracks[trackIndex] = current->_mixingFrom;
  397. _queue->interrupt(current);
  398. _queue->end(current);
  399. disposeNext(current);
  400. current = current->_mixingFrom;
  401. interrupt = false;
  402. } else {
  403. disposeNext(current);
  404. }
  405. }
  406. TrackEntry *entry = newTrackEntry(trackIndex, animation, loop, current);
  407. setCurrent(trackIndex, entry, interrupt);
  408. _queue->drain();
  409. return entry;
  410. }
  411. TrackEntry *AnimationState::addAnimation(size_t trackIndex, const String &animationName, bool loop, float delay) {
  412. Animation *animation = _data->_skeletonData->findAnimation(animationName);
  413. assert(animation != NULL);
  414. return addAnimation(trackIndex, animation, loop, delay);
  415. }
  416. TrackEntry *AnimationState::addAnimation(size_t trackIndex, Animation *animation, bool loop, float delay) {
  417. assert(animation != NULL);
  418. TrackEntry *last = expandToIndex(trackIndex);
  419. if (last != NULL) {
  420. while (last->_next != NULL)
  421. last = last->_next;
  422. }
  423. TrackEntry *entry = newTrackEntry(trackIndex, animation, loop, last);
  424. if (last == NULL) {
  425. setCurrent(trackIndex, entry, true);
  426. _queue->drain();
  427. } else {
  428. last->_next = entry;
  429. if (delay <= 0) {
  430. float duration = last->_animationEnd - last->_animationStart;
  431. if (duration != 0) {
  432. if (last->_loop) {
  433. delay += duration * (1 + (int) (last->_trackTime / duration));
  434. } else {
  435. delay += MathUtil::max(duration, last->_trackTime);
  436. }
  437. delay -= _data->getMix(last->_animation, animation);
  438. } else {
  439. delay = last->_trackTime;
  440. }
  441. }
  442. }
  443. entry->_delay = delay;
  444. return entry;
  445. }
  446. TrackEntry *AnimationState::setEmptyAnimation(size_t trackIndex, float mixDuration) {
  447. TrackEntry *entry = setAnimation(trackIndex, AnimationState::getEmptyAnimation(), false);
  448. entry->_mixDuration = mixDuration;
  449. entry->_trackEnd = mixDuration;
  450. return entry;
  451. }
  452. TrackEntry *AnimationState::addEmptyAnimation(size_t trackIndex, float mixDuration, float delay) {
  453. if (delay <= 0) {
  454. delay -= mixDuration;
  455. }
  456. TrackEntry *entry = addAnimation(trackIndex, AnimationState::getEmptyAnimation(), false, delay);
  457. entry->_mixDuration = mixDuration;
  458. entry->_trackEnd = mixDuration;
  459. return entry;
  460. }
  461. void AnimationState::setEmptyAnimations(float mixDuration) {
  462. bool oldDrainDisabled = _queue->_drainDisabled;
  463. _queue->_drainDisabled = true;
  464. for (size_t i = 0, n = _tracks.size(); i < n; ++i) {
  465. TrackEntry *current = _tracks[i];
  466. if (current != NULL) {
  467. setEmptyAnimation(i, mixDuration);
  468. }
  469. }
  470. _queue->_drainDisabled = oldDrainDisabled;
  471. _queue->drain();
  472. }
  473. TrackEntry *AnimationState::getCurrent(size_t trackIndex) {
  474. return trackIndex >= _tracks.size() ? NULL : _tracks[trackIndex];
  475. }
  476. AnimationStateData *AnimationState::getData() {
  477. return _data;
  478. }
  479. Vector<TrackEntry *> &AnimationState::getTracks() {
  480. return _tracks;
  481. }
  482. float AnimationState::getTimeScale() {
  483. return _timeScale;
  484. }
  485. void AnimationState::setTimeScale(float inValue) {
  486. _timeScale = inValue;
  487. }
  488. void AnimationState::setListener(AnimationStateListener inValue) {
  489. _listener = inValue;
  490. _listenerObject = NULL;
  491. }
  492. void AnimationState::setListener(AnimationStateListenerObject* inValue) {
  493. _listener = dummyOnAnimationEventFunc;
  494. _listenerObject = inValue;
  495. }
  496. void AnimationState::disableQueue() {
  497. _queue->_drainDisabled = true;
  498. }
  499. void AnimationState::enableQueue() {
  500. _queue->_drainDisabled = false;
  501. }
  502. Animation *AnimationState::getEmptyAnimation() {
  503. static Vector<Timeline *> timelines;
  504. static Animation ret(String("<empty>"), timelines, 0);
  505. return &ret;
  506. }
  507. void AnimationState::applyRotateTimeline(RotateTimeline *rotateTimeline, Skeleton &skeleton, float time, float alpha,
  508. MixBlend blend, Vector<float> &timelinesRotation, size_t i, bool firstFrame
  509. ) {
  510. if (firstFrame) timelinesRotation[i] = 0;
  511. if (alpha == 1) {
  512. rotateTimeline->apply(skeleton, 0, time, NULL, 1, blend, MixDirection_In);
  513. return;
  514. }
  515. Bone *bone = skeleton._bones[rotateTimeline->_boneIndex];
  516. if (!bone->isActive()) return;
  517. Vector<float>& frames = rotateTimeline->_frames;
  518. float r1, r2;
  519. if (time < frames[0]) {
  520. switch (blend) {
  521. case MixBlend_Setup:
  522. bone->_rotation = bone->_data._rotation;
  523. default:
  524. return;
  525. case MixBlend_First:
  526. r1 = bone->_rotation;
  527. r2 = bone->_data._rotation;
  528. }
  529. } else {
  530. r1 = blend == MixBlend_Setup ? bone->_data._rotation : bone->_rotation;
  531. if (time >= frames[frames.size() - RotateTimeline::ENTRIES]) {
  532. // Time is after last frame.
  533. r2 = bone->_data._rotation + frames[frames.size() + RotateTimeline::PREV_ROTATION];
  534. } else {
  535. // Interpolate between the previous frame and the current frame.
  536. int frame = Animation::binarySearch(frames, time, RotateTimeline::ENTRIES);
  537. float prevRotation = frames[frame + RotateTimeline::PREV_ROTATION];
  538. float frameTime = frames[frame];
  539. float percent = rotateTimeline->getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame +
  540. RotateTimeline::PREV_TIME] - frameTime));
  541. r2 = frames[frame + RotateTimeline::ROTATION] - prevRotation;
  542. r2 -= (16384 - (int) (16384.499999999996 - r2 / 360)) * 360;
  543. r2 = prevRotation + r2 * percent + bone->_data._rotation;
  544. r2 -= (16384 - (int) (16384.499999999996 - r2 / 360)) * 360;
  545. }
  546. }
  547. // Mix between rotations using the direction of the shortest route on the first frame while detecting crosses.
  548. float total, diff = r2 - r1;
  549. diff -= (16384 - (int) (16384.499999999996 - diff / 360)) * 360;
  550. if (diff == 0) {
  551. total = timelinesRotation[i];
  552. } else {
  553. float lastTotal, lastDiff;
  554. if (firstFrame) {
  555. lastTotal = 0;
  556. lastDiff = diff;
  557. } else {
  558. lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops.
  559. lastDiff = timelinesRotation[i + 1]; // Difference between bones.
  560. }
  561. bool current = diff > 0, dir = lastTotal >= 0;
  562. // Detect cross at 0 (not 180).
  563. if (MathUtil::sign(lastDiff) != MathUtil::sign(diff) && MathUtil::abs(lastDiff) <= 90) {
  564. // A cross after a 360 rotation is a loop.
  565. if (MathUtil::abs(lastTotal) > 180) lastTotal += 360 * MathUtil::sign(lastTotal);
  566. dir = current;
  567. }
  568. total = diff + lastTotal - MathUtil::fmod(lastTotal, 360); // Store loops as part of lastTotal.
  569. if (dir != current) {
  570. total += 360 * MathUtil::sign(lastTotal);
  571. }
  572. timelinesRotation[i] = total;
  573. }
  574. timelinesRotation[i + 1] = diff;
  575. r1 += total * alpha;
  576. bone->_rotation = r1 - (16384 - (int) (16384.499999999996 - r1 / 360)) * 360;
  577. }
  578. bool AnimationState::updateMixingFrom(TrackEntry *to, float delta) {
  579. TrackEntry *from = to->_mixingFrom;
  580. if (from == NULL) {
  581. return true;
  582. }
  583. bool finished = updateMixingFrom(from, delta);
  584. from->_animationLast = from->_nextAnimationLast;
  585. from->_trackLast = from->_nextTrackLast;
  586. // Require mixTime > 0 to ensure the mixing from entry was applied at least once.
  587. if (to->_mixTime > 0 && to->_mixTime >= to->_mixDuration) {
  588. // Require totalAlpha == 0 to ensure mixing is complete, unless mixDuration == 0 (the transition is a single frame).
  589. if (from->_totalAlpha == 0 || to->_mixDuration == 0) {
  590. to->_mixingFrom = from->_mixingFrom;
  591. if (from->_mixingFrom != NULL) from->_mixingFrom->_mixingTo = to;
  592. to->_interruptAlpha = from->_interruptAlpha;
  593. _queue->end(from);
  594. }
  595. return finished;
  596. }
  597. from->_trackTime += delta * from->_timeScale;
  598. to->_mixTime += delta;
  599. return false;
  600. }
  601. float AnimationState::applyMixingFrom(TrackEntry *to, Skeleton &skeleton, MixBlend blend) {
  602. TrackEntry *from = to->_mixingFrom;
  603. if (from->_mixingFrom != NULL) applyMixingFrom(from, skeleton, blend);
  604. float mix;
  605. if (to->_mixDuration == 0) {
  606. // Single frame mix to undo mixingFrom changes.
  607. mix = 1;
  608. if (blend == MixBlend_First) blend = MixBlend_Setup;
  609. } else {
  610. mix = to->_mixTime / to->_mixDuration;
  611. if (mix > 1) {
  612. mix = 1;
  613. }
  614. if (blend != MixBlend_First) blend = from->_mixBlend;
  615. }
  616. Vector<Event *> *eventBuffer = mix < from->_eventThreshold ? &_events : NULL;
  617. bool attachments = mix < from->_attachmentThreshold, drawOrder = mix < from->_drawOrderThreshold;
  618. float animationLast = from->_animationLast, animationTime = from->getAnimationTime();
  619. Vector<Timeline *> &timelines = from->_animation->_timelines;
  620. size_t timelineCount = timelines.size();
  621. float alphaHold = from->_alpha * to->_interruptAlpha, alphaMix = alphaHold * (1 - mix);
  622. if (blend == MixBlend_Add) {
  623. for (size_t i = 0; i < timelineCount; i++)
  624. timelines[i]->apply(skeleton, animationLast, animationTime, eventBuffer, alphaMix, blend, MixDirection_Out);
  625. } else {
  626. Vector<int> &timelineMode = from->_timelineMode;
  627. Vector<TrackEntry *> &timelineHoldMix = from->_timelineHoldMix;
  628. bool firstFrame = from->_timelinesRotation.size() == 0;
  629. if (firstFrame) from->_timelinesRotation.setSize(timelines.size() << 1, 0);
  630. Vector<float> &timelinesRotation = from->_timelinesRotation;
  631. from->_totalAlpha = 0;
  632. for (size_t i = 0; i < timelineCount; i++) {
  633. Timeline *timeline = timelines[i];
  634. MixDirection direction = MixDirection_Out;
  635. MixBlend timelineBlend;
  636. float alpha;
  637. switch (timelineMode[i] & (NotLast - 1)) {
  638. case Subsequent:
  639. timelineBlend = blend;
  640. if (!attachments && (timeline->getRTTI().isExactly(AttachmentTimeline::rtti))) {
  641. if ((timelineMode[i] & NotLast) == NotLast) continue;
  642. timelineBlend = MixBlend_Setup;
  643. }
  644. if (!drawOrder && (timeline->getRTTI().isExactly(DrawOrderTimeline::rtti))) continue;
  645. alpha = alphaMix;
  646. break;
  647. case First:
  648. timelineBlend = MixBlend_Setup;
  649. alpha = alphaMix;
  650. break;
  651. case Hold:
  652. timelineBlend = MixBlend_Setup;
  653. alpha = alphaHold;
  654. break;
  655. default:
  656. timelineBlend = MixBlend_Setup;
  657. TrackEntry *holdMix = timelineHoldMix[i];
  658. alpha = alphaHold * MathUtil::max(0.0f, 1.0f - holdMix->_mixTime / holdMix->_mixDuration);
  659. break;
  660. }
  661. from->_totalAlpha += alpha;
  662. if ((timeline->getRTTI().isExactly(RotateTimeline::rtti))) {
  663. applyRotateTimeline((RotateTimeline*)timeline, skeleton, animationTime, alpha, timelineBlend, timelinesRotation, i << 1, firstFrame);
  664. } else {
  665. if (timelineBlend == MixBlend_Setup) {
  666. if (timeline->getRTTI().isExactly(AttachmentTimeline::rtti)) {
  667. if (attachments || (timelineMode[i] & NotLast) == NotLast) direction = MixDirection_In;
  668. } else if (timeline->getRTTI().isExactly(DrawOrderTimeline::rtti)) {
  669. if (drawOrder) direction = MixDirection_In;
  670. }
  671. }
  672. timeline->apply(skeleton, animationLast, animationTime, eventBuffer, alpha, timelineBlend, direction);
  673. }
  674. }
  675. }
  676. if (to->_mixDuration > 0) {
  677. queueEvents(from, animationTime);
  678. }
  679. _events.clear();
  680. from->_nextAnimationLast = animationTime;
  681. from->_nextTrackLast = from->_trackTime;
  682. return mix;
  683. }
  684. void AnimationState::queueEvents(TrackEntry *entry, float animationTime) {
  685. float animationStart = entry->_animationStart, animationEnd = entry->_animationEnd;
  686. float duration = animationEnd - animationStart;
  687. float trackLastWrapped = MathUtil::fmod(entry->_trackLast, duration);
  688. // Queue events before complete.
  689. size_t i = 0, n = _events.size();
  690. for (; i < n; ++i) {
  691. Event *e = _events[i];
  692. if (e->_time < trackLastWrapped) break;
  693. if (e->_time > animationEnd) continue; // Discard events outside animation start/end.
  694. _queue->event(entry, e);
  695. }
  696. // Queue complete if completed a loop iteration or the animation.
  697. bool complete = false;
  698. if (entry->_loop)
  699. complete = duration == 0 || (trackLastWrapped > MathUtil::fmod(entry->_trackTime, duration));
  700. else
  701. complete = animationTime >= animationEnd && entry->_animationLast < animationEnd;
  702. if (complete) _queue->complete(entry);
  703. // Queue events after complete.
  704. for (; i < n; ++i) {
  705. Event *e = _events[i];
  706. if (e->_time < animationStart) continue; // Discard events outside animation start/end.
  707. _queue->event(entry, _events[i]);
  708. }
  709. }
  710. void AnimationState::setCurrent(size_t index, TrackEntry *current, bool interrupt) {
  711. TrackEntry *from = expandToIndex(index);
  712. _tracks[index] = current;
  713. if (from != NULL) {
  714. if (interrupt) _queue->interrupt(from);
  715. current->_mixingFrom = from;
  716. from->_mixingTo = current;
  717. current->_mixTime = 0;
  718. // Store interrupted mix percentage.
  719. if (from->_mixingFrom != NULL && from->_mixDuration > 0) {
  720. current->_interruptAlpha *= MathUtil::min(1.0f, from->_mixTime / from->_mixDuration);
  721. }
  722. from->_timelinesRotation.clear(); // Reset rotation for mixing out, in case entry was mixed in.
  723. }
  724. _queue->start(current); // triggers animationsChanged
  725. }
  726. TrackEntry *AnimationState::expandToIndex(size_t index) {
  727. if (index < _tracks.size()) return _tracks[index];
  728. while (index >= _tracks.size())
  729. _tracks.add(NULL);
  730. return NULL;
  731. }
  732. TrackEntry *AnimationState::newTrackEntry(size_t trackIndex, Animation *animation, bool loop, TrackEntry *last) {
  733. TrackEntry *entryP = _trackEntryPool.obtain(); // Pooling
  734. TrackEntry &entry = *entryP;
  735. entry._trackIndex = trackIndex;
  736. entry._animation = animation;
  737. entry._loop = loop;
  738. entry._holdPrevious = 0;
  739. entry._eventThreshold = 0;
  740. entry._attachmentThreshold = 0;
  741. entry._drawOrderThreshold = 0;
  742. entry._animationStart = 0;
  743. entry._animationEnd = animation->getDuration();
  744. entry._animationLast = -1;
  745. entry._nextAnimationLast = -1;
  746. entry._delay = 0;
  747. entry._trackTime = 0;
  748. entry._trackLast = -1;
  749. entry._nextTrackLast = -1; // nextTrackLast == -1 signifies a TrackEntry that wasn't applied yet.
  750. entry._trackEnd = FLT_MAX; // loop ? float.MaxValue : animation.Duration;
  751. entry._timeScale = 1;
  752. entry._alpha = 1;
  753. entry._interruptAlpha = 1;
  754. entry._mixTime = 0;
  755. entry._mixDuration = (last == NULL) ? 0 : _data->getMix(last->_animation, animation);
  756. return entryP;
  757. }
  758. void AnimationState::disposeNext(TrackEntry *entry) {
  759. TrackEntry *next = entry->_next;
  760. while (next != NULL) {
  761. _queue->dispose(next);
  762. next = next->_next;
  763. }
  764. entry->_next = NULL;
  765. }
  766. void AnimationState::animationsChanged() {
  767. _animationsChanged = false;
  768. _propertyIDs.clear();
  769. for (size_t i = 0, n = _tracks.size(); i < n; ++i) {
  770. TrackEntry *entry = _tracks[i];
  771. if (!entry) continue;
  772. while (entry->_mixingFrom != NULL)
  773. entry = entry->_mixingFrom;
  774. do {
  775. if (entry->_mixingTo == NULL || entry->_mixBlend != MixBlend_Add) computeHold(entry);
  776. entry = entry->_mixingTo;
  777. } while (entry != NULL);
  778. }
  779. _propertyIDs.clear();
  780. for (int i = (int)_tracks.size() - 1; i >= 0; i--) {
  781. TrackEntry *entry = _tracks[i];
  782. while (entry) {
  783. computeNotLast(entry);
  784. entry = entry->_mixingFrom;
  785. }
  786. }
  787. }
  788. void AnimationState::computeHold(TrackEntry *entry) {
  789. TrackEntry* to = entry->_mixingTo;
  790. Vector<Timeline *> &timelines = entry->_animation->_timelines;
  791. size_t timelinesCount = timelines.size();
  792. Vector<int> &timelineMode = entry->_timelineMode;
  793. timelineMode.setSize(timelinesCount, 0);
  794. Vector<TrackEntry *> &timelineHoldMix = entry->_timelineHoldMix;
  795. timelineHoldMix.setSize(timelinesCount, 0);
  796. if (to != NULL && to->_holdPrevious) {
  797. for (size_t i = 0; i < timelinesCount; i++) {
  798. int id = timelines[i]->getPropertyId();
  799. if (!_propertyIDs.containsKey(id)) _propertyIDs.put(id, true);
  800. timelineMode[i] = Hold;
  801. }
  802. return;
  803. }
  804. // outer:
  805. size_t i = 0;
  806. continue_outer:
  807. for (; i < timelinesCount; ++i) {
  808. Timeline *timeline = timelines[i];
  809. int id = timeline->getPropertyId();
  810. if (_propertyIDs.containsKey(id)) {
  811. timelineMode[i] = Subsequent;
  812. } else {
  813. _propertyIDs.put(id, true);
  814. if (to == NULL || timeline->getRTTI().isExactly(AttachmentTimeline::rtti) ||
  815. timeline->getRTTI().isExactly(DrawOrderTimeline::rtti) ||
  816. timeline->getRTTI().isExactly(EventTimeline::rtti) || !to->_animation->hasTimeline(id)) {
  817. timelineMode[i] = First;
  818. } else {
  819. for (TrackEntry *next = to->_mixingTo; next != NULL; next = next->_mixingTo) {
  820. if (next->_animation->hasTimeline(id)) continue;
  821. if (entry->_mixDuration > 0) {
  822. timelineMode[i] = HoldMix;
  823. timelineHoldMix[i] = entry;
  824. i++;
  825. goto continue_outer; // continue outer;
  826. }
  827. break;
  828. }
  829. timelineMode[i] = Hold;
  830. }
  831. }
  832. }
  833. }
  834. void AnimationState::computeNotLast(TrackEntry *entry) {
  835. Vector<Timeline *> &timelines = entry->_animation->_timelines;
  836. size_t timelinesCount = timelines.size();
  837. Vector<int> &timelineMode = entry->_timelineMode;
  838. for (size_t i = 0; i < timelinesCount; i++) {
  839. if (timelines[i]->getRTTI().isExactly(AttachmentTimeline::rtti)) {
  840. AttachmentTimeline *timeline = static_cast<AttachmentTimeline *>(timelines[i]);
  841. if (!_propertyIDs.containsKey(timeline->getSlotIndex()))
  842. _propertyIDs.put(timeline->getSlotIndex(), true);
  843. else
  844. timelineMode[i] |= NotLast;
  845. }
  846. }
  847. }