CAnimation.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. /*
  2. * CAnimation.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. #include "StdInc.h"
  11. #include "CAnimation.h"
  12. #include "SDL_Extensions.h"
  13. #include "SDL_Pixels.h"
  14. #include "../CBitmapHandler.h"
  15. #include "../Graphics.h"
  16. #include "../lib/filesystem/Filesystem.h"
  17. #include "../lib/filesystem/ISimpleResourceLoader.h"
  18. #include "../lib/JsonNode.h"
  19. #include "../lib/CRandomGenerator.h"
  20. class SDLImageLoader;
  21. typedef std::map <size_t, std::vector <JsonNode> > source_map;
  22. typedef std::map<size_t, IImage* > image_map;
  23. typedef std::map<size_t, image_map > group_map;
  24. /// Class for def loading
  25. /// After loading will store general info (palette and frame offsets) and pointer to file itself
  26. class CDefFile
  27. {
  28. private:
  29. struct SSpriteDef
  30. {
  31. ui32 size;
  32. ui32 format; /// format in which pixel data is stored
  33. ui32 fullWidth; /// full width and height of frame, including borders
  34. ui32 fullHeight;
  35. ui32 width; /// width and height of pixel data, borders excluded
  36. ui32 height;
  37. si32 leftMargin;
  38. si32 topMargin;
  39. } PACKED_STRUCT;
  40. //offset[group][frame] - offset of frame data in file
  41. std::map<size_t, std::vector <size_t> > offset;
  42. std::unique_ptr<ui8[]> data;
  43. std::unique_ptr<SDL_Color[]> palette;
  44. public:
  45. CDefFile(std::string Name);
  46. ~CDefFile();
  47. //load frame as SDL_Surface
  48. template<class ImageLoader>
  49. void loadFrame(size_t frame, size_t group, ImageLoader &loader) const;
  50. const std::map<size_t, size_t> getEntries() const;
  51. };
  52. /*
  53. * Wrapper around SDL_Surface
  54. */
  55. class SDLImage : public IImage
  56. {
  57. public:
  58. const static int DEFAULT_PALETTE_COLORS = 256;
  59. //Surface without empty borders
  60. SDL_Surface * surf;
  61. //size of left and top borders
  62. Point margins;
  63. //total size including borders
  64. Point fullSize;
  65. public:
  66. //Load image from def file
  67. SDLImage(CDefFile *data, size_t frame, size_t group=0);
  68. //Load from bitmap file
  69. SDLImage(std::string filename);
  70. SDLImage(const JsonNode & conf);
  71. //Create using existing surface, extraRef will increase refcount on SDL_Surface
  72. SDLImage(SDL_Surface * from, bool extraRef);
  73. ~SDLImage();
  74. // Keep the original palette, in order to do color switching operation
  75. void savePalette();
  76. void draw(SDL_Surface * where, int posX=0, int posY=0, Rect *src=nullptr, ui8 alpha=255) const override;
  77. void draw(SDL_Surface * where, SDL_Rect * dest, SDL_Rect * src, ui8 alpha=255) const override;
  78. std::shared_ptr<IImage> scaleFast(float scale) const override;
  79. void exportBitmap(const boost::filesystem::path & path) const override;
  80. void playerColored(PlayerColor player) override;
  81. void setFlagColor(PlayerColor player) override;
  82. int width() const override;
  83. int height() const override;
  84. void horizontalFlip() override;
  85. void verticalFlip() override;
  86. void shiftPalette(int from, int howMany) override;
  87. void adjustPalette(const ColorShifter * shifter) override;
  88. void resetPalette() override;
  89. void setBorderPallete(const BorderPallete & borderPallete) override;
  90. friend class SDLImageLoader;
  91. private:
  92. SDL_Palette * originalPalette;
  93. };
  94. class SDLImageLoader
  95. {
  96. SDLImage * image;
  97. ui8 * lineStart;
  98. ui8 * position;
  99. public:
  100. //load size raw pixels from data
  101. inline void Load(size_t size, const ui8 * data);
  102. //set size pixels to color
  103. inline void Load(size_t size, ui8 color=0);
  104. inline void EndLine();
  105. //init image with these sizes and palette
  106. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  107. SDLImageLoader(SDLImage * Img);
  108. ~SDLImageLoader();
  109. };
  110. std::shared_ptr<IImage> IImage::createFromFile( const std::string & path )
  111. {
  112. return std::shared_ptr<IImage>(new SDLImage(path));
  113. }
  114. // Extremely simple file cache. TODO: smarter, more general solution
  115. class CFileCache
  116. {
  117. static const int cacheSize = 50; //Max number of cached files
  118. struct FileData
  119. {
  120. ResourceID name;
  121. size_t size;
  122. std::unique_ptr<ui8[]> data;
  123. std::unique_ptr<ui8[]> getCopy()
  124. {
  125. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  126. std::copy(data.get(), data.get() + size, ret.get());
  127. return ret;
  128. }
  129. FileData(ResourceID name_, size_t size_, std::unique_ptr<ui8[]> data_):
  130. name{std::move(name_)},
  131. size{size_},
  132. data{std::move(data_)}
  133. {}
  134. };
  135. std::deque<FileData> cache;
  136. public:
  137. std::unique_ptr<ui8[]> getCachedFile(ResourceID rid)
  138. {
  139. for(auto & file : cache)
  140. {
  141. if (file.name == rid)
  142. return file.getCopy();
  143. }
  144. // Still here? Cache miss
  145. if (cache.size() > cacheSize)
  146. cache.pop_front();
  147. auto data = CResourceHandler::get()->load(rid)->readAll();
  148. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  149. return cache.back().getCopy();
  150. }
  151. };
  152. enum class DefType : uint32_t
  153. {
  154. SPELL = 0x40,
  155. SPRITE = 0x41,
  156. CREATURE = 0x42,
  157. MAP = 0x43,
  158. MAP_HERO = 0x44,
  159. TERRAIN = 0x45,
  160. CURSOR = 0x46,
  161. INTERFACE = 0x47,
  162. SPRITE_FRAME = 0x48,
  163. BATTLE_HERO = 0x49
  164. };
  165. static CFileCache animationCache;
  166. /*************************************************************************
  167. * DefFile, class used for def loading *
  168. *************************************************************************/
  169. bool operator== (const SDL_Color & lhs, const SDL_Color & rhs)
  170. {
  171. return (lhs.a == rhs.a) && (lhs.b == rhs.b) &&(lhs.g == rhs.g) &&(lhs.r == rhs.r);
  172. }
  173. CDefFile::CDefFile(std::string Name):
  174. data(nullptr),
  175. palette(nullptr)
  176. {
  177. #if 0
  178. static SDL_Color H3_ORIG_PALETTE[8] =
  179. {
  180. { 0, 255, 255, SDL_ALPHA_OPAQUE},
  181. {255, 150, 255, SDL_ALPHA_OPAQUE},
  182. {255, 100, 255, SDL_ALPHA_OPAQUE},
  183. {255, 50, 255, SDL_ALPHA_OPAQUE},
  184. {255, 0, 255, SDL_ALPHA_OPAQUE},
  185. {255, 255, 0, SDL_ALPHA_OPAQUE},
  186. {180, 0, 255, SDL_ALPHA_OPAQUE},
  187. { 0, 255, 0, SDL_ALPHA_OPAQUE}
  188. };
  189. #endif // 0
  190. //First 8 colors in def palette used for transparency
  191. static SDL_Color H3Palette[8] =
  192. {
  193. { 0, 0, 0, 0},// 100% - transparency
  194. { 0, 0, 0, 32},// 75% - shadow border,
  195. { 0, 0, 0, 64},// TODO: find exact value
  196. { 0, 0, 0, 128},// TODO: for transparency
  197. { 0, 0, 0, 128},// 50% - shadow body
  198. { 0, 0, 0, 0},// 100% - selection highlight
  199. { 0, 0, 0, 128},// 50% - shadow body below selection
  200. { 0, 0, 0, 64} // 75% - shadow border below selection
  201. };
  202. data = animationCache.getCachedFile(ResourceID(std::string("SPRITES/") + Name, EResType::ANIMATION));
  203. palette = std::unique_ptr<SDL_Color[]>(new SDL_Color[256]);
  204. int it = 0;
  205. ui32 type = read_le_u32(data.get() + it);
  206. it+=4;
  207. //int width = read_le_u32(data + it); it+=4;//not used
  208. //int height = read_le_u32(data + it); it+=4;
  209. it+=8;
  210. ui32 totalBlocks = read_le_u32(data.get() + it);
  211. it+=4;
  212. for (ui32 i= 0; i<256; i++)
  213. {
  214. palette[i].r = data[it++];
  215. palette[i].g = data[it++];
  216. palette[i].b = data[it++];
  217. palette[i].a = SDL_ALPHA_OPAQUE;
  218. }
  219. switch(static_cast<DefType>(type))
  220. {
  221. case DefType::SPELL:
  222. palette[0] = H3Palette[0];
  223. break;
  224. case DefType::SPRITE:
  225. case DefType::SPRITE_FRAME:
  226. for(ui32 i= 0; i<8; i++)
  227. palette[i] = H3Palette[i];
  228. break;
  229. case DefType::CREATURE:
  230. palette[0] = H3Palette[0];
  231. palette[1] = H3Palette[1];
  232. palette[4] = H3Palette[4];
  233. palette[5] = H3Palette[5];
  234. palette[6] = H3Palette[6];
  235. palette[7] = H3Palette[7];
  236. break;
  237. case DefType::MAP:
  238. case DefType::MAP_HERO:
  239. palette[0] = H3Palette[0];
  240. palette[1] = H3Palette[1];
  241. palette[4] = H3Palette[4];
  242. //5 = owner flag, handled separately
  243. break;
  244. case DefType::TERRAIN:
  245. palette[0] = H3Palette[0];
  246. palette[1] = H3Palette[1];
  247. palette[2] = H3Palette[2];
  248. palette[3] = H3Palette[3];
  249. palette[4] = H3Palette[4];
  250. break;
  251. case DefType::CURSOR:
  252. palette[0] = H3Palette[0];
  253. break;
  254. case DefType::INTERFACE:
  255. palette[0] = H3Palette[0];
  256. palette[1] = H3Palette[1];
  257. palette[4] = H3Palette[4];
  258. //player colors handled separately
  259. //TODO: disallow colorizing other def types
  260. break;
  261. case DefType::BATTLE_HERO:
  262. palette[0] = H3Palette[0];
  263. palette[1] = H3Palette[1];
  264. palette[4] = H3Palette[4];
  265. break;
  266. default:
  267. logAnim->error("Unknown def type %d in %s", type, Name);
  268. break;
  269. }
  270. for (ui32 i=0; i<totalBlocks; i++)
  271. {
  272. size_t blockID = read_le_u32(data.get() + it);
  273. it+=4;
  274. size_t totalEntries = read_le_u32(data.get() + it);
  275. it+=12;
  276. //8 unknown bytes - skipping
  277. //13 bytes for name of every frame in this block - not used, skipping
  278. it+= 13 * (int)totalEntries;
  279. for (ui32 j=0; j<totalEntries; j++)
  280. {
  281. size_t currOffset = read_le_u32(data.get() + it);
  282. offset[blockID].push_back(currOffset);
  283. it += 4;
  284. }
  285. }
  286. }
  287. template<class ImageLoader>
  288. void CDefFile::loadFrame(size_t frame, size_t group, ImageLoader &loader) const
  289. {
  290. std::map<size_t, std::vector <size_t> >::const_iterator it;
  291. it = offset.find(group);
  292. assert (it != offset.end());
  293. const ui8 * FDef = data.get()+it->second[frame];
  294. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  295. SSpriteDef sprite;
  296. sprite.format = read_le_u32(&sd.format);
  297. sprite.fullWidth = read_le_u32(&sd.fullWidth);
  298. sprite.fullHeight = read_le_u32(&sd.fullHeight);
  299. sprite.width = read_le_u32(&sd.width);
  300. sprite.height = read_le_u32(&sd.height);
  301. sprite.leftMargin = read_le_u32(&sd.leftMargin);
  302. sprite.topMargin = read_le_u32(&sd.topMargin);
  303. ui32 currentOffset = sizeof(SSpriteDef);
  304. //special case for some "old" format defs (SGTWMTA.DEF and SGTWMTB.DEF)
  305. if(sprite.format == 1 && sprite.width > sprite.fullWidth && sprite.height > sprite.fullHeight)
  306. {
  307. sprite.leftMargin = 0;
  308. sprite.topMargin = 0;
  309. sprite.width = sprite.fullWidth;
  310. sprite.height = sprite.fullHeight;
  311. currentOffset -= 16;
  312. }
  313. const ui32 BaseOffset = currentOffset;
  314. loader.init(Point(sprite.width, sprite.height),
  315. Point(sprite.leftMargin, sprite.topMargin),
  316. Point(sprite.fullWidth, sprite.fullHeight), palette.get());
  317. switch(sprite.format)
  318. {
  319. case 0:
  320. {
  321. //pixel data is not compressed, copy data to surface
  322. for(ui32 i=0; i<sprite.height; i++)
  323. {
  324. loader.Load(sprite.width, FDef + currentOffset);
  325. currentOffset += sprite.width;
  326. loader.EndLine();
  327. }
  328. break;
  329. }
  330. case 1:
  331. {
  332. //for each line we have offset of pixel data
  333. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  334. currentOffset += sizeof(ui32) * sprite.height;
  335. for(ui32 i=0; i<sprite.height; i++)
  336. {
  337. //get position of the line
  338. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  339. ui32 TotalRowLength = 0;
  340. while(TotalRowLength<sprite.width)
  341. {
  342. ui8 segmentType = FDef[currentOffset++];
  343. ui32 length = FDef[currentOffset++] + 1;
  344. if(segmentType==0xFF)//Raw data
  345. {
  346. loader.Load(length, FDef + currentOffset);
  347. currentOffset+=length;
  348. }
  349. else// RLE
  350. {
  351. loader.Load(length, segmentType);
  352. }
  353. TotalRowLength += length;
  354. }
  355. loader.EndLine();
  356. }
  357. break;
  358. }
  359. case 2:
  360. {
  361. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  362. for(ui32 i=0; i<sprite.height; i++)
  363. {
  364. ui32 TotalRowLength=0;
  365. while(TotalRowLength<sprite.width)
  366. {
  367. ui8 segment=FDef[currentOffset++];
  368. ui8 code = segment / 32;
  369. ui8 length = (segment & 31) + 1;
  370. if(code==7)//Raw data
  371. {
  372. loader.Load(length, FDef + currentOffset);
  373. currentOffset += length;
  374. }
  375. else//RLE
  376. {
  377. loader.Load(length, code);
  378. }
  379. TotalRowLength+=length;
  380. }
  381. loader.EndLine();
  382. }
  383. break;
  384. }
  385. case 3:
  386. {
  387. for(ui32 i=0; i<sprite.height; i++)
  388. {
  389. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  390. ui32 TotalRowLength=0;
  391. while(TotalRowLength<sprite.width)
  392. {
  393. ui8 segment = FDef[currentOffset++];
  394. ui8 code = segment / 32;
  395. ui8 length = (segment & 31) + 1;
  396. if(code==7)//Raw data
  397. {
  398. loader.Load(length, FDef + currentOffset);
  399. currentOffset += length;
  400. }
  401. else//RLE
  402. {
  403. loader.Load(length, code);
  404. }
  405. TotalRowLength += length;
  406. }
  407. loader.EndLine();
  408. }
  409. break;
  410. }
  411. default:
  412. logGlobal->error("Error: unsupported format of def file: %d", sprite.format);
  413. break;
  414. }
  415. }
  416. CDefFile::~CDefFile() = default;
  417. const std::map<size_t, size_t > CDefFile::getEntries() const
  418. {
  419. std::map<size_t, size_t > ret;
  420. for (auto & elem : offset)
  421. ret[elem.first] = elem.second.size();
  422. return ret;
  423. }
  424. /*************************************************************************
  425. * Classes for image loaders - helpers for loading from def files *
  426. *************************************************************************/
  427. SDLImageLoader::SDLImageLoader(SDLImage * Img):
  428. image(Img),
  429. lineStart(nullptr),
  430. position(nullptr)
  431. {
  432. }
  433. void SDLImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  434. {
  435. //Init image
  436. image->surf = SDL_CreateRGBSurface(0, SpriteSize.x, SpriteSize.y, 8, 0, 0, 0, 0);
  437. image->margins = Margins;
  438. image->fullSize = FullSize;
  439. //Prepare surface
  440. SDL_Palette * p = SDL_AllocPalette(SDLImage::DEFAULT_PALETTE_COLORS);
  441. SDL_SetPaletteColors(p, pal, 0, SDLImage::DEFAULT_PALETTE_COLORS);
  442. SDL_SetSurfacePalette(image->surf, p);
  443. SDL_FreePalette(p);
  444. SDL_LockSurface(image->surf);
  445. lineStart = position = (ui8*)image->surf->pixels;
  446. }
  447. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  448. {
  449. if (size)
  450. {
  451. memcpy((void *)position, data, size);
  452. position += size;
  453. }
  454. }
  455. inline void SDLImageLoader::Load(size_t size, ui8 color)
  456. {
  457. if (size)
  458. {
  459. memset((void *)position, color, size);
  460. position += size;
  461. }
  462. }
  463. inline void SDLImageLoader::EndLine()
  464. {
  465. lineStart += image->surf->pitch;
  466. position = lineStart;
  467. }
  468. SDLImageLoader::~SDLImageLoader()
  469. {
  470. SDL_UnlockSurface(image->surf);
  471. SDL_SetColorKey(image->surf, SDL_TRUE, 0);
  472. //TODO: RLE if compressed and bpp>1
  473. }
  474. /*************************************************************************
  475. * Classes for images, support loading from file and drawing on surface *
  476. *************************************************************************/
  477. IImage::IImage() = default;
  478. IImage::~IImage() = default;
  479. SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group)
  480. : surf(nullptr),
  481. margins(0, 0),
  482. fullSize(0, 0),
  483. originalPalette(nullptr)
  484. {
  485. SDLImageLoader loader(this);
  486. data->loadFrame(frame, group, loader);
  487. savePalette();
  488. }
  489. SDLImage::SDLImage(SDL_Surface * from, bool extraRef)
  490. : surf(nullptr),
  491. margins(0, 0),
  492. fullSize(0, 0),
  493. originalPalette(nullptr)
  494. {
  495. surf = from;
  496. if (surf == nullptr)
  497. return;
  498. savePalette();
  499. if (extraRef)
  500. surf->refcount++;
  501. fullSize.x = surf->w;
  502. fullSize.y = surf->h;
  503. }
  504. SDLImage::SDLImage(const JsonNode & conf)
  505. : surf(nullptr),
  506. margins(0, 0),
  507. fullSize(0, 0),
  508. originalPalette(nullptr)
  509. {
  510. std::string filename = conf["file"].String();
  511. surf = BitmapHandler::loadBitmap(filename);
  512. if(surf == nullptr)
  513. return;
  514. savePalette();
  515. const JsonNode & jsonMargins = conf["margins"];
  516. margins.x = static_cast<int>(jsonMargins["left"].Integer());
  517. margins.y = static_cast<int>(jsonMargins["top"].Integer());
  518. fullSize.x = static_cast<int>(conf["width"].Integer());
  519. fullSize.y = static_cast<int>(conf["height"].Integer());
  520. if(fullSize.x == 0)
  521. {
  522. fullSize.x = margins.x + surf->w + (int)jsonMargins["right"].Integer();
  523. }
  524. if(fullSize.y == 0)
  525. {
  526. fullSize.y = margins.y + surf->h + (int)jsonMargins["bottom"].Integer();
  527. }
  528. }
  529. SDLImage::SDLImage(std::string filename)
  530. : surf(nullptr),
  531. margins(0, 0),
  532. fullSize(0, 0),
  533. originalPalette(nullptr)
  534. {
  535. surf = BitmapHandler::loadBitmap(filename);
  536. if(surf == nullptr)
  537. {
  538. logGlobal->error("Error: failed to load image %s", filename);
  539. return;
  540. }
  541. else
  542. {
  543. savePalette();
  544. fullSize.x = surf->w;
  545. fullSize.y = surf->h;
  546. }
  547. }
  548. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  549. {
  550. if(!surf)
  551. return;
  552. Rect destRect(posX, posY, surf->w, surf->h);
  553. draw(where, &destRect, src);
  554. }
  555. void SDLImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  556. {
  557. if (!surf)
  558. return;
  559. Rect sourceRect(0, 0, surf->w, surf->h);
  560. Point destShift(0, 0);
  561. if(src)
  562. {
  563. if(src->x < margins.x)
  564. destShift.x += margins.x - src->x;
  565. if(src->y < margins.y)
  566. destShift.y += margins.y - src->y;
  567. sourceRect = Rect(*src) & Rect(margins.x, margins.y, surf->w, surf->h);
  568. sourceRect -= margins;
  569. }
  570. else
  571. destShift = margins;
  572. Rect destRect(destShift.x, destShift.y, surf->w, surf->h);
  573. if(dest)
  574. {
  575. destRect.x += dest->x;
  576. destRect.y += dest->y;
  577. }
  578. if(surf->format->BitsPerPixel == 8)
  579. {
  580. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  581. }
  582. else
  583. {
  584. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  585. }
  586. }
  587. std::shared_ptr<IImage> SDLImage::scaleFast(float scale) const
  588. {
  589. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, (int)(surf->w * scale), (int)(surf->h * scale));
  590. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  591. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  592. else if(scaled->format && scaled->format->Amask)
  593. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  594. else
  595. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  596. SDLImage * ret = new SDLImage(scaled, false);
  597. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  598. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  599. ret->margins.x = (int) round((float)margins.x * scale);
  600. ret->margins.y = (int) round((float)margins.y * scale);
  601. return std::shared_ptr<IImage>(ret);
  602. }
  603. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  604. {
  605. SDL_SaveBMP(surf, path.string().c_str());
  606. }
  607. void SDLImage::playerColored(PlayerColor player)
  608. {
  609. graphics->blueToPlayersAdv(surf, player);
  610. }
  611. void SDLImage::setFlagColor(PlayerColor player)
  612. {
  613. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  614. CSDL_Ext::setPlayerColor(surf, player);
  615. }
  616. int SDLImage::width() const
  617. {
  618. return fullSize.x;
  619. }
  620. int SDLImage::height() const
  621. {
  622. return fullSize.y;
  623. }
  624. void SDLImage::horizontalFlip()
  625. {
  626. margins.y = fullSize.y - surf->h - margins.y;
  627. //todo: modify in-place
  628. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  629. SDL_FreeSurface(surf);
  630. surf = flipped;
  631. }
  632. void SDLImage::verticalFlip()
  633. {
  634. margins.x = fullSize.x - surf->w - margins.x;
  635. //todo: modify in-place
  636. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  637. SDL_FreeSurface(surf);
  638. surf = flipped;
  639. }
  640. // Keep the original palette, in order to do color switching operation
  641. void SDLImage::savePalette()
  642. {
  643. // For some images that don't have palette, skip this
  644. if(surf->format->palette == nullptr)
  645. return;
  646. if(originalPalette == nullptr)
  647. originalPalette = SDL_AllocPalette(DEFAULT_PALETTE_COLORS);
  648. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, DEFAULT_PALETTE_COLORS);
  649. }
  650. void SDLImage::shiftPalette(int from, int howMany)
  651. {
  652. //works with at most 16 colors, if needed more -> increase values
  653. assert(howMany < 16);
  654. if(surf->format->palette)
  655. {
  656. SDL_Color palette[16];
  657. for(int i=0; i<howMany; ++i)
  658. {
  659. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  660. }
  661. SDL_SetColors(surf, palette, from, howMany);
  662. }
  663. }
  664. void SDLImage::adjustPalette(const ColorShifter * shifter)
  665. {
  666. if(originalPalette == nullptr)
  667. return;
  668. SDL_Palette* palette = surf->format->palette;
  669. // Note: here we skip the first 8 colors in the palette that predefined in H3Palette
  670. for(int i = 8; i < palette->ncolors; i++)
  671. {
  672. palette->colors[i] = shifter->shiftColor(originalPalette->colors[i]);
  673. }
  674. }
  675. void SDLImage::resetPalette()
  676. {
  677. if(originalPalette == nullptr)
  678. return;
  679. // Always keept the original palette not changed, copy a new palette to assign to surface
  680. SDL_SetPaletteColors(surf->format->palette, originalPalette->colors, 0, originalPalette->ncolors);
  681. }
  682. void SDLImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  683. {
  684. if(surf->format->palette)
  685. {
  686. SDL_SetColors(surf, const_cast<SDL_Color *>(borderPallete.data()), 5, 3);
  687. }
  688. }
  689. SDLImage::~SDLImage()
  690. {
  691. SDL_FreeSurface(surf);
  692. if(originalPalette != nullptr)
  693. {
  694. SDL_FreePalette(originalPalette);
  695. originalPalette = nullptr;
  696. }
  697. }
  698. std::shared_ptr<IImage> CAnimation::getFromExtraDef(std::string filename)
  699. {
  700. size_t pos = filename.find(':');
  701. if (pos == -1)
  702. return nullptr;
  703. CAnimation anim(filename.substr(0, pos));
  704. pos++;
  705. size_t frame = atoi(filename.c_str()+pos);
  706. size_t group = 0;
  707. pos = filename.find(':', pos);
  708. if (pos != -1)
  709. {
  710. pos++;
  711. group = frame;
  712. frame = atoi(filename.c_str()+pos);
  713. }
  714. anim.load(frame ,group);
  715. auto ret = anim.images[group][frame];
  716. anim.images.clear();
  717. return ret;
  718. }
  719. bool CAnimation::loadFrame(size_t frame, size_t group)
  720. {
  721. if(size(group) <= frame)
  722. {
  723. printError(frame, group, "LoadFrame");
  724. return false;
  725. }
  726. auto image = getImage(frame, group, false);
  727. if(image)
  728. {
  729. return true;
  730. }
  731. //try to get image from def
  732. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  733. {
  734. if(defFile)
  735. {
  736. auto frameList = defFile->getEntries();
  737. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  738. {
  739. images[group][frame] = std::make_shared<SDLImage>(defFile.get(), frame, group);
  740. return true;
  741. }
  742. }
  743. // still here? image is missing
  744. printError(frame, group, "LoadFrame");
  745. images[group][frame] = std::make_shared<SDLImage>("DEFAULT");
  746. }
  747. else //load from separate file
  748. {
  749. auto img = getFromExtraDef(source[group][frame]["file"].String());
  750. if(!img)
  751. img = std::make_shared<SDLImage>(source[group][frame]);
  752. images[group][frame] = img;
  753. return true;
  754. }
  755. return false;
  756. }
  757. bool CAnimation::unloadFrame(size_t frame, size_t group)
  758. {
  759. auto image = getImage(frame, group, false);
  760. if(image)
  761. {
  762. images[group].erase(frame);
  763. if(images[group].empty())
  764. images.erase(group);
  765. return true;
  766. }
  767. return false;
  768. }
  769. void CAnimation::initFromJson(const JsonNode & config)
  770. {
  771. std::string basepath;
  772. basepath = config["basepath"].String();
  773. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  774. base["margins"] = config["margins"];
  775. base["width"] = config["width"];
  776. base["height"] = config["height"];
  777. for(const JsonNode & group : config["sequences"].Vector())
  778. {
  779. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  780. source[groupID].clear();
  781. for(const JsonNode & frame : group["frames"].Vector())
  782. {
  783. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  784. JsonUtils::inherit(toAdd, base);
  785. toAdd["file"].String() = basepath + frame.String();
  786. source[groupID].push_back(toAdd);
  787. }
  788. }
  789. for(const JsonNode & node : config["images"].Vector())
  790. {
  791. size_t group = node["group"].Integer();
  792. size_t frame = node["frame"].Integer();
  793. if (source[group].size() <= frame)
  794. source[group].resize(frame+1);
  795. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  796. JsonUtils::inherit(toAdd, base);
  797. toAdd["file"].String() = basepath + node["file"].String();
  798. source[group][frame] = toAdd;
  799. }
  800. }
  801. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  802. {
  803. if(images.empty())
  804. {
  805. logGlobal->error("Nothing to export, animation is empty");
  806. return;
  807. }
  808. boost::filesystem::path actualPath = path / "SPRITES" / name;
  809. boost::filesystem::create_directories(actualPath);
  810. size_t counter = 0;
  811. for(const auto & groupPair : images)
  812. {
  813. size_t group = groupPair.first;
  814. for(const auto & imagePair : groupPair.second)
  815. {
  816. size_t frame = imagePair.first;
  817. const auto img = imagePair.second;
  818. boost::format fmt("%d_%d.bmp");
  819. fmt % group % frame;
  820. img->exportBitmap(actualPath / fmt.str());
  821. counter++;
  822. }
  823. }
  824. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  825. }
  826. void CAnimation::init()
  827. {
  828. if(defFile)
  829. {
  830. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  831. for (auto & defEntry : defEntries)
  832. source[defEntry.first].resize(defEntry.second);
  833. }
  834. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  835. if (vstd::contains(graphics->imageLists, resID.getName()))
  836. initFromJson(graphics->imageLists[resID.getName()]);
  837. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  838. for(auto & loader : configList)
  839. {
  840. auto stream = loader->load(resID);
  841. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  842. stream->read(textData.get(), stream->getSize());
  843. const JsonNode config((char*)textData.get(), stream->getSize());
  844. initFromJson(config);
  845. }
  846. }
  847. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  848. {
  849. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  850. }
  851. CAnimation::CAnimation(std::string Name):
  852. name(Name),
  853. preloaded(false),
  854. defFile()
  855. {
  856. size_t dotPos = name.find_last_of('.');
  857. if ( dotPos!=-1 )
  858. name.erase(dotPos);
  859. std::transform(name.begin(), name.end(), name.begin(), toupper);
  860. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  861. if(CResourceHandler::get()->existsResource(resource))
  862. defFile = std::make_shared<CDefFile>(name);
  863. init();
  864. if(source.empty())
  865. logAnim->error("Animation %s failed to load", Name);
  866. }
  867. CAnimation::CAnimation():
  868. name(""),
  869. preloaded(false),
  870. defFile()
  871. {
  872. init();
  873. }
  874. CAnimation::~CAnimation() = default;
  875. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  876. {
  877. if(!source.count(sourceGroup))
  878. {
  879. logAnim->error("Group %d missing in %s", sourceGroup, name);
  880. return;
  881. }
  882. if(source[sourceGroup].size() <= sourceFrame)
  883. {
  884. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name);
  885. return;
  886. }
  887. //todo: clone actual loaded Image object
  888. JsonNode clone(source[sourceGroup][sourceFrame]);
  889. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  890. {
  891. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  892. clone["file"].String() = temp;
  893. }
  894. source[targetGroup].push_back(clone);
  895. size_t index = source[targetGroup].size() - 1;
  896. if(preloaded)
  897. load(index, targetGroup);
  898. }
  899. void CAnimation::shiftColor(const ColorShifter * shifter)
  900. {
  901. for(auto groupIter = images.begin(); groupIter != images.end(); groupIter++)
  902. {
  903. for(auto frameIter = groupIter->second.begin(); frameIter != groupIter->second.end(); frameIter++)
  904. {
  905. std::shared_ptr<IImage> image = frameIter->second;
  906. image->adjustPalette(shifter);
  907. }
  908. }
  909. }
  910. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  911. {
  912. if (source[group].size() <= frame)
  913. source[group].resize(frame+1);
  914. source[group][frame]["file"].String() = filename;
  915. //FIXME: update image if already loaded
  916. }
  917. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  918. {
  919. auto groupIter = images.find(group);
  920. if (groupIter != images.end())
  921. {
  922. auto imageIter = groupIter->second.find(frame);
  923. if (imageIter != groupIter->second.end())
  924. return imageIter->second;
  925. }
  926. if (verbose)
  927. printError(frame, group, "GetImage");
  928. return nullptr;
  929. }
  930. void CAnimation::load()
  931. {
  932. for (auto & elem : source)
  933. for (size_t image=0; image < elem.second.size(); image++)
  934. loadFrame(image, elem.first);
  935. }
  936. void CAnimation::unload()
  937. {
  938. for (auto & elem : source)
  939. for (size_t image=0; image < elem.second.size(); image++)
  940. unloadFrame(image, elem.first);
  941. }
  942. void CAnimation::preload()
  943. {
  944. if(!preloaded)
  945. {
  946. preloaded = true;
  947. load();
  948. }
  949. }
  950. void CAnimation::loadGroup(size_t group)
  951. {
  952. if (vstd::contains(source, group))
  953. for (size_t image=0; image < source[group].size(); image++)
  954. loadFrame(image, group);
  955. }
  956. void CAnimation::unloadGroup(size_t group)
  957. {
  958. if (vstd::contains(source, group))
  959. for (size_t image=0; image < source[group].size(); image++)
  960. unloadFrame(image, group);
  961. }
  962. void CAnimation::load(size_t frame, size_t group)
  963. {
  964. loadFrame(frame, group);
  965. }
  966. void CAnimation::unload(size_t frame, size_t group)
  967. {
  968. unloadFrame(frame, group);
  969. }
  970. size_t CAnimation::size(size_t group) const
  971. {
  972. auto iter = source.find(group);
  973. if (iter != source.end())
  974. return iter->second.size();
  975. return 0;
  976. }
  977. void CAnimation::horizontalFlip()
  978. {
  979. for(auto & group : images)
  980. for(auto & image : group.second)
  981. image.second->horizontalFlip();
  982. }
  983. void CAnimation::verticalFlip()
  984. {
  985. for(auto & group : images)
  986. for(auto & image : group.second)
  987. image.second->verticalFlip();
  988. }
  989. void CAnimation::playerColored(PlayerColor player)
  990. {
  991. for(auto & group : images)
  992. for(auto & image : group.second)
  993. image.second->playerColored(player);
  994. }
  995. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  996. {
  997. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  998. {
  999. duplicateImage(sourceGroup, frame, targetGroup);
  1000. auto image = getImage(frame, targetGroup);
  1001. image->verticalFlip();
  1002. }
  1003. }
  1004. float CFadeAnimation::initialCounter() const
  1005. {
  1006. if (fadingMode == EMode::OUT)
  1007. return 1.0f;
  1008. return 0.0f;
  1009. }
  1010. void CFadeAnimation::update()
  1011. {
  1012. if (!fading)
  1013. return;
  1014. if (fadingMode == EMode::OUT)
  1015. fadingCounter -= delta;
  1016. else
  1017. fadingCounter += delta;
  1018. if (isFinished())
  1019. {
  1020. fading = false;
  1021. if (shouldFreeSurface)
  1022. {
  1023. SDL_FreeSurface(fadingSurface);
  1024. fadingSurface = nullptr;
  1025. }
  1026. }
  1027. }
  1028. bool CFadeAnimation::isFinished() const
  1029. {
  1030. if (fadingMode == EMode::OUT)
  1031. return fadingCounter <= 0.0f;
  1032. return fadingCounter >= 1.0f;
  1033. }
  1034. CFadeAnimation::CFadeAnimation()
  1035. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  1036. fadingMode(EMode::NONE)
  1037. {
  1038. }
  1039. CFadeAnimation::~CFadeAnimation()
  1040. {
  1041. if (fadingSurface && shouldFreeSurface)
  1042. SDL_FreeSurface(fadingSurface);
  1043. }
  1044. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  1045. {
  1046. if (fading)
  1047. {
  1048. // in that case, immediately finish the previous fade
  1049. // (alternatively, we could just return here to ignore the new fade request until this one finished (but we'd need to free the passed bitmap to avoid leaks))
  1050. logGlobal->warn("Tried to init fading animation that is already running.");
  1051. if (fadingSurface && shouldFreeSurface)
  1052. SDL_FreeSurface(fadingSurface);
  1053. }
  1054. if (animDelta <= 0.0f)
  1055. {
  1056. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  1057. animDelta = DEFAULT_DELTA;
  1058. }
  1059. if (sourceSurface)
  1060. fadingSurface = sourceSurface;
  1061. delta = animDelta;
  1062. fadingMode = mode;
  1063. fadingCounter = initialCounter();
  1064. fading = true;
  1065. shouldFreeSurface = freeSurfaceAtEnd;
  1066. }
  1067. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1068. {
  1069. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1070. {
  1071. fading = false;
  1072. return;
  1073. }
  1074. CSDL_Ext::setAlpha(fadingSurface, (int)(fadingCounter * 255));
  1075. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1076. CSDL_Ext::setAlpha(fadingSurface, 255);
  1077. }