Animation.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. /*
  2. * Animation.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. //code is copied from vcmiclient/CAnimation.cpp with minimal changes
  11. #include "StdInc.h"
  12. #include "Animation.h"
  13. #include "BitmapHandler.h"
  14. #include "graphics.h"
  15. #include "../lib/vcmi_endian.h"
  16. #include "../lib/filesystem/Filesystem.h"
  17. #include "../lib/filesystem/ISimpleResourceLoader.h"
  18. #include "../lib/json/JsonUtils.h"
  19. #include "../lib/CRandomGenerator.h"
  20. #include "../lib/VCMIDirs.h"
  21. typedef std::map<size_t, std::vector<JsonNode>> source_map;
  22. /// Class for def loading
  23. /// After loading will store general info (palette and frame offsets) and pointer to file itself
  24. class DefFile
  25. {
  26. private:
  27. struct SSpriteDef
  28. {
  29. ui32 size;
  30. ui32 format; /// format in which pixel data is stored
  31. ui32 fullWidth; /// full width and height of frame, including borders
  32. ui32 fullHeight;
  33. ui32 width; /// width and height of pixel data, borders excluded
  34. ui32 height;
  35. si32 leftMargin;
  36. si32 topMargin;
  37. };
  38. //offset[group][frame] - offset of frame data in file
  39. std::map<size_t, std::vector <size_t> > offset;
  40. std::unique_ptr<ui8[]> data;
  41. QVector<QRgb> palette;
  42. public:
  43. DefFile(std::string Name);
  44. ~DefFile();
  45. std::shared_ptr<QImage> loadFrame(size_t frame, size_t group) const;
  46. const std::map<size_t, size_t> getEntries() const;
  47. };
  48. class ImageLoader
  49. {
  50. QImage * image;
  51. ui8 * lineStart;
  52. ui8 * position;
  53. QPoint spriteSize;
  54. QPoint margins;
  55. QPoint fullSize;
  56. public:
  57. //load size raw pixels from data
  58. inline void Load(size_t size, const ui8 * data);
  59. //set size pixels to color
  60. inline void Load(size_t size, ui8 color=0);
  61. inline void EndLine();
  62. //init image with these sizes and palette
  63. inline void init(QPoint SpriteSize, QPoint Margins, QPoint FullSize);
  64. ImageLoader(QImage * Img);
  65. ~ImageLoader();
  66. };
  67. // Extremely simple file cache. TODO: smarter, more general solution
  68. class FileCache
  69. {
  70. static const int cacheSize = 50; //Max number of cached files
  71. struct FileData
  72. {
  73. ResourcePath name;
  74. size_t size;
  75. std::unique_ptr<ui8[]> data;
  76. std::unique_ptr<ui8[]> getCopy()
  77. {
  78. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  79. std::copy(data.get(), data.get() + size, ret.get());
  80. return ret;
  81. }
  82. FileData(ResourcePath name_, size_t size_, std::unique_ptr<ui8[]> data_):
  83. name{std::move(name_)},
  84. size{size_},
  85. data{std::move(data_)}
  86. {}
  87. };
  88. std::deque<FileData> cache;
  89. public:
  90. std::unique_ptr<ui8[]> getCachedFile(ResourcePath rid)
  91. {
  92. for(auto & file : cache)
  93. {
  94. if(file.name == rid)
  95. return file.getCopy();
  96. }
  97. // Still here? Cache miss
  98. if(cache.size() > cacheSize)
  99. cache.pop_front();
  100. auto data = CResourceHandler::get()->load(rid)->readAll();
  101. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  102. return cache.back().getCopy();
  103. }
  104. };
  105. enum class DefType : uint32_t
  106. {
  107. SPELL = 0x40,
  108. SPRITE = 0x41,
  109. CREATURE = 0x42,
  110. MAP = 0x43,
  111. MAP_HERO = 0x44,
  112. TERRAIN = 0x45,
  113. CURSOR = 0x46,
  114. INTERFACE = 0x47,
  115. SPRITE_FRAME = 0x48,
  116. BATTLE_HERO = 0x49
  117. };
  118. static FileCache animationCache;
  119. //First 8 colors in def palette used for transparency
  120. static constexpr std::array TARGET_PALETTE =
  121. {
  122. qRgba(0, 0, 0, 0 ), // transparency ( used in most images )
  123. qRgba(0, 0, 0, 64 ), // shadow border ( used in battle, adventure map def's )
  124. qRgba(0, 0, 0, 64 ), // shadow border ( used in fog-of-war def's )
  125. qRgba(0, 0, 0, 128), // shadow body ( used in fog-of-war def's )
  126. qRgba(0, 0, 0, 128), // shadow body ( used in battle, adventure map def's )
  127. qRgba(0, 0, 0, 0 ), // selection / owner flag ( used in battle, adventure map def's )
  128. qRgba(0, 0, 0, 128), // shadow body below selection ( used in battle def's )
  129. qRgba(0, 0, 0, 64 ) // shadow border below selection ( used in battle def's )
  130. };
  131. static constexpr std::array SOURCE_PALETTE =
  132. {
  133. qRgba(0, 255, 255, 255),
  134. qRgba(255, 150, 255, 255),
  135. qRgba(255, 100, 255, 255),
  136. qRgba(255, 50, 255, 255),
  137. qRgba(255, 0, 255, 255),
  138. qRgba(255, 255, 0, 255),
  139. qRgba(180, 0, 255, 255),
  140. qRgba(0, 255, 0, 255)
  141. };
  142. static bool colorsSimilar(const QRgb & lhs, const QRgb & rhs)
  143. {
  144. // it seems that H3 does not requires exact match to replace colors -> (255, 103, 255) gets interpreted as shadow
  145. // exact logic is not clear and requires extensive testing with image editing
  146. // potential reason is that H3 uses 16-bit color format (565 RGB bits), meaning that 3 least significant bits are lost in red and blue component
  147. static const int threshold = 8;
  148. int diffR = qRed(lhs) - qRed(rhs);
  149. int diffG = qGreen(lhs) - qGreen(rhs);
  150. int diffB = qBlue(lhs) - qBlue(rhs);
  151. int diffA = qAlpha(lhs) - qAlpha(rhs);
  152. return std::abs(diffR) < threshold && std::abs(diffG) < threshold && std::abs(diffB) < threshold && std::abs(diffA) < threshold;
  153. };
  154. /*************************************************************************
  155. * DefFile, class used for def loading *
  156. *************************************************************************/
  157. DefFile::DefFile(std::string Name):
  158. data(nullptr)
  159. {
  160. #if 0
  161. static QRgba H3_ORIG_PALETTE[8] =
  162. {
  163. { 0, 255, 255, SDL_ALPHA_OPAQUE},
  164. {255, 150, 255, SDL_ALPHA_OPAQUE},
  165. {255, 100, 255, SDL_ALPHA_OPAQUE},
  166. {255, 50, 255, SDL_ALPHA_OPAQUE},
  167. {255, 0, 255, SDL_ALPHA_OPAQUE},
  168. {255, 255, 0, SDL_ALPHA_OPAQUE},
  169. {180, 0, 255, SDL_ALPHA_OPAQUE},
  170. { 0, 255, 0, SDL_ALPHA_OPAQUE}
  171. };
  172. #endif // 0
  173. data = animationCache.getCachedFile(AnimationPath::builtin("SPRITES/" + Name));
  174. palette = QVector<QRgb>(256);
  175. int it = 0;
  176. //ui32 type = read_le_u32(data.get() + it);
  177. it += 4;
  178. //int width = read_le_u32(data + it); it+=4;//not used
  179. //int height = read_le_u32(data + it); it+=4;
  180. it += 8;
  181. ui32 totalBlocks = read_le_u32(data.get() + it);
  182. it += 4;
  183. for (ui32 i= 0; i<256; i++)
  184. {
  185. ui8 c[3];
  186. c[0] = data[it++];
  187. c[1] = data[it++];
  188. c[2] = data[it++];
  189. palette[i] = qRgba(c[0], c[1], c[2], 255);
  190. }
  191. // these colors seems to be used unconditionally
  192. palette[0] = TARGET_PALETTE[0];
  193. palette[1] = TARGET_PALETTE[1];
  194. palette[4] = TARGET_PALETTE[4];
  195. // rest of special colors are used only if their RGB values are close to H3
  196. for (uint32_t i = 0; i < 8; ++i)
  197. {
  198. if (colorsSimilar(SOURCE_PALETTE[i], palette[i]))
  199. palette[i] = TARGET_PALETTE[i];
  200. }
  201. for (ui32 i=0; i<totalBlocks; i++)
  202. {
  203. size_t blockID = read_le_u32(data.get() + it);
  204. it+=4;
  205. size_t totalEntries = read_le_u32(data.get() + it);
  206. it+=12;
  207. //8 unknown bytes - skipping
  208. //13 bytes for name of every frame in this block - not used, skipping
  209. it+= 13 * (int)totalEntries;
  210. for (ui32 j=0; j<totalEntries; j++)
  211. {
  212. size_t currOffset = read_le_u32(data.get() + it);
  213. offset[blockID].push_back(currOffset);
  214. it += 4;
  215. }
  216. }
  217. }
  218. std::shared_ptr<QImage> DefFile::loadFrame(size_t frame, size_t group) const
  219. {
  220. std::map<size_t, std::vector <size_t> >::const_iterator it;
  221. it = offset.find(group);
  222. assert (it != offset.end());
  223. const ui8 * FDef = data.get()+it->second[frame];
  224. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  225. SSpriteDef sprite;
  226. sprite.format = read_le_u32(&sd.format);
  227. sprite.fullWidth = read_le_u32(&sd.fullWidth);
  228. sprite.fullHeight = read_le_u32(&sd.fullHeight);
  229. sprite.width = read_le_u32(&sd.width);
  230. sprite.height = read_le_u32(&sd.height);
  231. sprite.leftMargin = read_le_u32(&sd.leftMargin);
  232. sprite.topMargin = read_le_u32(&sd.topMargin);
  233. ui32 currentOffset = sizeof(SSpriteDef);
  234. //special case for some "old" format defs (SGTWMTA.DEF and SGTWMTB.DEF)
  235. if(sprite.format == 1 && sprite.width > sprite.fullWidth && sprite.height > sprite.fullHeight)
  236. {
  237. sprite.leftMargin = 0;
  238. sprite.topMargin = 0;
  239. sprite.width = sprite.fullWidth;
  240. sprite.height = sprite.fullHeight;
  241. currentOffset -= 16;
  242. }
  243. const ui32 BaseOffset = currentOffset;
  244. auto img = std::make_shared<QImage>(sprite.fullWidth, sprite.fullHeight, QImage::Format_Indexed8);
  245. if(!img)
  246. throw std::runtime_error("Image memory cannot be allocated");
  247. ImageLoader loader(img.get());
  248. loader.init(QPoint(sprite.width, sprite.height),
  249. QPoint(sprite.leftMargin, sprite.topMargin),
  250. QPoint(sprite.fullWidth, sprite.fullHeight));
  251. switch(sprite.format)
  252. {
  253. case 0:
  254. {
  255. //pixel data is not compressed, copy data to surface
  256. for(ui32 i=0; i<sprite.height; i++)
  257. {
  258. loader.Load(sprite.width, FDef + currentOffset);
  259. currentOffset += sprite.width;
  260. loader.EndLine();
  261. }
  262. break;
  263. }
  264. case 1:
  265. {
  266. //for each line we have offset of pixel data
  267. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  268. currentOffset += sizeof(ui32) * sprite.height;
  269. for(ui32 i=0; i<sprite.height; i++)
  270. {
  271. //get position of the line
  272. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  273. ui32 TotalRowLength = 0;
  274. while(TotalRowLength<sprite.width)
  275. {
  276. ui8 segmentType = FDef[currentOffset++];
  277. ui32 length = FDef[currentOffset++] + 1;
  278. if(segmentType==0xFF)//Raw data
  279. {
  280. loader.Load(length, FDef + currentOffset);
  281. currentOffset+=length;
  282. }
  283. else// RLE
  284. {
  285. loader.Load(length, segmentType);
  286. }
  287. TotalRowLength += length;
  288. }
  289. loader.EndLine();
  290. }
  291. break;
  292. }
  293. case 2:
  294. {
  295. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  296. for(ui32 i=0; i<sprite.height; i++)
  297. {
  298. ui32 TotalRowLength=0;
  299. while(TotalRowLength<sprite.width)
  300. {
  301. ui8 segment=FDef[currentOffset++];
  302. ui8 code = segment / 32;
  303. ui8 length = (segment & 31) + 1;
  304. if(code==7)//Raw data
  305. {
  306. loader.Load(length, FDef + currentOffset);
  307. currentOffset += length;
  308. }
  309. else//RLE
  310. {
  311. loader.Load(length, code);
  312. }
  313. TotalRowLength+=length;
  314. }
  315. loader.EndLine();
  316. }
  317. break;
  318. }
  319. case 3:
  320. {
  321. for(ui32 i=0; i<sprite.height; i++)
  322. {
  323. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  324. ui32 TotalRowLength=0;
  325. while(TotalRowLength<sprite.width)
  326. {
  327. ui8 segment = FDef[currentOffset++];
  328. ui8 code = segment / 32;
  329. ui8 length = (segment & 31) + 1;
  330. if(code==7)//Raw data
  331. {
  332. loader.Load(length, FDef + currentOffset);
  333. currentOffset += length;
  334. }
  335. else//RLE
  336. {
  337. loader.Load(length, code);
  338. }
  339. TotalRowLength += length;
  340. }
  341. loader.EndLine();
  342. }
  343. break;
  344. }
  345. default:
  346. logGlobal->error("Error: unsupported format of def file: %d", sprite.format);
  347. break;
  348. }
  349. img->setColorTable(palette);
  350. return img;
  351. }
  352. DefFile::~DefFile() = default;
  353. const std::map<size_t, size_t > DefFile::getEntries() const
  354. {
  355. std::map<size_t, size_t > ret;
  356. for (auto & elem : offset)
  357. ret[elem.first] = elem.second.size();
  358. return ret;
  359. }
  360. /*************************************************************************
  361. * Classes for image loaders - helpers for loading from def files *
  362. *************************************************************************/
  363. ImageLoader::ImageLoader(QImage * Img):
  364. image(Img),
  365. lineStart(Img->bits()),
  366. position(Img->bits())
  367. {
  368. }
  369. void ImageLoader::init(QPoint SpriteSize, QPoint Margins, QPoint FullSize)
  370. {
  371. spriteSize = SpriteSize;
  372. margins = Margins;
  373. fullSize = FullSize;
  374. memset((void *)image->bits(), 0, fullSize.y() * image->bytesPerLine());
  375. lineStart = image->bits();
  376. lineStart += margins.y() * image->bytesPerLine() + margins.x();
  377. position = lineStart;
  378. }
  379. inline void ImageLoader::Load(size_t size, const ui8 * data)
  380. {
  381. if(size)
  382. {
  383. memcpy((void *)position, data, size);
  384. position += size;
  385. }
  386. }
  387. inline void ImageLoader::Load(size_t size, ui8 color)
  388. {
  389. if(size)
  390. {
  391. memset((void *)position, color, size);
  392. position += size;
  393. }
  394. }
  395. inline void ImageLoader::EndLine()
  396. {
  397. lineStart += image->bytesPerLine();
  398. position = lineStart;
  399. }
  400. ImageLoader::~ImageLoader()
  401. {
  402. }
  403. /*************************************************************************
  404. * Classes for images, support loading from file and drawing on surface *
  405. *************************************************************************/
  406. std::shared_ptr<QImage> Animation::getFromExtraDef(std::string filename)
  407. {
  408. size_t pos = filename.find(':');
  409. if(pos == -1)
  410. return nullptr;
  411. Animation anim(filename.substr(0, pos));
  412. pos++;
  413. size_t frame = atoi(filename.c_str()+pos);
  414. size_t group = 0;
  415. pos = filename.find(':', pos);
  416. if(pos != -1)
  417. {
  418. pos++;
  419. group = frame;
  420. frame = atoi(filename.c_str()+pos);
  421. }
  422. anim.load(frame ,group);
  423. auto ret = anim.images[group][frame];
  424. anim.images.clear();
  425. return ret;
  426. }
  427. bool Animation::loadFrame(size_t frame, size_t group)
  428. {
  429. if(size(group) <= frame)
  430. {
  431. printError(frame, group, "LoadFrame");
  432. return false;
  433. }
  434. auto image = getImage(frame, group, false);
  435. if(image)
  436. {
  437. return true;
  438. }
  439. //try to get image from def
  440. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  441. {
  442. if(defFile)
  443. {
  444. auto frameList = defFile->getEntries();
  445. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  446. {
  447. images[group][frame] = defFile->loadFrame(frame, group);
  448. return true;
  449. }
  450. }
  451. // still here? image is missing
  452. printError(frame, group, "LoadFrame");
  453. images[group][frame] = std::make_shared<QImage>("DEFAULT");
  454. }
  455. else //load from separate file
  456. {
  457. auto img = getFromExtraDef(source[group][frame]["file"].String());
  458. if(!img)
  459. {
  460. auto bitmap = BitmapHandler::loadBitmap(source[group][frame]["file"].String());
  461. img.reset(new QImage(bitmap));
  462. }
  463. images[group][frame] = img;
  464. return true;
  465. }
  466. return false;
  467. }
  468. bool Animation::unloadFrame(size_t frame, size_t group)
  469. {
  470. auto image = getImage(frame, group, false);
  471. if(image)
  472. {
  473. images[group].erase(frame);
  474. if(images[group].empty())
  475. images.erase(group);
  476. return true;
  477. }
  478. return false;
  479. }
  480. void Animation::init()
  481. {
  482. if(defFile)
  483. {
  484. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  485. for (auto & defEntry : defEntries)
  486. source[defEntry.first].resize(defEntry.second);
  487. }
  488. JsonPath resID = JsonPath::builtin("SPRITES/" + name);
  489. if(vstd::contains(graphics->imageLists, resID.getName()))
  490. initFromJson(graphics->imageLists[resID.getName()]);
  491. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  492. for(auto & loader : configList)
  493. {
  494. auto stream = loader->load(resID);
  495. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  496. stream->read(textData.get(), stream->getSize());
  497. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), resID.getName());
  498. initFromJson(config);
  499. }
  500. }
  501. void Animation::initFromJson(const JsonNode & config)
  502. {
  503. std::string basepath;
  504. basepath = config["basepath"].String();
  505. JsonNode base;
  506. base["margins"] = config["margins"];
  507. base["width"] = config["width"];
  508. base["height"] = config["height"];
  509. for(const JsonNode & group : config["sequences"].Vector())
  510. {
  511. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  512. source[groupID].clear();
  513. for(const JsonNode & frame : group["frames"].Vector())
  514. {
  515. JsonNode toAdd;
  516. JsonUtils::inherit(toAdd, base);
  517. toAdd["file"].String() = basepath + frame.String();
  518. source[groupID].push_back(toAdd);
  519. }
  520. }
  521. for(const JsonNode & node : config["images"].Vector())
  522. {
  523. size_t group = node["group"].Integer();
  524. size_t frame = node["frame"].Integer();
  525. if (source[group].size() <= frame)
  526. source[group].resize(frame+1);
  527. JsonNode toAdd;
  528. JsonUtils::inherit(toAdd, base);
  529. toAdd["file"].String() = basepath + node["file"].String();
  530. source[group][frame] = toAdd;
  531. }
  532. }
  533. void Animation::printError(size_t frame, size_t group, std::string type) const
  534. {
  535. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  536. }
  537. Animation::Animation(std::string Name):
  538. name(Name),
  539. preloaded(false),
  540. defFile()
  541. {
  542. size_t dotPos = name.find_last_of('.');
  543. if( dotPos!=-1 )
  544. name.erase(dotPos);
  545. std::transform(name.begin(), name.end(), name.begin(), toupper);
  546. auto resource = AnimationPath::builtin("SPRITES/" + name);
  547. if(CResourceHandler::get()->existsResource(resource))
  548. defFile = std::make_shared<DefFile>(name);
  549. init();
  550. if(source.empty())
  551. logAnim->error("Animation %s failed to load", Name);
  552. }
  553. Animation::Animation():
  554. name(""),
  555. preloaded(false),
  556. defFile()
  557. {
  558. init();
  559. }
  560. Animation::~Animation() = default;
  561. void Animation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  562. {
  563. if(!source.count(sourceGroup))
  564. {
  565. logAnim->error("Group %d missing in %s", sourceGroup, name);
  566. return;
  567. }
  568. if(source[sourceGroup].size() <= sourceFrame)
  569. {
  570. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name);
  571. return;
  572. }
  573. //todo: clone actual loaded Image object
  574. JsonNode clone(source[sourceGroup][sourceFrame]);
  575. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  576. {
  577. std::string temp = name+":"+std::to_string(sourceGroup)+":"+std::to_string(sourceFrame);
  578. clone["file"].String() = temp;
  579. }
  580. source[targetGroup].push_back(clone);
  581. size_t index = source[targetGroup].size() - 1;
  582. if(preloaded)
  583. load(index, targetGroup);
  584. }
  585. std::shared_ptr<QImage> Animation::getImage(size_t frame, size_t group, bool verbose) const
  586. {
  587. auto groupIter = images.find(group);
  588. if(groupIter != images.end())
  589. {
  590. auto imageIter = groupIter->second.find(frame);
  591. if(imageIter != groupIter->second.end())
  592. return imageIter->second;
  593. }
  594. if(verbose)
  595. printError(frame, group, "GetImage");
  596. return nullptr;
  597. }
  598. void Animation::exportBitmaps(const QDir & path) const
  599. {
  600. if(images.empty())
  601. {
  602. logGlobal->error("Nothing to export, animation is empty");
  603. return;
  604. }
  605. QString actualPath = path.absolutePath() + "/" + QString::fromStdString(name);
  606. QDir().mkdir(actualPath);
  607. size_t counter = 0;
  608. for(const auto& groupPair : images)
  609. {
  610. size_t group = groupPair.first;
  611. for(const auto& imagePair : groupPair.second)
  612. {
  613. size_t frame = imagePair.first;
  614. const auto img = imagePair.second;
  615. QString filename = QString("%1_%2_%3.png").arg(QString::fromStdString(name)).arg(group).arg(frame);
  616. QString filePath = actualPath + "/" + filename;
  617. img->save(filePath, "PNG");
  618. counter++;
  619. }
  620. }
  621. logGlobal->info("Exported %d frames to %s", counter, actualPath.toStdString());
  622. }
  623. void Animation::load()
  624. {
  625. for (auto & elem : source)
  626. for (size_t image=0; image < elem.second.size(); image++)
  627. loadFrame(image, elem.first);
  628. }
  629. void Animation::unload()
  630. {
  631. for (auto & elem : source)
  632. for (size_t image=0; image < elem.second.size(); image++)
  633. unloadFrame(image, elem.first);
  634. }
  635. void Animation::preload()
  636. {
  637. if(!preloaded)
  638. {
  639. preloaded = true;
  640. load();
  641. }
  642. }
  643. void Animation::loadGroup(size_t group)
  644. {
  645. if(vstd::contains(source, group))
  646. for (size_t image=0; image < source[group].size(); image++)
  647. loadFrame(image, group);
  648. }
  649. void Animation::unloadGroup(size_t group)
  650. {
  651. if(vstd::contains(source, group))
  652. for (size_t image=0; image < source[group].size(); image++)
  653. unloadFrame(image, group);
  654. }
  655. void Animation::load(size_t frame, size_t group)
  656. {
  657. loadFrame(frame, group);
  658. }
  659. void Animation::unload(size_t frame, size_t group)
  660. {
  661. unloadFrame(frame, group);
  662. }
  663. size_t Animation::size(size_t group) const
  664. {
  665. auto iter = source.find(group);
  666. if(iter != source.end())
  667. return iter->second.size();
  668. return 0;
  669. }
  670. void Animation::horizontalFlip()
  671. {
  672. for(auto & group : images)
  673. for(auto & image : group.second)
  674. *image.second = image.second->transformed(QTransform::fromScale(-1, 1));
  675. }
  676. void Animation::verticalFlip()
  677. {
  678. for(auto & group : images)
  679. for(auto & image : group.second)
  680. *image.second = image.second->transformed(QTransform::fromScale(1, -1));
  681. }
  682. void Animation::playerColored(PlayerColor player)
  683. {
  684. #if 0 //can be required in image preview?
  685. for(auto & group : images)
  686. for(auto & image : group.second)
  687. image.second->playerColored(player);
  688. #endif
  689. }
  690. void Animation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  691. {
  692. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  693. {
  694. duplicateImage(sourceGroup, frame, targetGroup);
  695. auto image = getImage(frame, targetGroup);
  696. *image = image->transformed(QTransform::fromScale(1, -1));
  697. }
  698. }