CAnimation.cpp 31 KB

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