AnimationState.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../Precompiled.h"
  4. #include "../Graphics/AnimatedModel.h"
  5. #include "../Graphics/Animation.h"
  6. #include "../Graphics/AnimationState.h"
  7. #include "../Graphics/DrawableEvents.h"
  8. #include "../IO/Log.h"
  9. #include "../DebugNew.h"
  10. namespace Urho3D
  11. {
  12. AnimationStateTrack::AnimationStateTrack() :
  13. track_(nullptr),
  14. bone_(nullptr),
  15. weight_(1.0f),
  16. keyFrame_(0)
  17. {
  18. }
  19. AnimationStateTrack::~AnimationStateTrack() = default;
  20. AnimationState::AnimationState(AnimatedModel* model, Animation* animation) :
  21. model_(model),
  22. animation_(animation),
  23. startBone_(nullptr),
  24. looped_(false),
  25. weight_(0.0f),
  26. time_(0.0f),
  27. layer_(0),
  28. blendingMode_(ABM_LERP)
  29. {
  30. // Set default start bone (use all tracks)
  31. SetStartBone(nullptr);
  32. }
  33. AnimationState::AnimationState(Node* node, Animation* animation) :
  34. node_(node),
  35. animation_(animation),
  36. startBone_(nullptr),
  37. looped_(false),
  38. weight_(1.0f),
  39. time_(0.0f),
  40. layer_(0),
  41. blendingMode_(ABM_LERP)
  42. {
  43. if (animation_)
  44. {
  45. // Setup animation track to scene node mapping
  46. if (node_)
  47. {
  48. const HashMap<StringHash, AnimationTrack>& tracks = animation_->GetTracks();
  49. stateTracks_.Clear();
  50. for (HashMap<StringHash, AnimationTrack>::ConstIterator i = tracks.Begin(); i != tracks.End(); ++i)
  51. {
  52. const StringHash& nameHash = i->second_.nameHash_;
  53. AnimationStateTrack stateTrack;
  54. stateTrack.track_ = &i->second_;
  55. if (node_->GetNameHash() == nameHash || tracks.Size() == 1)
  56. stateTrack.node_ = node_;
  57. else
  58. {
  59. Node* targetNode = node_->GetChild(nameHash, true);
  60. if (targetNode)
  61. stateTrack.node_ = targetNode;
  62. else
  63. URHO3D_LOGWARNING("Node " + i->second_.name_ + " not found for node animation " + animation_->GetName());
  64. }
  65. if (stateTrack.node_)
  66. stateTracks_.Push(stateTrack);
  67. }
  68. }
  69. }
  70. }
  71. AnimationState::~AnimationState() = default;
  72. void AnimationState::SetStartBone(Bone* startBone)
  73. {
  74. if (!model_ || !animation_)
  75. return;
  76. Skeleton& skeleton = model_->GetSkeleton();
  77. if (!startBone)
  78. {
  79. Bone* rootBone = skeleton.GetRootBone();
  80. if (!rootBone)
  81. return;
  82. startBone = rootBone;
  83. }
  84. // Do not reassign if the start bone did not actually change, and we already have valid bone nodes
  85. if (startBone == startBone_ && !stateTracks_.Empty())
  86. return;
  87. startBone_ = startBone;
  88. const HashMap<StringHash, AnimationTrack>& tracks = animation_->GetTracks();
  89. stateTracks_.Clear();
  90. if (!startBone->node_)
  91. return;
  92. for (HashMap<StringHash, AnimationTrack>::ConstIterator i = tracks.Begin(); i != tracks.End(); ++i)
  93. {
  94. AnimationStateTrack stateTrack;
  95. stateTrack.track_ = &i->second_;
  96. // Include those tracks that are either the start bone itself, or its children
  97. Bone* trackBone = nullptr;
  98. const StringHash& nameHash = i->second_.nameHash_;
  99. if (nameHash == startBone->nameHash_)
  100. trackBone = startBone;
  101. else
  102. {
  103. Node* trackBoneNode = startBone->node_->GetChild(nameHash, true);
  104. if (trackBoneNode)
  105. trackBone = skeleton.GetBone(nameHash);
  106. }
  107. if (trackBone && trackBone->node_)
  108. {
  109. stateTrack.bone_ = trackBone;
  110. stateTrack.node_ = trackBone->node_;
  111. stateTracks_.Push(stateTrack);
  112. }
  113. }
  114. model_->MarkAnimationDirty();
  115. }
  116. void AnimationState::SetLooped(bool looped)
  117. {
  118. looped_ = looped;
  119. }
  120. void AnimationState::SetWeight(float weight)
  121. {
  122. // Weight can only be set in model mode. In node animation it is hardcoded to full
  123. if (model_)
  124. {
  125. weight = Clamp(weight, 0.0f, 1.0f);
  126. if (weight != weight_)
  127. {
  128. weight_ = weight;
  129. model_->MarkAnimationDirty();
  130. }
  131. }
  132. }
  133. void AnimationState::SetBlendMode(AnimationBlendMode mode)
  134. {
  135. if (model_)
  136. {
  137. if (blendingMode_ != mode)
  138. {
  139. blendingMode_ = mode;
  140. model_->MarkAnimationDirty();
  141. }
  142. }
  143. }
  144. void AnimationState::SetTime(float time)
  145. {
  146. if (!animation_)
  147. return;
  148. time = Clamp(time, 0.0f, animation_->GetLength());
  149. if (time != time_)
  150. {
  151. time_ = time;
  152. if (model_)
  153. model_->MarkAnimationDirty();
  154. }
  155. }
  156. void AnimationState::SetBoneWeight(unsigned index, float weight, bool recursive)
  157. {
  158. if (index >= stateTracks_.Size())
  159. return;
  160. weight = Clamp(weight, 0.0f, 1.0f);
  161. if (weight != stateTracks_[index].weight_)
  162. {
  163. stateTracks_[index].weight_ = weight;
  164. if (model_)
  165. model_->MarkAnimationDirty();
  166. }
  167. if (recursive)
  168. {
  169. Node* boneNode = stateTracks_[index].node_;
  170. if (boneNode)
  171. {
  172. const Vector<SharedPtr<Node>>& children = boneNode->GetChildren();
  173. for (unsigned i = 0; i < children.Size(); ++i)
  174. {
  175. unsigned childTrackIndex = GetTrackIndex(children[i]);
  176. if (childTrackIndex != M_MAX_UNSIGNED)
  177. SetBoneWeight(childTrackIndex, weight, true);
  178. }
  179. }
  180. }
  181. }
  182. void AnimationState::SetBoneWeight(const String& name, float weight, bool recursive)
  183. {
  184. SetBoneWeight(GetTrackIndex(name), weight, recursive);
  185. }
  186. void AnimationState::SetBoneWeight(StringHash nameHash, float weight, bool recursive)
  187. {
  188. SetBoneWeight(GetTrackIndex(nameHash), weight, recursive);
  189. }
  190. void AnimationState::AddWeight(float delta)
  191. {
  192. if (delta == 0.0f)
  193. return;
  194. SetWeight(GetWeight() + delta);
  195. }
  196. void AnimationState::AddTime(float delta)
  197. {
  198. if (!animation_ || (!model_ && !node_))
  199. return;
  200. float length = animation_->GetLength();
  201. if (delta == 0.0f || length == 0.0f)
  202. return;
  203. bool sendFinishEvent = false;
  204. float oldTime = GetTime();
  205. float time = oldTime + delta;
  206. if (looped_)
  207. {
  208. while (time >= length)
  209. {
  210. time -= length;
  211. sendFinishEvent = true;
  212. }
  213. while (time < 0.0f)
  214. {
  215. time += length;
  216. sendFinishEvent = true;
  217. }
  218. }
  219. SetTime(time);
  220. if (!looped_)
  221. {
  222. if (delta > 0.0f && oldTime < length && GetTime() == length)
  223. sendFinishEvent = true;
  224. else if (delta < 0.0f && oldTime > 0.0f && GetTime() == 0.0f)
  225. sendFinishEvent = true;
  226. }
  227. // Process finish event
  228. if (sendFinishEvent)
  229. {
  230. using namespace AnimationFinished;
  231. WeakPtr<AnimationState> self(this);
  232. WeakPtr<Node> senderNode(model_ ? model_->GetNode() : node_);
  233. VariantMap& eventData = senderNode->GetEventDataMap();
  234. eventData[P_NODE] = senderNode;
  235. eventData[P_ANIMATION] = animation_;
  236. eventData[P_NAME] = animation_->GetAnimationName();
  237. eventData[P_LOOPED] = looped_;
  238. // Note: this may cause arbitrary deletion of animation states, including the one we are currently processing
  239. senderNode->SendEvent(E_ANIMATIONFINISHED, eventData);
  240. if (senderNode.Expired() || self.Expired())
  241. return;
  242. }
  243. // Process animation triggers
  244. if (animation_->GetNumTriggers())
  245. {
  246. bool wrap = false;
  247. if (delta > 0.0f)
  248. {
  249. if (oldTime > time)
  250. {
  251. oldTime -= length;
  252. wrap = true;
  253. }
  254. }
  255. if (delta < 0.0f)
  256. {
  257. if (time > oldTime)
  258. {
  259. time -= length;
  260. wrap = true;
  261. }
  262. }
  263. if (oldTime > time)
  264. Swap(oldTime, time);
  265. const Vector<AnimationTriggerPoint>& triggers = animation_->GetTriggers();
  266. for (Vector<AnimationTriggerPoint>::ConstIterator i = triggers.Begin(); i != triggers.End(); ++i)
  267. {
  268. float frameTime = i->time_;
  269. if (looped_ && wrap)
  270. frameTime = fmodf(frameTime, length);
  271. if (oldTime <= frameTime && time > frameTime)
  272. {
  273. using namespace AnimationTrigger;
  274. WeakPtr<AnimationState> self(this);
  275. WeakPtr<Node> senderNode(model_ ? model_->GetNode() : node_);
  276. VariantMap& eventData = senderNode->GetEventDataMap();
  277. eventData[P_NODE] = senderNode;
  278. eventData[P_ANIMATION] = animation_;
  279. eventData[P_NAME] = animation_->GetAnimationName();
  280. eventData[P_TIME] = i->time_;
  281. eventData[P_DATA] = i->data_;
  282. // Note: this may cause arbitrary deletion of animation states, including the one we are currently processing
  283. senderNode->SendEvent(E_ANIMATIONTRIGGER, eventData);
  284. if (senderNode.Expired() || self.Expired())
  285. return;
  286. }
  287. }
  288. }
  289. }
  290. void AnimationState::SetLayer(unsigned char layer)
  291. {
  292. if (layer != layer_)
  293. {
  294. layer_ = layer;
  295. if (model_)
  296. model_->MarkAnimationOrderDirty();
  297. }
  298. }
  299. AnimatedModel* AnimationState::GetModel() const
  300. {
  301. return model_;
  302. }
  303. Node* AnimationState::GetNode() const
  304. {
  305. return node_;
  306. }
  307. Bone* AnimationState::GetStartBone() const
  308. {
  309. return model_ ? startBone_ : nullptr;
  310. }
  311. float AnimationState::GetBoneWeight(unsigned index) const
  312. {
  313. return index < stateTracks_.Size() ? stateTracks_[index].weight_ : 0.0f;
  314. }
  315. float AnimationState::GetBoneWeight(const String& name) const
  316. {
  317. return GetBoneWeight(GetTrackIndex(name));
  318. }
  319. float AnimationState::GetBoneWeight(StringHash nameHash) const
  320. {
  321. return GetBoneWeight(GetTrackIndex(nameHash));
  322. }
  323. unsigned AnimationState::GetTrackIndex(const String& name) const
  324. {
  325. for (unsigned i = 0; i < stateTracks_.Size(); ++i)
  326. {
  327. Node* node = stateTracks_[i].node_;
  328. if (node && node->GetName() == name)
  329. return i;
  330. }
  331. return M_MAX_UNSIGNED;
  332. }
  333. unsigned AnimationState::GetTrackIndex(Node* node) const
  334. {
  335. for (unsigned i = 0; i < stateTracks_.Size(); ++i)
  336. {
  337. if (stateTracks_[i].node_ == node)
  338. return i;
  339. }
  340. return M_MAX_UNSIGNED;
  341. }
  342. unsigned AnimationState::GetTrackIndex(StringHash nameHash) const
  343. {
  344. for (unsigned i = 0; i < stateTracks_.Size(); ++i)
  345. {
  346. Node* node = stateTracks_[i].node_;
  347. if (node && node->GetNameHash() == nameHash)
  348. return i;
  349. }
  350. return M_MAX_UNSIGNED;
  351. }
  352. float AnimationState::GetLength() const
  353. {
  354. return animation_ ? animation_->GetLength() : 0.0f;
  355. }
  356. void AnimationState::Apply()
  357. {
  358. if (!animation_ || !IsEnabled())
  359. return;
  360. if (model_)
  361. ApplyToModel();
  362. else
  363. ApplyToNodes();
  364. }
  365. void AnimationState::ApplyToModel()
  366. {
  367. for (Vector<AnimationStateTrack>::Iterator i = stateTracks_.Begin(); i != stateTracks_.End(); ++i)
  368. {
  369. AnimationStateTrack& stateTrack = *i;
  370. float finalWeight = weight_ * stateTrack.weight_;
  371. // Do not apply if zero effective weight or the bone has animation disabled
  372. if (Equals(finalWeight, 0.0f) || !stateTrack.bone_->animated_)
  373. continue;
  374. ApplyTrack(stateTrack, finalWeight, true);
  375. }
  376. }
  377. void AnimationState::ApplyToNodes()
  378. {
  379. // When applying to a node hierarchy, can only use full weight (nothing to blend to)
  380. for (Vector<AnimationStateTrack>::Iterator i = stateTracks_.Begin(); i != stateTracks_.End(); ++i)
  381. ApplyTrack(*i, 1.0f, false);
  382. }
  383. void AnimationState::ApplyTrack(AnimationStateTrack& stateTrack, float weight, bool silent)
  384. {
  385. const AnimationTrack* track = stateTrack.track_;
  386. Node* node = stateTrack.node_;
  387. if (track->keyFrames_.Empty() || !node)
  388. return;
  389. unsigned& frame = stateTrack.keyFrame_;
  390. track->GetKeyFrameIndex(time_, frame);
  391. // Check if next frame to interpolate to is valid, or if wrapping is needed (looping animation only)
  392. unsigned nextFrame = frame + 1;
  393. bool interpolate = true;
  394. if (nextFrame >= track->keyFrames_.Size())
  395. {
  396. if (!looped_)
  397. {
  398. nextFrame = frame;
  399. interpolate = false;
  400. }
  401. else
  402. nextFrame = 0;
  403. }
  404. const AnimationKeyFrame* keyFrame = &track->keyFrames_[frame];
  405. const AnimationChannelFlags channelMask = track->channelMask_;
  406. Vector3 newPosition;
  407. Quaternion newRotation;
  408. Vector3 newScale;
  409. if (interpolate)
  410. {
  411. const AnimationKeyFrame* nextKeyFrame = &track->keyFrames_[nextFrame];
  412. float timeInterval = nextKeyFrame->time_ - keyFrame->time_;
  413. if (timeInterval < 0.0f)
  414. timeInterval += animation_->GetLength();
  415. float t = timeInterval > 0.0f ? (time_ - keyFrame->time_) / timeInterval : 1.0f;
  416. if (channelMask & CHANNEL_POSITION)
  417. newPosition = keyFrame->position_.Lerp(nextKeyFrame->position_, t);
  418. if (channelMask & CHANNEL_ROTATION)
  419. newRotation = keyFrame->rotation_.Slerp(nextKeyFrame->rotation_, t);
  420. if (channelMask & CHANNEL_SCALE)
  421. newScale = keyFrame->scale_.Lerp(nextKeyFrame->scale_, t);
  422. }
  423. else
  424. {
  425. if (channelMask & CHANNEL_POSITION)
  426. newPosition = keyFrame->position_;
  427. if (channelMask & CHANNEL_ROTATION)
  428. newRotation = keyFrame->rotation_;
  429. if (channelMask & CHANNEL_SCALE)
  430. newScale = keyFrame->scale_;
  431. }
  432. if (blendingMode_ == ABM_ADDITIVE) // not ABM_LERP
  433. {
  434. if (channelMask & CHANNEL_POSITION)
  435. {
  436. Vector3 delta = newPosition - stateTrack.bone_->initialPosition_;
  437. newPosition = node->GetPosition() + delta * weight;
  438. }
  439. if (channelMask & CHANNEL_ROTATION)
  440. {
  441. Quaternion delta = newRotation * stateTrack.bone_->initialRotation_.Inverse();
  442. newRotation = (delta * node->GetRotation()).Normalized();
  443. if (!Equals(weight, 1.0f))
  444. newRotation = node->GetRotation().Slerp(newRotation, weight);
  445. }
  446. if (channelMask & CHANNEL_SCALE)
  447. {
  448. Vector3 delta = newScale - stateTrack.bone_->initialScale_;
  449. newScale = node->GetScale() + delta * weight;
  450. }
  451. }
  452. else
  453. {
  454. if (!Equals(weight, 1.0f)) // not full weight
  455. {
  456. if (channelMask & CHANNEL_POSITION)
  457. newPosition = node->GetPosition().Lerp(newPosition, weight);
  458. if (channelMask & CHANNEL_ROTATION)
  459. newRotation = node->GetRotation().Slerp(newRotation, weight);
  460. if (channelMask & CHANNEL_SCALE)
  461. newScale = node->GetScale().Lerp(newScale, weight);
  462. }
  463. }
  464. if (silent)
  465. {
  466. if (channelMask & CHANNEL_POSITION)
  467. node->SetPositionSilent(newPosition);
  468. if (channelMask & CHANNEL_ROTATION)
  469. node->SetRotationSilent(newRotation);
  470. if (channelMask & CHANNEL_SCALE)
  471. node->SetScaleSilent(newScale);
  472. }
  473. else
  474. {
  475. if (channelMask & CHANNEL_POSITION)
  476. node->SetPosition(newPosition);
  477. if (channelMask & CHANNEL_ROTATION)
  478. node->SetRotation(newRotation);
  479. if (channelMask & CHANNEL_SCALE)
  480. node->SetScale(newScale);
  481. }
  482. }
  483. }