AnimationSet2D.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. //
  2. // Copyright (c) 2008-2017 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 "../Container/ArrayPtr.h"
  24. #include "../Core/Context.h"
  25. #include "../Graphics/Graphics.h"
  26. #include "../Graphics/Texture2D.h"
  27. #include "../IO/FileSystem.h"
  28. #include "../IO/Log.h"
  29. #include "../Math/AreaAllocator.h"
  30. #include "../Resource/Image.h"
  31. #include "../Resource/ResourceCache.h"
  32. #include "../Resource/XMLFile.h"
  33. #include "../Atomic2D/AnimationSet2D.h"
  34. #include "../Atomic2D/Sprite2D.h"
  35. #include "../Atomic2D/SpriterData2D.h"
  36. #include "../Atomic2D/SpriteSheet2D.h"
  37. #include "../DebugNew.h"
  38. #ifdef ATOMIC_SPINE
  39. #include <spine/spine.h>
  40. #include <spine/extension.h>
  41. #endif
  42. #ifdef ATOMIC_SPINE
  43. // Current animation set
  44. static Atomic::AnimationSet2D* currentAnimationSet = 0;
  45. void _spAtlasPage_createTexture(spAtlasPage* self, const char* path)
  46. {
  47. using namespace Atomic;
  48. if (!currentAnimationSet)
  49. return;
  50. ResourceCache* cache = currentAnimationSet->GetSubsystem<ResourceCache>();
  51. Sprite2D* sprite = cache->GetResource<Sprite2D>(path);
  52. // Add reference
  53. if (sprite)
  54. sprite->AddRef();
  55. self->width = sprite->GetTexture()->GetWidth();
  56. self->height = sprite->GetTexture()->GetHeight();
  57. self->rendererObject = sprite;
  58. }
  59. void _spAtlasPage_disposeTexture(spAtlasPage* self)
  60. {
  61. using namespace Atomic;
  62. Sprite2D* sprite = static_cast<Sprite2D*>(self->rendererObject);
  63. if (sprite)
  64. sprite->ReleaseRef();
  65. self->rendererObject = 0;
  66. }
  67. char* _spUtil_readFile(const char* path, int* length)
  68. {
  69. using namespace Atomic;
  70. if (!currentAnimationSet)
  71. return 0;
  72. ResourceCache* cache = currentAnimationSet->GetSubsystem<ResourceCache>();
  73. SharedPtr<File> file = cache->GetFile(path);
  74. if (!file)
  75. return 0;
  76. unsigned size = file->GetSize();
  77. char* data = MALLOC(char, size + 1);
  78. file->Read(data, size);
  79. data[size] = '\0';
  80. file.Reset();
  81. *length = size;
  82. return data;
  83. }
  84. #endif
  85. namespace Atomic
  86. {
  87. AnimationSet2D::AnimationSet2D(Context* context) :
  88. Resource(context),
  89. #ifdef ATOMIC_SPINE
  90. skeletonData_(0),
  91. atlas_(0),
  92. #endif
  93. hasSpriteSheet_(false)
  94. {
  95. }
  96. AnimationSet2D::~AnimationSet2D()
  97. {
  98. Dispose();
  99. }
  100. void AnimationSet2D::RegisterObject(Context* context)
  101. {
  102. context->RegisterFactory<AnimationSet2D>();
  103. }
  104. bool AnimationSet2D::BeginLoad(Deserializer& source)
  105. {
  106. Dispose();
  107. if (GetName().Empty())
  108. SetName(source.GetName());
  109. String extension = GetExtension(source.GetName());
  110. #ifdef ATOMIC_SPINE
  111. if (extension == ".json")
  112. return BeginLoadSpine(source);
  113. #endif
  114. if (extension == ".scml")
  115. return BeginLoadSpriter(source);
  116. ATOMIC_LOGERROR("Unsupport animation set file: " + source.GetName());
  117. return false;
  118. }
  119. bool AnimationSet2D::EndLoad()
  120. {
  121. #ifdef ATOMIC_SPINE
  122. if (jsonData_)
  123. return EndLoadSpine();
  124. #endif
  125. if (spriterData_)
  126. return EndLoadSpriter();
  127. return false;
  128. }
  129. unsigned AnimationSet2D::GetNumAnimations() const
  130. {
  131. #ifdef ATOMIC_SPINE
  132. if (skeletonData_)
  133. return (unsigned)skeletonData_->animationsCount;
  134. #endif
  135. if (spriterData_ && !spriterData_->entities_.Empty())
  136. return (unsigned)spriterData_->entities_[0]->animations_.Size();
  137. return 0;
  138. }
  139. String AnimationSet2D::GetAnimation(unsigned index) const
  140. {
  141. if (index >= GetNumAnimations())
  142. return String::EMPTY;
  143. #ifdef ATOMIC_SPINE
  144. if (skeletonData_)
  145. return skeletonData_->animations[index]->name;
  146. #endif
  147. if (spriterData_ && !spriterData_->entities_.Empty())
  148. return spriterData_->entities_[0]->animations_[index]->name_;
  149. return String::EMPTY;
  150. }
  151. bool AnimationSet2D::HasAnimation(const String& animationName) const
  152. {
  153. #ifdef ATOMIC_SPINE
  154. if (skeletonData_)
  155. {
  156. for (int i = 0; i < skeletonData_->animationsCount; ++i)
  157. {
  158. if (animationName == skeletonData_->animations[i]->name)
  159. return true;
  160. }
  161. }
  162. #endif
  163. if (spriterData_ && !spriterData_->entities_.Empty())
  164. {
  165. const PODVector<Spriter::Animation*>& animations = spriterData_->entities_[0]->animations_;
  166. for (unsigned i = 0; i < animations.Size(); ++i)
  167. {
  168. if (animationName == animations[i]->name_)
  169. return true;
  170. }
  171. }
  172. return false;
  173. }
  174. Sprite2D* AnimationSet2D::GetSprite() const
  175. {
  176. return sprite_;
  177. }
  178. Sprite2D* AnimationSet2D::GetSpriterFileSprite(int folderId, int fileId) const
  179. {
  180. int key = (folderId << 16) + fileId;
  181. HashMap<int, SharedPtr<Sprite2D> >::ConstIterator i = spriterFileSprites_.Find(key);
  182. if (i != spriterFileSprites_.End())
  183. return i->second_;
  184. return 0;
  185. }
  186. #ifdef ATOMIC_SPINE
  187. bool AnimationSet2D::BeginLoadSpine(Deserializer& source)
  188. {
  189. if (GetName().Empty())
  190. SetName(source.GetName());
  191. unsigned size = source.GetSize();
  192. jsonData_ = new char[size + 1];
  193. source.Read(jsonData_, size);
  194. jsonData_[size] = '\0';
  195. SetMemoryUse(size);
  196. return true;
  197. }
  198. bool AnimationSet2D::EndLoadSpine()
  199. {
  200. currentAnimationSet = this;
  201. String atlasFileName = ReplaceExtension(GetName(), ".atlas");
  202. atlas_ = spAtlas_createFromFile(atlasFileName.CString(), 0);
  203. if (!atlas_)
  204. {
  205. ATOMIC_LOGERROR("Create spine atlas failed");
  206. return false;
  207. }
  208. int numAtlasPages = 0;
  209. spAtlasPage* atlasPage = atlas_->pages;
  210. while (atlasPage)
  211. {
  212. ++numAtlasPages;
  213. atlasPage = atlasPage->next;
  214. }
  215. if (numAtlasPages > 1)
  216. {
  217. ATOMIC_LOGERROR("Only one page is supported in Atomic");
  218. return false;
  219. }
  220. sprite_ = static_cast<Sprite2D*>(atlas_->pages->rendererObject);
  221. spSkeletonJson* skeletonJson = spSkeletonJson_create(atlas_);
  222. if (!skeletonJson)
  223. {
  224. ATOMIC_LOGERROR("Create skeleton Json failed");
  225. return false;
  226. }
  227. skeletonJson->scale = 0.01f; // PIXEL_SIZE;
  228. skeletonData_ = spSkeletonJson_readSkeletonData(skeletonJson, &jsonData_[0]);
  229. spSkeletonJson_dispose(skeletonJson);
  230. jsonData_.Reset();
  231. currentAnimationSet = 0;
  232. return true;
  233. }
  234. #endif
  235. bool AnimationSet2D::BeginLoadSpriter(Deserializer& source)
  236. {
  237. unsigned dataSize = source.GetSize();
  238. if (!dataSize && !source.GetName().Empty())
  239. {
  240. ATOMIC_LOGERROR("Zero sized XML data in " + source.GetName());
  241. return false;
  242. }
  243. SharedArrayPtr<char> buffer(new char[dataSize]);
  244. if (source.Read(buffer.Get(), dataSize) != dataSize)
  245. return false;
  246. spriterData_ = new Spriter::SpriterData();
  247. if (!spriterData_->Load(buffer.Get(), dataSize))
  248. {
  249. ATOMIC_LOGERROR("Could not spriter data from " + source.GetName());
  250. return false;
  251. }
  252. // Check has sprite sheet
  253. String parentPath = GetParentPath(GetName());
  254. ResourceCache* cache = GetSubsystem<ResourceCache>();
  255. spriteSheetFilePath_ = parentPath + GetFileName(GetName()) + ".xml";
  256. hasSpriteSheet_ = cache->Exists(spriteSheetFilePath_);
  257. if (!hasSpriteSheet_)
  258. {
  259. spriteSheetFilePath_ = parentPath + GetFileName(GetName()) + ".plist";
  260. hasSpriteSheet_ = cache->Exists(spriteSheetFilePath_);
  261. }
  262. if (GetAsyncLoadState() == ASYNC_LOADING)
  263. {
  264. if (hasSpriteSheet_)
  265. cache->BackgroundLoadResource<SpriteSheet2D>(spriteSheetFilePath_, true, this);
  266. else
  267. {
  268. for (unsigned i = 0; i < spriterData_->folders_.Size(); ++i)
  269. {
  270. Spriter::Folder* folder = spriterData_->folders_[i];
  271. for (unsigned j = 0; j < folder->files_.Size(); ++j)
  272. {
  273. Spriter::File* file = folder->files_[j];
  274. String imagePath = parentPath + file->name_;
  275. cache->BackgroundLoadResource<Image>(imagePath, true, this);
  276. }
  277. }
  278. }
  279. }
  280. // Note: this probably does not reflect internal data structure size accurately
  281. SetMemoryUse(dataSize);
  282. return true;
  283. }
  284. struct SpriteInfo
  285. {
  286. int x;
  287. int y;
  288. Spriter::File* file_;
  289. SharedPtr<Image> image_;
  290. };
  291. bool AnimationSet2D::EndLoadSpriter()
  292. {
  293. if (!spriterData_)
  294. return false;
  295. ResourceCache* cache = GetSubsystem<ResourceCache>();
  296. if (hasSpriteSheet_)
  297. {
  298. spriteSheet_ = cache->GetResource<SpriteSheet2D>(spriteSheetFilePath_);
  299. if (!spriteSheet_)
  300. return false;
  301. for (unsigned i = 0; i < spriterData_->folders_.Size(); ++i)
  302. {
  303. Spriter::Folder* folder = spriterData_->folders_[i];
  304. for (unsigned j = 0; j < folder->files_.Size(); ++j)
  305. {
  306. Spriter::File* file = folder->files_[j];
  307. SharedPtr<Sprite2D> sprite(spriteSheet_->GetSprite(GetFileName(file->name_)));
  308. if (!sprite)
  309. {
  310. ATOMIC_LOGERROR("Could not load sprite " + file->name_);
  311. return false;
  312. }
  313. Vector2 hotSpot(file->pivotX_, file->pivotY_);
  314. // If sprite is trimmed, recalculate hot spot
  315. const IntVector2& offset = sprite->GetOffset();
  316. if (offset != IntVector2::ZERO)
  317. {
  318. float pivotX = file->width_ * hotSpot.x_;
  319. float pivotY = file->height_ * (1.0f - hotSpot.y_);
  320. const IntRect& rectangle = sprite->GetRectangle();
  321. hotSpot.x_ = (offset.x_ + pivotX) / rectangle.Width();
  322. hotSpot.y_ = 1.0f - (offset.y_ + pivotY) / rectangle.Height();
  323. }
  324. sprite->SetHotSpot(hotSpot);
  325. if (!sprite_)
  326. sprite_ = sprite;
  327. int key = (folder->id_ << 16) + file->id_;
  328. spriterFileSprites_[key] = sprite;
  329. }
  330. }
  331. }
  332. else
  333. {
  334. Vector<SpriteInfo> spriteInfos;
  335. String parentPath = GetParentPath(GetName());
  336. for (unsigned i = 0; i < spriterData_->folders_.Size(); ++i)
  337. {
  338. Spriter::Folder* folder = spriterData_->folders_[i];
  339. for (unsigned j = 0; j < folder->files_.Size(); ++j)
  340. {
  341. Spriter::File* file = folder->files_[j];
  342. String imagePath = parentPath + file->name_;
  343. SharedPtr<Image> image(cache->GetResource<Image>(imagePath));
  344. if (!image)
  345. {
  346. ATOMIC_LOGERROR("Could not load image");
  347. return false;
  348. }
  349. if (image->IsCompressed())
  350. {
  351. ATOMIC_LOGERROR("Compressed image is not support");
  352. return false;
  353. }
  354. if (image->GetComponents() != 4)
  355. {
  356. ATOMIC_LOGERROR("Only support image with 4 components");
  357. return false;
  358. }
  359. SpriteInfo def;
  360. def.x = 0;
  361. def.y = 0;
  362. def.file_ = file;
  363. def.image_ = image;
  364. spriteInfos.Push(def);
  365. }
  366. }
  367. if (spriteInfos.Empty())
  368. return false;
  369. if (spriteInfos.Size() > 1)
  370. {
  371. AreaAllocator allocator(128, 128, 2048, 2048);
  372. for (unsigned i = 0; i < spriteInfos.Size(); ++i)
  373. {
  374. SpriteInfo& info = spriteInfos[i];
  375. Image* image = info.image_;
  376. if (!allocator.Allocate(image->GetWidth() + 1, image->GetHeight() + 1, info.x, info.y))
  377. {
  378. ATOMIC_LOGERROR("Could not allocate area");
  379. return false;
  380. }
  381. }
  382. SharedPtr<Texture2D> texture(new Texture2D(context_));
  383. texture->SetMipsToSkip(QUALITY_LOW, 0);
  384. texture->SetNumLevels(1);
  385. texture->SetSize(allocator.GetWidth(), allocator.GetHeight(), Graphics::GetRGBAFormat());
  386. unsigned textureDataSize = allocator.GetWidth() * allocator.GetHeight() * 4;
  387. SharedArrayPtr<unsigned char> textureData(new unsigned char[textureDataSize]);
  388. memset(textureData.Get(), 0, textureDataSize);
  389. sprite_ = new Sprite2D(context_);
  390. sprite_->SetTexture(texture);
  391. for (unsigned i = 0; i < spriteInfos.Size(); ++i)
  392. {
  393. SpriteInfo& info = spriteInfos[i];
  394. Image* image = info.image_;
  395. for (int y = 0; y < image->GetHeight(); ++y)
  396. {
  397. memcpy(textureData.Get() + ((info.y + y) * allocator.GetWidth() + info.x) * 4,
  398. image->GetData() + y * image->GetWidth() * 4, image->GetWidth() * 4);
  399. }
  400. SharedPtr<Sprite2D> sprite(new Sprite2D(context_));
  401. sprite->SetTexture(texture);
  402. sprite->SetRectangle(IntRect(info.x, info.y, info.x + image->GetWidth(), info.y + image->GetHeight()));
  403. sprite->SetHotSpot(Vector2(info.file_->pivotX_, info.file_->pivotY_));
  404. int key = (info.file_->folder_->id_ << 16) + info.file_->id_;
  405. spriterFileSprites_[key] = sprite;
  406. }
  407. texture->SetData(0, 0, 0, allocator.GetWidth(), allocator.GetHeight(), textureData.Get());
  408. }
  409. else
  410. {
  411. SharedPtr<Texture2D> texture(new Texture2D(context_));
  412. texture->SetMipsToSkip(QUALITY_LOW, 0);
  413. texture->SetNumLevels(1);
  414. SpriteInfo& info = spriteInfos[0];
  415. texture->SetData(info.image_, true);
  416. sprite_ = new Sprite2D(context_);
  417. sprite_->SetTexture(texture);
  418. sprite_->SetRectangle(IntRect(info.x, info.y, info.x + info.image_->GetWidth(), info.y + info.image_->GetHeight()));
  419. sprite_->SetHotSpot(Vector2(info.file_->pivotX_, info.file_->pivotY_));
  420. int key = (info.file_->folder_->id_ << 16) + info.file_->id_;
  421. spriterFileSprites_[key] = sprite_;
  422. }
  423. }
  424. return true;
  425. }
  426. void AnimationSet2D::Dispose()
  427. {
  428. #ifdef ATOMIC_SPINE
  429. if (skeletonData_)
  430. {
  431. spSkeletonData_dispose(skeletonData_);
  432. skeletonData_ = 0;
  433. }
  434. if (atlas_)
  435. {
  436. spAtlas_dispose(atlas_);
  437. atlas_ = 0;
  438. }
  439. #endif
  440. spriterData_.Reset();
  441. sprite_.Reset();
  442. spriteSheet_.Reset();
  443. spriterFileSprites_.Clear();
  444. }
  445. }