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