AnimatedSprite2D.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. //
  2. // Copyright (c) 2008-2014 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 "AnimatedSprite2D.h"
  24. #include "Animation2D.h"
  25. #include "AnimationSet2D.h"
  26. #include "Context.h"
  27. #include "Drawable2D.h"
  28. #include "ResourceCache.h"
  29. #include "Scene.h"
  30. #include "SceneEvents.h"
  31. #include "Sprite2D.h"
  32. #include "StaticSprite2D.h"
  33. #include "DebugNew.h"
  34. namespace Urho3D
  35. {
  36. extern const char* URHO2D_CATEGORY;
  37. extern const char* blendModeNames[];
  38. const char* loopModeNames[] =
  39. {
  40. "Default",
  41. "ForceLooped",
  42. "ForceClamped",
  43. 0
  44. };
  45. template<> LoopMode2D Variant::Get<LoopMode2D>() const
  46. {
  47. return (LoopMode2D)GetInt();
  48. }
  49. AnimatedSprite2D::AnimatedSprite2D(Context* context) :
  50. Drawable(context, DRAWABLE_GEOMETRY),
  51. layer_(0),
  52. orderInLayer_(0),
  53. blendMode_(BLEND_ALPHA),
  54. flipX_(false),
  55. flipY_(false),
  56. color_(Color::WHITE),
  57. speed_(1.0f),
  58. loopMode_(LM_DEFAULT),
  59. looped_(false),
  60. currentTime_(0.0f)
  61. {
  62. }
  63. AnimatedSprite2D::~AnimatedSprite2D()
  64. {
  65. }
  66. void AnimatedSprite2D::RegisterObject(Context* context)
  67. {
  68. context->RegisterFactory<AnimatedSprite2D>(URHO2D_CATEGORY);
  69. ACCESSOR_ATTRIBUTE("Layer", GetLayer, SetLayer, int, 0, AM_DEFAULT);
  70. ACCESSOR_ATTRIBUTE("Order in Layer", GetOrderInLayer, SetOrderInLayer, int, 0, AM_DEFAULT);
  71. ENUM_ACCESSOR_ATTRIBUTE("Blend Mode", GetBlendMode, SetBlendMode, BlendMode, blendModeNames, BLEND_ALPHA, AM_DEFAULT);
  72. ACCESSOR_ATTRIBUTE("Flip X", GetFlipX, SetFlipX, bool, false, AM_DEFAULT);
  73. ACCESSOR_ATTRIBUTE("Flip Y", GetFlipY, SetFlipY, bool, false, AM_DEFAULT);
  74. REF_ACCESSOR_ATTRIBUTE("Color", GetColor, SetColor, Color, Color::WHITE, AM_DEFAULT);
  75. ACCESSOR_ATTRIBUTE("Speed", GetSpeed, SetSpeed, float, 1.0f, AM_DEFAULT);
  76. MIXED_ACCESSOR_ATTRIBUTE("Animation Set", GetAnimationSetAttr, SetAnimationSetAttr, ResourceRef, ResourceRef(AnimatedSprite2D::GetTypeStatic()), AM_DEFAULT);
  77. REF_ACCESSOR_ATTRIBUTE("Animation", GetAnimation, SetAnimationAttr, String, String::EMPTY, AM_DEFAULT);
  78. ENUM_ACCESSOR_ATTRIBUTE("Loop Mode", GetLoopMode, SetLoopMode, LoopMode2D, loopModeNames, LM_DEFAULT, AM_DEFAULT);
  79. COPY_BASE_ATTRIBUTES(Drawable);
  80. }
  81. void AnimatedSprite2D::OnSetEnabled()
  82. {
  83. Drawable::OnSetEnabled();
  84. Scene* scene = GetScene();
  85. if (scene)
  86. {
  87. if (IsEnabledEffective())
  88. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
  89. else
  90. UnsubscribeFromEvent(scene, E_SCENEPOSTUPDATE);
  91. }
  92. }
  93. void AnimatedSprite2D::SetLayer(int layer)
  94. {
  95. if (layer == layer_)
  96. return;
  97. layer_ = layer;
  98. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  99. {
  100. if (!timelineNodes_[i])
  101. continue;
  102. StaticSprite2D* staticSprite = timelineNodes_[i]->GetComponent<StaticSprite2D>();
  103. staticSprite->SetLayer(layer_);
  104. }
  105. }
  106. void AnimatedSprite2D::SetOrderInLayer(int orderInLayer)
  107. {
  108. orderInLayer_ = orderInLayer;
  109. }
  110. void AnimatedSprite2D::SetBlendMode(BlendMode blendMode)
  111. {
  112. if (blendMode == blendMode_)
  113. return;
  114. blendMode_ = blendMode;
  115. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  116. {
  117. if (!timelineNodes_[i])
  118. continue;
  119. StaticSprite2D* staticSprite = timelineNodes_[i]->GetComponent<StaticSprite2D>();
  120. staticSprite->SetBlendMode(blendMode_);
  121. }
  122. }
  123. void AnimatedSprite2D::SetFlip(bool flipX, bool flipY)
  124. {
  125. if (flipX == flipX_ && flipY == flipY_)
  126. return;
  127. flipX_ = flipX;
  128. flipY_ = flipY;
  129. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  130. {
  131. if (!timelineNodes_[i])
  132. continue;
  133. StaticSprite2D* staticSprite = timelineNodes_[i]->GetComponent<StaticSprite2D>();
  134. staticSprite->SetFlip(flipX_, flipY_);
  135. }
  136. // For editor paused mode
  137. UpdateAnimation(0.0f);
  138. MarkNetworkUpdate();
  139. }
  140. void AnimatedSprite2D::SetFlipX(bool flipX)
  141. {
  142. SetFlip(flipX, flipY_);
  143. }
  144. void AnimatedSprite2D::SetFlipY(bool flipY)
  145. {
  146. SetFlip(flipX_, flipY);
  147. }
  148. void AnimatedSprite2D::SetColor(const Color& color)
  149. {
  150. color_ = color;
  151. MarkNetworkUpdate();
  152. }
  153. void AnimatedSprite2D::SetSpeed(float speed)
  154. {
  155. speed_ = speed;
  156. MarkNetworkUpdate();
  157. }
  158. void AnimatedSprite2D::SetAnimation(AnimationSet2D* animationSet, const String& name, LoopMode2D loopMode)
  159. {
  160. animationSet_ = animationSet;
  161. SetAnimation(name, loopMode);
  162. }
  163. void AnimatedSprite2D::SetAnimation(const String& name, LoopMode2D loopMode)
  164. {
  165. animationName_ = name;
  166. if (animationSet_)
  167. SetAnimation(animationSet_->GetAnimation(animationName_), loopMode);
  168. }
  169. void AnimatedSprite2D::SetAnimationSet(AnimationSet2D* animationSet)
  170. {
  171. if (animationSet == animationSet_)
  172. return;
  173. animationSet_ = animationSet;
  174. SetAnimation(animationName_, loopMode_);
  175. }
  176. void AnimatedSprite2D::SetLoopMode(LoopMode2D loopMode)
  177. {
  178. if (!animation_)
  179. return;
  180. loopMode_ = loopMode;
  181. switch (loopMode_)
  182. {
  183. case LM_FORCE_LOOPED:
  184. looped_ = true;
  185. break;
  186. case LM_FORCE_CLAMPED:
  187. looped_ = false;
  188. break;
  189. default:
  190. looped_ = animation_->IsLooped();
  191. break;
  192. }
  193. }
  194. AnimationSet2D* AnimatedSprite2D::GetAnimationSet() const
  195. {
  196. return animationSet_;
  197. }
  198. Node* AnimatedSprite2D::GetRootNode() const
  199. {
  200. return rootNode_;
  201. }
  202. void AnimatedSprite2D::SetAnimationSetAttr(const ResourceRef& value)
  203. {
  204. ResourceCache* cache = GetSubsystem<ResourceCache>();
  205. SetAnimationSet(cache->GetResource<AnimationSet2D>(value.name_));
  206. }
  207. ResourceRef AnimatedSprite2D::GetAnimationSetAttr() const
  208. {
  209. return GetResourceRef(animationSet_, AnimationSet2D::GetTypeStatic());
  210. }
  211. void AnimatedSprite2D::OnNodeSet(Node* node)
  212. {
  213. Drawable::OnNodeSet(node);
  214. if (node)
  215. {
  216. Scene* scene = GetScene();
  217. if (scene && IsEnabledEffective())
  218. SubscribeToEvent(scene, E_SCENEPOSTUPDATE, HANDLER(AnimatedSprite2D, HandleScenePostUpdate));
  219. }
  220. else
  221. {
  222. if (rootNode_)
  223. rootNode_->Remove();
  224. rootNode_ = 0;
  225. timelineNodes_.Clear();
  226. }
  227. }
  228. void AnimatedSprite2D::SetAnimationAttr(const String& name)
  229. {
  230. animationName_ = name;
  231. if (animationSet_)
  232. SetAnimation(animationSet_->GetAnimation(animationName_), loopMode_);
  233. }
  234. void AnimatedSprite2D::OnWorldBoundingBoxUpdate()
  235. {
  236. boundingBox_.Clear();
  237. worldBoundingBox_.Clear();
  238. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  239. {
  240. if (!timelineNodes_[i])
  241. continue;
  242. StaticSprite2D* staticSprite = timelineNodes_[i]->GetComponent<StaticSprite2D>();
  243. if (staticSprite)
  244. worldBoundingBox_.Merge(staticSprite->GetWorldBoundingBox());
  245. }
  246. boundingBox_ = worldBoundingBox_.Transformed(node_->GetWorldTransform().Inverse());
  247. }
  248. void AnimatedSprite2D::SetAnimation(Animation2D* animation, LoopMode2D loopMode)
  249. {
  250. if (animation == animation_)
  251. {
  252. SetLoopMode(loopMode_);
  253. currentTime_ = 0.0f;
  254. UpdateAnimation(0.0f);
  255. return;
  256. }
  257. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  258. {
  259. if (timelineNodes_[i])
  260. timelineNodes_[i]->SetEnabled(false);
  261. }
  262. timelineNodes_.Clear();
  263. animation_ = animation;
  264. if (!animation_)
  265. return;
  266. currentTime_ = 0.0f;
  267. if (!rootNode_)
  268. {
  269. rootNode_ = GetNode()->CreateChild("RootNode", LOCAL);
  270. rootNode_->SetTemporary(true);
  271. }
  272. timelineNodes_.Resize(animation_->GetNumTimelines());
  273. timelineTransformInfos_.Resize(animation_->GetNumTimelines());
  274. for (unsigned i = 0; i < animation_->GetNumTimelines(); ++i)
  275. {
  276. const Timeline2D& timeline = animation->GetTimeline(i);
  277. SharedPtr<Node> timelineNode(rootNode_->GetChild(timeline.name_));
  278. StaticSprite2D* staticSprite = 0;
  279. if (timelineNode)
  280. {
  281. // Enable timeline node
  282. timelineNode->SetEnabled(true);
  283. // Get StaticSprite2D component
  284. if (timeline.type_ == OT_SPRITE)
  285. staticSprite = timelineNode->GetComponent<StaticSprite2D>();
  286. }
  287. else
  288. {
  289. // Create new timeline node
  290. timelineNode = rootNode_->CreateChild(timeline.name_, LOCAL);
  291. // Create StaticSprite2D component
  292. if (timeline.type_ == OT_SPRITE)
  293. staticSprite = timelineNode->CreateComponent<StaticSprite2D>();
  294. }
  295. if (staticSprite)
  296. {
  297. staticSprite->SetLayer(layer_);
  298. staticSprite->SetBlendMode(blendMode_);
  299. staticSprite->SetFlip(flipX_, flipY_);
  300. staticSprite->SetUseHotSpot(true);
  301. }
  302. timelineNodes_[i] = timelineNode;
  303. timelineTransformInfos_[i].parent_ = timeline.parent_;
  304. }
  305. SetLoopMode(loopMode);
  306. UpdateAnimation(0.0f);
  307. MarkNetworkUpdate();
  308. }
  309. void AnimatedSprite2D::UpdateAnimation(float timeStep)
  310. {
  311. if (!animation_)
  312. return;
  313. currentTime_ += timeStep * speed_;
  314. float time;
  315. float animtationLength = animation_->GetLength();
  316. if (looped_)
  317. {
  318. time = fmodf(currentTime_, animtationLength);
  319. if (time < 0.0f)
  320. time += animation_->GetLength();
  321. }
  322. else
  323. time = Clamp(currentTime_, 0.0f, animtationLength);
  324. // Update timeline's local transform
  325. for (unsigned i = 0; i < timelineTransformInfos_.Size(); ++i)
  326. {
  327. const Timeline2D& timeline = animation_->GetTimeline(i);
  328. const Vector<TimelineKey2D>& objectKeys = timeline.timelineKeys_;
  329. unsigned index = objectKeys.Size() - 1;
  330. for (unsigned j = 0; j < objectKeys.Size() - 1; ++j)
  331. {
  332. if (time <= objectKeys[j + 1].time_)
  333. {
  334. index = j;
  335. break;
  336. }
  337. }
  338. const TimelineKey2D& currKey = objectKeys[index];
  339. if (index < objectKeys.Size() - 1)
  340. {
  341. const TimelineKey2D& nextKey = objectKeys[index + 1];
  342. float t = (time - currKey.time_) / (nextKey.time_ - currKey.time_);
  343. timelineTransformInfos_[i].worldSpace_ = false;
  344. timelineTransformInfos_[i].transform_ = currKey.transform_.Lerp(nextKey.transform_, t, currKey.spin_);
  345. // Update sprite's sprite and hot spot and color
  346. Node* timelineNode = timelineNodes_[i];
  347. if (timelineNode)
  348. {
  349. StaticSprite2D* staticSprite = timelineNode->GetComponent<StaticSprite2D>();
  350. if (staticSprite)
  351. {
  352. staticSprite->SetSprite(currKey.sprite_);
  353. staticSprite->SetHotSpot(currKey.hotSpot_.Lerp(nextKey.hotSpot_, t));
  354. float alpha = Lerp(currKey.alpha_, nextKey.alpha_, t);
  355. staticSprite->SetColor(Color(color_.r_, color_.g_, color_.b_, color_.a_ * alpha));
  356. }
  357. }
  358. }
  359. else
  360. {
  361. timelineTransformInfos_[i].worldSpace_ = false;
  362. timelineTransformInfos_[i].transform_ = currKey.transform_;
  363. // Update sprite's sprite and hot spot and color
  364. Node* timelineNode = timelineNodes_[i];
  365. if (timelineNode)
  366. {
  367. StaticSprite2D* staticSprite = timelineNode->GetComponent<StaticSprite2D>();
  368. if (staticSprite)
  369. {
  370. staticSprite->SetSprite(currKey.sprite_);
  371. staticSprite->SetHotSpot(currKey.hotSpot_);
  372. staticSprite->SetColor(Color(color_.r_, color_.g_, color_.b_, color_.a_ * currKey.alpha_));
  373. }
  374. }
  375. }
  376. }
  377. // Calculate timeline world transform.
  378. for (unsigned i = 0; i < timelineTransformInfos_.Size(); ++i)
  379. CalculateTimelineWorldTransform(i);
  380. // Get mainline key
  381. const Vector<MainlineKey2D>& mainlineKeys = animation_->GetMainlineKeys();
  382. const MainlineKey2D* mainlineKey = 0;
  383. for (unsigned i = 1; i < mainlineKeys.Size(); ++i)
  384. {
  385. if (time < mainlineKeys[i].time_)
  386. {
  387. mainlineKey = &mainlineKeys[i - 1];
  388. break;
  389. }
  390. }
  391. if (!mainlineKey)
  392. mainlineKey = &mainlineKeys.Back();
  393. // Update node's transform and sprite's z order
  394. for (unsigned i = 0; i < timelineNodes_.Size(); ++i)
  395. {
  396. Node* timelineNode = timelineNodes_[i];
  397. if (!timelineNode)
  398. continue;
  399. const Reference2D* ref = mainlineKey->GetReference(i);
  400. if (!ref)
  401. {
  402. // Disable node
  403. if (timelineNode->IsEnabled())
  404. timelineNode->SetEnabled(false);
  405. }
  406. else
  407. {
  408. // Enable node
  409. if (!timelineNode->IsEnabled())
  410. timelineNode->SetEnabled(true);
  411. // Update node's transform
  412. const Transform2D& transform = timelineTransformInfos_[i].transform_;
  413. Vector2 position = transform.position_ * PIXEL_SIZE;
  414. if (flipX_)
  415. position.x_ = -position.x_;
  416. if (flipY_)
  417. position.y_ = -position.y_;
  418. timelineNode->SetPosition(position);
  419. float angle = transform.angle_;
  420. if (flipX_ != flipY_)
  421. angle = -angle;
  422. timelineNode->SetRotation(angle);
  423. timelineNode->SetScale(transform.scale_);
  424. // Update sprite's z order
  425. StaticSprite2D* staticSprite = timelineNode->GetComponent<StaticSprite2D>();
  426. if (staticSprite)
  427. staticSprite->SetOrderInLayer(orderInLayer_ + ref->zIndex_);
  428. }
  429. }
  430. MarkForUpdate();
  431. }
  432. void AnimatedSprite2D::CalculateTimelineWorldTransform(unsigned index)
  433. {
  434. TransformInfo& info = timelineTransformInfos_[index];
  435. if (info.worldSpace_)
  436. return;
  437. info.worldSpace_ = true;
  438. if (info.parent_ != -1)
  439. {
  440. CalculateTimelineWorldTransform(info.parent_);
  441. info.transform_ = timelineTransformInfos_[info.parent_].transform_ * info.transform_;
  442. }
  443. }
  444. void AnimatedSprite2D::HandleScenePostUpdate(StringHash eventType, VariantMap& eventData)
  445. {
  446. using namespace ScenePostUpdate;
  447. float timeStep = eventData[P_TIMESTEP].GetFloat();
  448. UpdateAnimation(timeStep);
  449. }
  450. }