AnimationSet2D.cpp 16 KB

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