CAnimation.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  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, const Rect *src=nullptr, ui8 alpha=255) const override;
  77. void draw(SDL_Surface * where, const SDL_Rect * dest, const 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. bool isTransparent(const Point & coords) const override;
  83. Point dimensions() const override;
  84. int width() const override;
  85. int height() const override;
  86. void horizontalFlip() override;
  87. void verticalFlip() override;
  88. void shiftPalette(int from, int howMany) override;
  89. void adjustPalette(const ColorShifter * shifter) override;
  90. void resetPalette() override;
  91. void setBorderPallete(const BorderPallete & borderPallete) override;
  92. friend class SDLImageLoader;
  93. private:
  94. SDL_Palette * originalPalette;
  95. };
  96. class SDLImageLoader
  97. {
  98. SDLImage * image;
  99. ui8 * lineStart;
  100. ui8 * position;
  101. public:
  102. //load size raw pixels from data
  103. inline void Load(size_t size, const ui8 * data);
  104. //set size pixels to color
  105. inline void Load(size_t size, ui8 color=0);
  106. inline void EndLine();
  107. //init image with these sizes and palette
  108. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  109. SDLImageLoader(SDLImage * Img);
  110. ~SDLImageLoader();
  111. };
  112. std::shared_ptr<IImage> IImage::createFromFile( const std::string & path )
  113. {
  114. return std::shared_ptr<IImage>(new SDLImage(path));
  115. }
  116. // Extremely simple file cache. TODO: smarter, more general solution
  117. class CFileCache
  118. {
  119. static const int cacheSize = 50; //Max number of cached files
  120. struct FileData
  121. {
  122. ResourceID name;
  123. size_t size;
  124. std::unique_ptr<ui8[]> data;
  125. std::unique_ptr<ui8[]> getCopy()
  126. {
  127. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  128. std::copy(data.get(), data.get() + size, ret.get());
  129. return ret;
  130. }
  131. FileData(ResourceID name_, size_t size_, std::unique_ptr<ui8[]> data_):
  132. name{std::move(name_)},
  133. size{size_},
  134. data{std::move(data_)}
  135. {}
  136. };
  137. std::deque<FileData> cache;
  138. public:
  139. std::unique_ptr<ui8[]> getCachedFile(ResourceID rid)
  140. {
  141. for(auto & file : cache)
  142. {
  143. if (file.name == rid)
  144. return file.getCopy();
  145. }
  146. // Still here? Cache miss
  147. if (cache.size() > cacheSize)
  148. cache.pop_front();
  149. auto data = CResourceHandler::get()->load(rid)->readAll();
  150. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  151. return cache.back().getCopy();
  152. }
  153. };
  154. enum class DefType : uint32_t
  155. {
  156. SPELL = 0x40,
  157. SPRITE = 0x41,
  158. CREATURE = 0x42,
  159. MAP = 0x43,
  160. MAP_HERO = 0x44,
  161. TERRAIN = 0x45,
  162. CURSOR = 0x46,
  163. INTERFACE = 0x47,
  164. SPRITE_FRAME = 0x48,
  165. BATTLE_HERO = 0x49
  166. };
  167. static CFileCache animationCache;
  168. /*************************************************************************
  169. * DefFile, class used for def loading *
  170. *************************************************************************/
  171. bool operator== (const SDL_Color & lhs, const SDL_Color & rhs)
  172. {
  173. return (lhs.a == rhs.a) && (lhs.b == rhs.b) &&(lhs.g == rhs.g) &&(lhs.r == rhs.r);
  174. }
  175. CDefFile::CDefFile(std::string Name):
  176. data(nullptr),
  177. palette(nullptr)
  178. {
  179. #if 0
  180. static SDL_Color H3_ORIG_PALETTE[8] =
  181. {
  182. { 0, 255, 255, SDL_ALPHA_OPAQUE},
  183. {255, 150, 255, SDL_ALPHA_OPAQUE},
  184. {255, 100, 255, SDL_ALPHA_OPAQUE},
  185. {255, 50, 255, SDL_ALPHA_OPAQUE},
  186. {255, 0, 255, SDL_ALPHA_OPAQUE},
  187. {255, 255, 0, SDL_ALPHA_OPAQUE},
  188. {180, 0, 255, SDL_ALPHA_OPAQUE},
  189. { 0, 255, 0, SDL_ALPHA_OPAQUE}
  190. };
  191. #endif // 0
  192. //First 8 colors in def palette used for transparency
  193. static SDL_Color H3Palette[8] =
  194. {
  195. { 0, 0, 0, 0},// 100% - transparency
  196. { 0, 0, 0, 32},// 75% - shadow border,
  197. { 0, 0, 0, 64},// TODO: find exact value
  198. { 0, 0, 0, 128},// TODO: for transparency
  199. { 0, 0, 0, 128},// 50% - shadow body
  200. { 0, 0, 0, 0},// 100% - selection highlight
  201. { 0, 0, 0, 128},// 50% - shadow body below selection
  202. { 0, 0, 0, 64} // 75% - shadow border below selection
  203. };
  204. data = animationCache.getCachedFile(ResourceID(std::string("SPRITES/") + Name, EResType::ANIMATION));
  205. palette = std::unique_ptr<SDL_Color[]>(new SDL_Color[256]);
  206. int it = 0;
  207. ui32 type = read_le_u32(data.get() + it);
  208. it+=4;
  209. //int width = read_le_u32(data + it); it+=4;//not used
  210. //int height = read_le_u32(data + it); it+=4;
  211. it+=8;
  212. ui32 totalBlocks = read_le_u32(data.get() + it);
  213. it+=4;
  214. for (ui32 i= 0; i<256; i++)
  215. {
  216. palette[i].r = data[it++];
  217. palette[i].g = data[it++];
  218. palette[i].b = data[it++];
  219. palette[i].a = SDL_ALPHA_OPAQUE;
  220. }
  221. switch(static_cast<DefType>(type))
  222. {
  223. case DefType::SPELL:
  224. palette[0] = H3Palette[0];
  225. break;
  226. case DefType::SPRITE:
  227. case DefType::SPRITE_FRAME:
  228. for(ui32 i= 0; i<8; i++)
  229. palette[i] = H3Palette[i];
  230. break;
  231. case DefType::CREATURE:
  232. palette[0] = H3Palette[0];
  233. palette[1] = H3Palette[1];
  234. palette[4] = H3Palette[4];
  235. palette[5] = H3Palette[5];
  236. palette[6] = H3Palette[6];
  237. palette[7] = H3Palette[7];
  238. break;
  239. case DefType::MAP:
  240. case DefType::MAP_HERO:
  241. palette[0] = H3Palette[0];
  242. palette[1] = H3Palette[1];
  243. palette[4] = H3Palette[4];
  244. //5 = owner flag, handled separately
  245. break;
  246. case DefType::TERRAIN:
  247. palette[0] = H3Palette[0];
  248. palette[1] = H3Palette[1];
  249. palette[2] = H3Palette[2];
  250. palette[3] = H3Palette[3];
  251. palette[4] = H3Palette[4];
  252. break;
  253. case DefType::CURSOR:
  254. palette[0] = H3Palette[0];
  255. break;
  256. case DefType::INTERFACE:
  257. palette[0] = H3Palette[0];
  258. palette[1] = H3Palette[1];
  259. palette[4] = H3Palette[4];
  260. //player colors handled separately
  261. //TODO: disallow colorizing other def types
  262. break;
  263. case DefType::BATTLE_HERO:
  264. palette[0] = H3Palette[0];
  265. palette[1] = H3Palette[1];
  266. palette[4] = H3Palette[4];
  267. break;
  268. default:
  269. logAnim->error("Unknown def type %d in %s", type, Name);
  270. break;
  271. }
  272. for (ui32 i=0; i<totalBlocks; i++)
  273. {
  274. size_t blockID = read_le_u32(data.get() + it);
  275. it+=4;
  276. size_t totalEntries = read_le_u32(data.get() + it);
  277. it+=12;
  278. //8 unknown bytes - skipping
  279. //13 bytes for name of every frame in this block - not used, skipping
  280. it+= 13 * (int)totalEntries;
  281. for (ui32 j=0; j<totalEntries; j++)
  282. {
  283. size_t currOffset = read_le_u32(data.get() + it);
  284. offset[blockID].push_back(currOffset);
  285. it += 4;
  286. }
  287. }
  288. }
  289. template<class ImageLoader>
  290. void CDefFile::loadFrame(size_t frame, size_t group, ImageLoader &loader) const
  291. {
  292. std::map<size_t, std::vector <size_t> >::const_iterator it;
  293. it = offset.find(group);
  294. assert (it != offset.end());
  295. const ui8 * FDef = data.get()+it->second[frame];
  296. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  297. SSpriteDef sprite;
  298. sprite.format = read_le_u32(&sd.format);
  299. sprite.fullWidth = read_le_u32(&sd.fullWidth);
  300. sprite.fullHeight = read_le_u32(&sd.fullHeight);
  301. sprite.width = read_le_u32(&sd.width);
  302. sprite.height = read_le_u32(&sd.height);
  303. sprite.leftMargin = read_le_u32(&sd.leftMargin);
  304. sprite.topMargin = read_le_u32(&sd.topMargin);
  305. ui32 currentOffset = sizeof(SSpriteDef);
  306. //special case for some "old" format defs (SGTWMTA.DEF and SGTWMTB.DEF)
  307. if(sprite.format == 1 && sprite.width > sprite.fullWidth && sprite.height > sprite.fullHeight)
  308. {
  309. sprite.leftMargin = 0;
  310. sprite.topMargin = 0;
  311. sprite.width = sprite.fullWidth;
  312. sprite.height = sprite.fullHeight;
  313. currentOffset -= 16;
  314. }
  315. const ui32 BaseOffset = currentOffset;
  316. loader.init(Point(sprite.width, sprite.height),
  317. Point(sprite.leftMargin, sprite.topMargin),
  318. Point(sprite.fullWidth, sprite.fullHeight), palette.get());
  319. switch(sprite.format)
  320. {
  321. case 0:
  322. {
  323. //pixel data is not compressed, copy data to surface
  324. for(ui32 i=0; i<sprite.height; i++)
  325. {
  326. loader.Load(sprite.width, FDef + currentOffset);
  327. currentOffset += sprite.width;
  328. loader.EndLine();
  329. }
  330. break;
  331. }
  332. case 1:
  333. {
  334. //for each line we have offset of pixel data
  335. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  336. currentOffset += sizeof(ui32) * sprite.height;
  337. for(ui32 i=0; i<sprite.height; i++)
  338. {
  339. //get position of the line
  340. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  341. ui32 TotalRowLength = 0;
  342. while(TotalRowLength<sprite.width)
  343. {
  344. ui8 segmentType = FDef[currentOffset++];
  345. ui32 length = FDef[currentOffset++] + 1;
  346. if(segmentType==0xFF)//Raw data
  347. {
  348. loader.Load(length, FDef + currentOffset);
  349. currentOffset+=length;
  350. }
  351. else// RLE
  352. {
  353. loader.Load(length, segmentType);
  354. }
  355. TotalRowLength += length;
  356. }
  357. loader.EndLine();
  358. }
  359. break;
  360. }
  361. case 2:
  362. {
  363. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  364. for(ui32 i=0; i<sprite.height; i++)
  365. {
  366. ui32 TotalRowLength=0;
  367. while(TotalRowLength<sprite.width)
  368. {
  369. ui8 segment=FDef[currentOffset++];
  370. ui8 code = segment / 32;
  371. ui8 length = (segment & 31) + 1;
  372. if(code==7)//Raw data
  373. {
  374. loader.Load(length, FDef + currentOffset);
  375. currentOffset += length;
  376. }
  377. else//RLE
  378. {
  379. loader.Load(length, code);
  380. }
  381. TotalRowLength+=length;
  382. }
  383. loader.EndLine();
  384. }
  385. break;
  386. }
  387. case 3:
  388. {
  389. for(ui32 i=0; i<sprite.height; i++)
  390. {
  391. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  392. ui32 TotalRowLength=0;
  393. while(TotalRowLength<sprite.width)
  394. {
  395. ui8 segment = FDef[currentOffset++];
  396. ui8 code = segment / 32;
  397. ui8 length = (segment & 31) + 1;
  398. if(code==7)//Raw data
  399. {
  400. loader.Load(length, FDef + currentOffset);
  401. currentOffset += length;
  402. }
  403. else//RLE
  404. {
  405. loader.Load(length, code);
  406. }
  407. TotalRowLength += length;
  408. }
  409. loader.EndLine();
  410. }
  411. break;
  412. }
  413. default:
  414. logGlobal->error("Error: unsupported format of def file: %d", sprite.format);
  415. break;
  416. }
  417. }
  418. CDefFile::~CDefFile() = default;
  419. const std::map<size_t, size_t > CDefFile::getEntries() const
  420. {
  421. std::map<size_t, size_t > ret;
  422. for (auto & elem : offset)
  423. ret[elem.first] = elem.second.size();
  424. return ret;
  425. }
  426. /*************************************************************************
  427. * Classes for image loaders - helpers for loading from def files *
  428. *************************************************************************/
  429. SDLImageLoader::SDLImageLoader(SDLImage * Img):
  430. image(Img),
  431. lineStart(nullptr),
  432. position(nullptr)
  433. {
  434. }
  435. void SDLImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  436. {
  437. //Init image
  438. image->surf = SDL_CreateRGBSurface(0, SpriteSize.x, SpriteSize.y, 8, 0, 0, 0, 0);
  439. image->margins = Margins;
  440. image->fullSize = FullSize;
  441. //Prepare surface
  442. SDL_Palette * p = SDL_AllocPalette(SDLImage::DEFAULT_PALETTE_COLORS);
  443. SDL_SetPaletteColors(p, pal, 0, SDLImage::DEFAULT_PALETTE_COLORS);
  444. SDL_SetSurfacePalette(image->surf, p);
  445. SDL_FreePalette(p);
  446. SDL_LockSurface(image->surf);
  447. lineStart = position = (ui8*)image->surf->pixels;
  448. }
  449. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  450. {
  451. if (size)
  452. {
  453. memcpy((void *)position, data, size);
  454. position += size;
  455. }
  456. }
  457. inline void SDLImageLoader::Load(size_t size, ui8 color)
  458. {
  459. if (size)
  460. {
  461. memset((void *)position, color, size);
  462. position += size;
  463. }
  464. }
  465. inline void SDLImageLoader::EndLine()
  466. {
  467. lineStart += image->surf->pitch;
  468. position = lineStart;
  469. }
  470. SDLImageLoader::~SDLImageLoader()
  471. {
  472. SDL_UnlockSurface(image->surf);
  473. SDL_SetColorKey(image->surf, SDL_TRUE, 0);
  474. //TODO: RLE if compressed and bpp>1
  475. }
  476. /*************************************************************************
  477. * Classes for images, support loading from file and drawing on surface *
  478. *************************************************************************/
  479. IImage::IImage() = default;
  480. IImage::~IImage() = default;
  481. SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group)
  482. : surf(nullptr),
  483. margins(0, 0),
  484. fullSize(0, 0),
  485. originalPalette(nullptr)
  486. {
  487. SDLImageLoader loader(this);
  488. data->loadFrame(frame, group, loader);
  489. savePalette();
  490. }
  491. SDLImage::SDLImage(SDL_Surface * from, bool extraRef)
  492. : surf(nullptr),
  493. margins(0, 0),
  494. fullSize(0, 0),
  495. originalPalette(nullptr)
  496. {
  497. surf = from;
  498. if (surf == nullptr)
  499. return;
  500. savePalette();
  501. if (extraRef)
  502. surf->refcount++;
  503. fullSize.x = surf->w;
  504. fullSize.y = surf->h;
  505. }
  506. SDLImage::SDLImage(const JsonNode & conf)
  507. : surf(nullptr),
  508. margins(0, 0),
  509. fullSize(0, 0),
  510. originalPalette(nullptr)
  511. {
  512. std::string filename = conf["file"].String();
  513. surf = BitmapHandler::loadBitmap(filename);
  514. if(surf == nullptr)
  515. return;
  516. savePalette();
  517. const JsonNode & jsonMargins = conf["margins"];
  518. margins.x = static_cast<int>(jsonMargins["left"].Integer());
  519. margins.y = static_cast<int>(jsonMargins["top"].Integer());
  520. fullSize.x = static_cast<int>(conf["width"].Integer());
  521. fullSize.y = static_cast<int>(conf["height"].Integer());
  522. if(fullSize.x == 0)
  523. {
  524. fullSize.x = margins.x + surf->w + (int)jsonMargins["right"].Integer();
  525. }
  526. if(fullSize.y == 0)
  527. {
  528. fullSize.y = margins.y + surf->h + (int)jsonMargins["bottom"].Integer();
  529. }
  530. }
  531. SDLImage::SDLImage(std::string filename)
  532. : surf(nullptr),
  533. margins(0, 0),
  534. fullSize(0, 0),
  535. originalPalette(nullptr)
  536. {
  537. surf = BitmapHandler::loadBitmap(filename);
  538. if(surf == nullptr)
  539. {
  540. logGlobal->error("Error: failed to load image %s", filename);
  541. return;
  542. }
  543. else
  544. {
  545. savePalette();
  546. fullSize.x = surf->w;
  547. fullSize.y = surf->h;
  548. }
  549. }
  550. void SDLImage::draw(SDL_Surface *where, int posX, int posY, const Rect *src, ui8 alpha) const
  551. {
  552. if(!surf)
  553. return;
  554. Rect destRect(posX, posY, surf->w, surf->h);
  555. draw(where, &destRect, src);
  556. }
  557. void SDLImage::draw(SDL_Surface* where, const SDL_Rect* dest, const SDL_Rect* src, ui8 alpha) const
  558. {
  559. if (!surf)
  560. return;
  561. Rect sourceRect(0, 0, surf->w, surf->h);
  562. Point destShift(0, 0);
  563. if(src)
  564. {
  565. if(src->x < margins.x)
  566. destShift.x += margins.x - src->x;
  567. if(src->y < margins.y)
  568. destShift.y += margins.y - src->y;
  569. sourceRect = Rect(*src) & Rect(margins.x, margins.y, surf->w, surf->h);
  570. sourceRect -= margins;
  571. }
  572. else
  573. destShift = margins;
  574. Rect destRect(destShift.x, destShift.y, surf->w, surf->h);
  575. if(dest)
  576. {
  577. destRect.x += dest->x;
  578. destRect.y += dest->y;
  579. }
  580. if(surf->format->BitsPerPixel == 8)
  581. {
  582. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  583. }
  584. else
  585. {
  586. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  587. }
  588. }
  589. std::shared_ptr<IImage> SDLImage::scaleFast(float scale) const
  590. {
  591. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, (int)(surf->w * scale), (int)(surf->h * scale));
  592. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  593. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  594. else if(scaled->format && scaled->format->Amask)
  595. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  596. else
  597. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  598. SDLImage * ret = new SDLImage(scaled, false);
  599. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  600. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  601. ret->margins.x = (int) round((float)margins.x * scale);
  602. ret->margins.y = (int) round((float)margins.y * scale);
  603. return std::shared_ptr<IImage>(ret);
  604. }
  605. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  606. {
  607. SDL_SaveBMP(surf, path.string().c_str());
  608. }
  609. void SDLImage::playerColored(PlayerColor player)
  610. {
  611. graphics->blueToPlayersAdv(surf, player);
  612. }
  613. void SDLImage::setFlagColor(PlayerColor player)
  614. {
  615. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  616. CSDL_Ext::setPlayerColor(surf, player);
  617. }
  618. int SDLImage::width() const
  619. {
  620. return fullSize.x;
  621. }
  622. int SDLImage::height() const
  623. {
  624. return fullSize.y;
  625. }
  626. bool SDLImage::isTransparent(const Point & coords) const
  627. {
  628. return CSDL_Ext::isTransparent(surf, coords.x, coords.y);
  629. }
  630. Point SDLImage::dimensions() const
  631. {
  632. return fullSize;
  633. }
  634. void SDLImage::horizontalFlip()
  635. {
  636. margins.y = fullSize.y - surf->h - margins.y;
  637. //todo: modify in-place
  638. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  639. SDL_FreeSurface(surf);
  640. surf = flipped;
  641. }
  642. void SDLImage::verticalFlip()
  643. {
  644. margins.x = fullSize.x - surf->w - margins.x;
  645. //todo: modify in-place
  646. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  647. SDL_FreeSurface(surf);
  648. surf = flipped;
  649. }
  650. // Keep the original palette, in order to do color switching operation
  651. void SDLImage::savePalette()
  652. {
  653. // For some images that don't have palette, skip this
  654. if(surf->format->palette == nullptr)
  655. return;
  656. if(originalPalette == nullptr)
  657. originalPalette = SDL_AllocPalette(DEFAULT_PALETTE_COLORS);
  658. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, DEFAULT_PALETTE_COLORS);
  659. }
  660. void SDLImage::shiftPalette(int from, int howMany)
  661. {
  662. //works with at most 16 colors, if needed more -> increase values
  663. assert(howMany < 16);
  664. if(surf->format->palette)
  665. {
  666. SDL_Color palette[16];
  667. for(int i=0; i<howMany; ++i)
  668. {
  669. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  670. }
  671. SDL_SetColors(surf, palette, from, howMany);
  672. }
  673. }
  674. void SDLImage::adjustPalette(const ColorShifter * shifter)
  675. {
  676. if(originalPalette == nullptr)
  677. return;
  678. SDL_Palette* palette = surf->format->palette;
  679. // Note: here we skip the first 8 colors in the palette that predefined in H3Palette
  680. for(int i = 8; i < palette->ncolors; i++)
  681. {
  682. palette->colors[i] = shifter->shiftColor(originalPalette->colors[i]);
  683. }
  684. }
  685. void SDLImage::resetPalette()
  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, 0, originalPalette->ncolors);
  691. }
  692. void SDLImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  693. {
  694. if(surf->format->palette)
  695. {
  696. SDL_SetColors(surf, const_cast<SDL_Color *>(borderPallete.data()), 5, 3);
  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::shiftColor(const ColorShifter * shifter)
  910. {
  911. for(auto groupIter = images.begin(); groupIter != images.end(); groupIter++)
  912. {
  913. for(auto frameIter = groupIter->second.begin(); frameIter != groupIter->second.end(); frameIter++)
  914. {
  915. std::shared_ptr<IImage> image = frameIter->second;
  916. image->adjustPalette(shifter);
  917. }
  918. }
  919. }
  920. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  921. {
  922. if (source[group].size() <= frame)
  923. source[group].resize(frame+1);
  924. source[group][frame]["file"].String() = filename;
  925. //FIXME: update image if already loaded
  926. }
  927. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  928. {
  929. auto groupIter = images.find(group);
  930. if (groupIter != images.end())
  931. {
  932. auto imageIter = groupIter->second.find(frame);
  933. if (imageIter != groupIter->second.end())
  934. return imageIter->second;
  935. }
  936. if (verbose)
  937. printError(frame, group, "GetImage");
  938. return nullptr;
  939. }
  940. void CAnimation::load()
  941. {
  942. for (auto & elem : source)
  943. for (size_t image=0; image < elem.second.size(); image++)
  944. loadFrame(image, elem.first);
  945. }
  946. void CAnimation::unload()
  947. {
  948. for (auto & elem : source)
  949. for (size_t image=0; image < elem.second.size(); image++)
  950. unloadFrame(image, elem.first);
  951. }
  952. void CAnimation::preload()
  953. {
  954. if(!preloaded)
  955. {
  956. preloaded = true;
  957. load();
  958. }
  959. }
  960. void CAnimation::loadGroup(size_t group)
  961. {
  962. if (vstd::contains(source, group))
  963. for (size_t image=0; image < source[group].size(); image++)
  964. loadFrame(image, group);
  965. }
  966. void CAnimation::unloadGroup(size_t group)
  967. {
  968. if (vstd::contains(source, group))
  969. for (size_t image=0; image < source[group].size(); image++)
  970. unloadFrame(image, group);
  971. }
  972. void CAnimation::load(size_t frame, size_t group)
  973. {
  974. loadFrame(frame, group);
  975. }
  976. void CAnimation::unload(size_t frame, size_t group)
  977. {
  978. unloadFrame(frame, group);
  979. }
  980. size_t CAnimation::size(size_t group) const
  981. {
  982. auto iter = source.find(group);
  983. if (iter != source.end())
  984. return iter->second.size();
  985. return 0;
  986. }
  987. void CAnimation::horizontalFlip()
  988. {
  989. for(auto & group : images)
  990. for(auto & image : group.second)
  991. image.second->horizontalFlip();
  992. }
  993. void CAnimation::verticalFlip()
  994. {
  995. for(auto & group : images)
  996. for(auto & image : group.second)
  997. image.second->verticalFlip();
  998. }
  999. void CAnimation::playerColored(PlayerColor player)
  1000. {
  1001. for(auto & group : images)
  1002. for(auto & image : group.second)
  1003. image.second->playerColored(player);
  1004. }
  1005. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  1006. {
  1007. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  1008. {
  1009. duplicateImage(sourceGroup, frame, targetGroup);
  1010. auto image = getImage(frame, targetGroup);
  1011. image->verticalFlip();
  1012. }
  1013. }
  1014. float CFadeAnimation::initialCounter() const
  1015. {
  1016. if (fadingMode == EMode::OUT)
  1017. return 1.0f;
  1018. return 0.0f;
  1019. }
  1020. void CFadeAnimation::update()
  1021. {
  1022. if (!fading)
  1023. return;
  1024. if (fadingMode == EMode::OUT)
  1025. fadingCounter -= delta;
  1026. else
  1027. fadingCounter += delta;
  1028. if (isFinished())
  1029. {
  1030. fading = false;
  1031. if (shouldFreeSurface)
  1032. {
  1033. SDL_FreeSurface(fadingSurface);
  1034. fadingSurface = nullptr;
  1035. }
  1036. }
  1037. }
  1038. bool CFadeAnimation::isFinished() const
  1039. {
  1040. if (fadingMode == EMode::OUT)
  1041. return fadingCounter <= 0.0f;
  1042. return fadingCounter >= 1.0f;
  1043. }
  1044. CFadeAnimation::CFadeAnimation()
  1045. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  1046. fadingMode(EMode::NONE)
  1047. {
  1048. }
  1049. CFadeAnimation::~CFadeAnimation()
  1050. {
  1051. if (fadingSurface && shouldFreeSurface)
  1052. SDL_FreeSurface(fadingSurface);
  1053. }
  1054. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  1055. {
  1056. if (fading)
  1057. {
  1058. // in that case, immediately finish the previous fade
  1059. // (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))
  1060. logGlobal->warn("Tried to init fading animation that is already running.");
  1061. if (fadingSurface && shouldFreeSurface)
  1062. SDL_FreeSurface(fadingSurface);
  1063. }
  1064. if (animDelta <= 0.0f)
  1065. {
  1066. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  1067. animDelta = DEFAULT_DELTA;
  1068. }
  1069. if (sourceSurface)
  1070. fadingSurface = sourceSurface;
  1071. delta = animDelta;
  1072. fadingMode = mode;
  1073. fadingCounter = initialCounter();
  1074. fading = true;
  1075. shouldFreeSurface = freeSurfaceAtEnd;
  1076. }
  1077. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1078. {
  1079. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1080. {
  1081. fading = false;
  1082. return;
  1083. }
  1084. CSDL_Ext::setAlpha(fadingSurface, (int)(fadingCounter * 255));
  1085. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1086. CSDL_Ext::setAlpha(fadingSurface, 255);
  1087. }