AnimatedSprite2D.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../IO/Log.h"
  25. #include "../Resource/ResourceCache.h"
  26. #include "../Scene/Scene.h"
  27. #include "../Scene/SceneEvents.h"
  28. #include "../Atomic2D/AnimatedSprite2D.h"
  29. #include "../Atomic2D/AnimationSet2D.h"
  30. #include "../Atomic2D/Sprite2D.h"
  31. #include "../DebugNew.h"
  32. namespace Atomic
  33. {
  34. extern const char* ATOMIC2D_CATEGORY;
  35. extern const char* blendModeNames[];
  36. const char* loopModeNames[] =
  37. {
  38. "Default",
  39. "ForceLooped",
  40. "ForceClamped",
  41. 0
  42. };
  43. AnimatedSprite2D::AnimatedSprite2D(Context* context) :
  44. StaticSprite2D(context),
  45. speed_(1.0f),
  46. loopMode_(LM_DEFAULT),
  47. looped_(false),
  48. currentTime_(0.0f),
  49. numTracks_(0)
  50. {
  51. }
  52. AnimatedSprite2D::~AnimatedSprite2D()
  53. {
  54. }
  55. void AnimatedSprite2D::RegisterObject(Context* context)
  56. {
  57. context->RegisterFactory<AnimatedSprite2D>(ATOMIC2D_CATEGORY);
  58. COPY_BASE_ATTRIBUTES(StaticSprite2D);
  59. REMOVE_ATTRIBUTE("Sprite");
  60. ACCESSOR_ATTRIBUTE("Speed", GetSpeed, SetSpeed, float, 1.0f, AM_DEFAULT);
  61. MIXED_ACCESSOR_ATTRIBUTE("Animation Set", GetAnimationSetAttr, SetAnimationSetAttr, ResourceRef,
  62. ResourceRef(AnimatedSprite2D::GetTypeStatic()), AM_DEFAULT);
  63. ACCESSOR_ATTRIBUTE("Animation", GetAnimation, SetAnimationAttr, String, String::EMPTY, AM_DEFAULT);
  64. ENUM_ACCESSOR_ATTRIBUTE("Loop Mode", GetLoopMode, SetLoopMode, LoopMode2D, loopModeNames, LM_DEFAULT, AM_DEFAULT);
  65. }
  66. void AnimatedSprite2D::OnSetEnabled()
  67. {
  68. StaticSprite2D::OnSetEnabled();
  69. bool enabled = IsEnabledEffective();
  70. Scene* scene = GetScene();
  71. if (scene)
  72. {
  73. if (enabled)
  74. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
  75. else
  76. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  77. }
  78. for (unsigned i = 0; i < trackNodes_.Size(); ++i)
  79. {
  80. if (!trackNodes_[i])
  81. continue;
  82. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  83. if (staticSprite)
  84. staticSprite->SetEnabled(enabled);
  85. }
  86. }
  87. void AnimatedSprite2D::SetSpeed(float speed)
  88. {
  89. speed_ = speed;
  90. MarkNetworkUpdate();
  91. }
  92. void AnimatedSprite2D::SetAnimation(AnimationSet2D* animationSet, const String& name, LoopMode2D loopMode)
  93. {
  94. animationSet_ = animationSet;
  95. SetAnimation(name, loopMode);
  96. }
  97. void AnimatedSprite2D::SetAnimation(const String& name, LoopMode2D loopMode)
  98. {
  99. animationName_ = name;
  100. if (animationSet_)
  101. SetAnimation(animationSet_->GetAnimation(animationName_), loopMode);
  102. }
  103. void AnimatedSprite2D::SetAnimationSet(AnimationSet2D* animationSet)
  104. {
  105. if (animationSet == animationSet_)
  106. return;
  107. animationSet_ = animationSet;
  108. SetAnimation(animationName_, loopMode_);
  109. }
  110. void AnimatedSprite2D::SetLoopMode(LoopMode2D loopMode)
  111. {
  112. if (!animation_)
  113. return;
  114. loopMode_ = loopMode;
  115. switch (loopMode_)
  116. {
  117. case LM_FORCE_LOOPED:
  118. looped_ = true;
  119. break;
  120. case LM_FORCE_CLAMPED:
  121. looped_ = false;
  122. break;
  123. default:
  124. looped_ = animation_->IsLooped();
  125. break;
  126. }
  127. }
  128. AnimationSet2D* AnimatedSprite2D::GetAnimationSet() const
  129. {
  130. return animationSet_;
  131. }
  132. Node* AnimatedSprite2D::GetRootNode() const
  133. {
  134. return rootNode_;
  135. }
  136. void AnimatedSprite2D::SetAnimationSetAttr(const ResourceRef& value)
  137. {
  138. ResourceCache* cache = GetSubsystem<ResourceCache>();
  139. SetAnimationSet(cache->GetResource<AnimationSet2D>(value.name_));
  140. }
  141. ResourceRef AnimatedSprite2D::GetAnimationSetAttr() const
  142. {
  143. return GetResourceRef(animationSet_, AnimationSet2D::GetTypeStatic());
  144. }
  145. void AnimatedSprite2D::OnSceneSet(Scene* scene)
  146. {
  147. StaticSprite2D::OnSceneSet(scene);
  148. if (scene)
  149. {
  150. if (scene == node_)
  151. LOGWARNING(GetTypeName() + " should not be created to the root scene node");
  152. if (IsEnabledEffective())
  153. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
  154. }
  155. else
  156. UnsubscribeFromEvent(E_SCENEPOSTUPDATE);
  157. }
  158. void AnimatedSprite2D::SetAnimationAttr(const String& name)
  159. {
  160. animationName_ = name;
  161. if (animationSet_)
  162. SetAnimation(animationSet_->GetAnimation(animationName_), loopMode_);
  163. }
  164. void AnimatedSprite2D::OnWorldBoundingBoxUpdate()
  165. {
  166. boundingBox_.Clear();
  167. worldBoundingBox_.Clear();
  168. for (unsigned i = 0; i < numTracks_; ++i)
  169. {
  170. if (!trackNodes_[i])
  171. continue;
  172. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  173. if (staticSprite)
  174. worldBoundingBox_.Merge(staticSprite->GetWorldBoundingBox());
  175. }
  176. boundingBox_ = worldBoundingBox_.Transformed(node_->GetWorldTransform().Inverse());
  177. }
  178. void AnimatedSprite2D::OnDrawOrderChanged()
  179. {
  180. for (unsigned i = 0; i < numTracks_; ++i)
  181. {
  182. if (!trackNodes_[i])
  183. continue;
  184. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  185. if (staticSprite)
  186. staticSprite->SetLayer(layer_);
  187. }
  188. }
  189. void AnimatedSprite2D::OnFlipChanged()
  190. {
  191. for (unsigned i = 0; i < numTracks_; ++i)
  192. {
  193. if (!trackNodes_[i])
  194. continue;
  195. StaticSprite2D* staticSprite = trackNodes_[i]->GetComponent<StaticSprite2D>();
  196. if (staticSprite)
  197. staticSprite->SetFlip(flipX_, flipY_);
  198. }
  199. // For editor paused mode
  200. UpdateAnimation(0.0f);
  201. }
  202. void AnimatedSprite2D::UpdateSourceBatches()
  203. {
  204. sourceBatchesDirty_ = false;
  205. }
  206. void AnimatedSprite2D::SetAnimation(Animation2D* animation, LoopMode2D loopMode)
  207. {
  208. if (animation == animation_)
  209. {
  210. SetLoopMode(loopMode_);
  211. currentTime_ = 0.0f;
  212. UpdateAnimation(0.0f);
  213. return;
  214. }
  215. for (unsigned i = 0; i < numTracks_; ++i)
  216. {
  217. if (trackNodes_[i])
  218. trackNodes_[i]->SetEnabled(false);
  219. }
  220. numTracks_ = 0;
  221. trackNodes_.Clear();
  222. trackNodeInfos_.Clear();
  223. animation_ = animation;
  224. if (!animation_)
  225. return;
  226. currentTime_ = 0.0f;
  227. if (!rootNode_)
  228. {
  229. rootNode_ = GetNode()->CreateChild("_root_", LOCAL);
  230. rootNode_->SetTemporary(true);
  231. }
  232. numTracks_ = animation_->GetNumTracks();
  233. trackNodes_.Resize(numTracks_);
  234. trackNodeInfos_.Resize(numTracks_);
  235. for (unsigned i = 0; i < numTracks_; ++i)
  236. {
  237. const AnimationTrack2D& track = animation->GetTrack(i);
  238. SharedPtr<Node> trackNode(rootNode_->GetChild(track.name_));
  239. StaticSprite2D* staticSprite = 0;
  240. if (trackNode)
  241. {
  242. // Enable track node
  243. trackNode->SetEnabled(true);
  244. // Get StaticSprite2D component
  245. if (track.hasSprite_)
  246. staticSprite = trackNode->GetComponent<StaticSprite2D>();
  247. }
  248. else
  249. {
  250. // Create new track node
  251. trackNode = rootNode_->CreateChild(track.name_, LOCAL);
  252. trackNode->SetTemporary(true);
  253. // Create StaticSprite2D component
  254. if (track.hasSprite_)
  255. {
  256. staticSprite = trackNode->CreateComponent<StaticSprite2D>();
  257. staticSprite->SetEnabled(IsEnabledEffective());
  258. }
  259. }
  260. if (staticSprite)
  261. {
  262. staticSprite->SetLayer(layer_);
  263. staticSprite->SetBlendMode(blendMode_);
  264. staticSprite->SetFlip(flipX_, flipY_);
  265. staticSprite->SetUseHotSpot(true);
  266. }
  267. trackNodes_[i] = trackNode;
  268. trackNodeInfos_[i].hasSprite = track.hasSprite_;
  269. }
  270. SetLoopMode(loopMode);
  271. UpdateAnimation(0.0f);
  272. MarkNetworkUpdate();
  273. }
  274. void AnimatedSprite2D::UpdateAnimation(float timeStep)
  275. {
  276. if (!animation_)
  277. return;
  278. currentTime_ += timeStep * speed_;
  279. float time;
  280. float animationLength = animation_->GetLength();
  281. if (looped_)
  282. {
  283. time = fmodf(currentTime_, animationLength);
  284. if (time < 0.0f)
  285. time += animation_->GetLength();
  286. }
  287. else
  288. time = Clamp(currentTime_, 0.0f, animationLength);
  289. for (unsigned i = 0; i < numTracks_; ++i)
  290. {
  291. trackNodeInfos_[i].worldSpace = false;
  292. const AnimationTrack2D& track = animation_->GetTrack(i);
  293. const Vector<AnimationKeyFrame2D>& keyFrames = track.keyFrames_;
  294. // Time out of range
  295. if (time < keyFrames[0].time_ || time > keyFrames.Back().time_)
  296. trackNodeInfos_[i].value.enabled_ = false;
  297. else
  298. {
  299. unsigned index = keyFrames.Size() - 1;
  300. for (unsigned j = 0; j < keyFrames.Size() - 1; ++j)
  301. {
  302. if (time <= keyFrames[j + 1].time_)
  303. {
  304. index = j;
  305. break;
  306. }
  307. }
  308. const AnimationKeyFrame2D& currKey = keyFrames[index];
  309. AnimationKeyFrame2D& value = trackNodeInfos_[i].value;
  310. value.enabled_ = currKey.enabled_;
  311. value.parent_ = currKey.parent_;
  312. if (index < keyFrames.Size() - 1)
  313. {
  314. const AnimationKeyFrame2D& nextKey = keyFrames[index + 1];
  315. float t = (time - currKey.time_) / (nextKey.time_ - currKey.time_);
  316. value.transform_ = currKey.transform_.Lerp(nextKey.transform_, t, currKey.spin_);
  317. if (trackNodeInfos_[i].hasSprite)
  318. value.alpha_ = Atomic::Lerp(currKey.alpha_, nextKey.alpha_, t);
  319. }
  320. else
  321. {
  322. value.transform_ = currKey.transform_;
  323. if (trackNodeInfos_[i].hasSprite)
  324. value.alpha_ = currKey.alpha_;
  325. }
  326. if (trackNodeInfos_[i].hasSprite)
  327. {
  328. value.zIndex_ = currKey.zIndex_;
  329. value.sprite_ = currKey.sprite_;
  330. value.useHotSpot_ = currKey.useHotSpot_;
  331. value.hotSpot_ = currKey.hotSpot_;
  332. }
  333. }
  334. }
  335. for (unsigned i = 0; i < numTracks_; ++i)
  336. {
  337. Node* node = trackNodes_[i];
  338. if (!node)
  339. continue;
  340. TrackNodeInfo& nodeInfo = trackNodeInfos_[i];
  341. if (!nodeInfo.value.enabled_)
  342. node->SetEnabled(false);
  343. else
  344. {
  345. node->SetEnabled(true);
  346. // Calculate world transform.
  347. CalculateTimelineWorldTransform(i);
  348. // Update node's transform
  349. Vector2 position = nodeInfo.value.transform_.position_ * PIXEL_SIZE;
  350. if (flipX_)
  351. position.x_ = -position.x_;
  352. if (flipY_)
  353. position.y_ = -position.y_;
  354. node->SetPosition(position);
  355. float angle = nodeInfo.value.transform_.angle_;
  356. if (flipX_ != flipY_)
  357. angle = -angle;
  358. node->SetRotation(angle);
  359. node->SetScale(nodeInfo.value.transform_.scale_);
  360. if (nodeInfo.hasSprite)
  361. {
  362. StaticSprite2D* staticSprite = node->GetComponent<StaticSprite2D>();
  363. if (staticSprite)
  364. {
  365. staticSprite->SetOrderInLayer(orderInLayer_ + nodeInfo.value.zIndex_);
  366. staticSprite->SetSprite(nodeInfo.value.sprite_);
  367. staticSprite->SetAlpha(nodeInfo.value.alpha_);
  368. staticSprite->SetUseHotSpot(nodeInfo.value.useHotSpot_);
  369. staticSprite->SetHotSpot(nodeInfo.value.hotSpot_);
  370. }
  371. }
  372. }
  373. }
  374. }
  375. void AnimatedSprite2D::CalculateTimelineWorldTransform(int index)
  376. {
  377. TrackNodeInfo& info = trackNodeInfos_[index];
  378. if (info.worldSpace)
  379. return;
  380. info.worldSpace = true;
  381. int parent = info.value.parent_;
  382. if (parent != -1)
  383. {
  384. CalculateTimelineWorldTransform(parent);
  385. info.value.transform_ = trackNodeInfos_[parent].value.transform_ * info.value.transform_;
  386. }
  387. }
  388. void AnimatedSprite2D::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  389. {
  390. using namespace ScenePostUpdate;
  391. float timeStep = eventData[P_TIMESTEP].GetFloat();
  392. UpdateAnimation(timeStep);
  393. }
  394. }