CAnimation.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  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_image.h>
  13. #include "../CBitmapHandler.h"
  14. #include "../Graphics.h"
  15. #include "../gui/SDL_Extensions.h"
  16. #include "../gui/SDL_Pixels.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. class CompImageLoader;
  23. typedef std::map <size_t, std::vector <JsonNode> > source_map;
  24. typedef std::map<size_t, IImage* > image_map;
  25. typedef std::map<size_t, image_map > group_map;
  26. /// Class for def loading
  27. /// After loading will store general info (palette and frame offsets) and pointer to file itself
  28. class CDefFile
  29. {
  30. private:
  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;
  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. //Surface without empty borders
  61. SDL_Surface * surf;
  62. //size of left and top borders
  63. Point margins;
  64. //total size including borders
  65. Point fullSize;
  66. public:
  67. //Load image from def file
  68. SDLImage(CDefFile *data, size_t frame, size_t group=0, bool compressed=false);
  69. //Load from bitmap file
  70. SDLImage(std::string filename, bool compressed=false);
  71. SDLImage(const JsonNode & conf);
  72. //Create using existing surface, extraRef will increase refcount on SDL_Surface
  73. SDLImage(SDL_Surface * from, bool extraRef);
  74. ~SDLImage();
  75. void draw(SDL_Surface * where, int posX=0, int posY=0, Rect *src=nullptr, ui8 alpha=255) const override;
  76. void draw(SDL_Surface * where, SDL_Rect * dest, SDL_Rect * src, ui8 alpha=255) const override;
  77. std::shared_ptr<IImage> scaleFast(float scale) const override;
  78. void exportBitmap(const boost::filesystem::path & path) const override;
  79. void playerColored(PlayerColor player) override;
  80. void setFlagColor(PlayerColor player) override;
  81. int width() const override;
  82. int height() const override;
  83. void horizontalFlip() override;
  84. void verticalFlip() override;
  85. void shiftPalette(int from, int howMany) override;
  86. void setBorderPallete(const BorderPallete & borderPallete) override;
  87. friend class SDLImageLoader;
  88. };
  89. /*
  90. * RLE-compressed image data for 8-bit images with alpha-channel, currently far from finished
  91. * primary purpose is not high compression ratio but fast drawing.
  92. * Consist of repeatable segments with format similar to H3 def compression:
  93. * 1st byte:
  94. * if (byte == 0xff)
  95. * raw data, opaque and semi-transparent data always in separate blocks
  96. * else
  97. * RLE-compressed image data with this color
  98. * 2nd byte = size of segment
  99. * raw data (if any)
  100. */
  101. class CompImage : public IImage
  102. {
  103. //x,y - margins, w,h - sprite size
  104. Rect sprite;
  105. //total size including borders
  106. Point fullSize;
  107. //RLE-d data
  108. ui8 * surf;
  109. //array of offsets for each line
  110. ui32 * line;
  111. //palette
  112. SDL_Color *palette;
  113. //Used internally to blit one block of data
  114. template<int bpp, int dir>
  115. void BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const;
  116. void BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const;
  117. public:
  118. //Load image from def file
  119. CompImage(const CDefFile *data, size_t frame, size_t group=0);
  120. //TODO: load image from SDL_Surface
  121. CompImage(SDL_Surface * surf);
  122. ~CompImage();
  123. void draw(SDL_Surface *where, int posX=0, int posY=0, Rect *src=nullptr, ui8 alpha=255) const override;
  124. void draw(SDL_Surface * where, SDL_Rect * dest, SDL_Rect * src, ui8 alpha=255) const override;
  125. std::shared_ptr<IImage> scaleFast(float scale) const override;
  126. void exportBitmap(const boost::filesystem::path & path) const override;
  127. void playerColored(PlayerColor player) override;
  128. void setFlagColor(PlayerColor player) override;
  129. int width() const override;
  130. int height() const override;
  131. void horizontalFlip() override;
  132. void verticalFlip() override;
  133. void shiftPalette(int from, int howMany) override;
  134. void setBorderPallete(const BorderPallete & borderPallete) override;
  135. friend class CompImageLoader;
  136. };
  137. class SDLImageLoader
  138. {
  139. SDLImage * image;
  140. ui8 * lineStart;
  141. ui8 * position;
  142. public:
  143. //load size raw pixels from data
  144. inline void Load(size_t size, const ui8 * data);
  145. //set size pixels to color
  146. inline void Load(size_t size, ui8 color=0);
  147. inline void EndLine();
  148. //init image with these sizes and palette
  149. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  150. SDLImageLoader(SDLImage * Img);
  151. ~SDLImageLoader();
  152. };
  153. class CompImageLoader
  154. {
  155. CompImage * image;
  156. ui8 *position;
  157. ui8 *entry;
  158. ui32 currentLine;
  159. inline ui8 typeOf(ui8 color);
  160. inline void NewEntry(ui8 color, size_t size);
  161. inline void NewEntry(const ui8 * &data, size_t size);
  162. public:
  163. //load size raw pixels from data
  164. inline void Load(size_t size, const ui8 * data);
  165. //set size pixels to color
  166. inline void Load(size_t size, ui8 color=0);
  167. inline void EndLine();
  168. //init image with these sizes and palette
  169. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  170. CompImageLoader(CompImage * Img);
  171. ~CompImageLoader();
  172. };
  173. // Extremely simple file cache. TODO: smarter, more general solution
  174. class CFileCache
  175. {
  176. static const int cacheSize = 50; //Max number of cached files
  177. struct FileData
  178. {
  179. ResourceID name;
  180. size_t size;
  181. std::unique_ptr<ui8[]> data;
  182. std::unique_ptr<ui8[]> getCopy()
  183. {
  184. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  185. std::copy(data.get(), data.get() + size, ret.get());
  186. return ret;
  187. }
  188. FileData(ResourceID name_, size_t size_, std::unique_ptr<ui8[]> data_):
  189. name{std::move(name_)},
  190. size{size_},
  191. data{std::move(data_)}
  192. {}
  193. };
  194. std::deque<FileData> cache;
  195. public:
  196. std::unique_ptr<ui8[]> getCachedFile(ResourceID rid)
  197. {
  198. for(auto & file : cache)
  199. {
  200. if (file.name == rid)
  201. return file.getCopy();
  202. }
  203. // Still here? Cache miss
  204. if (cache.size() > cacheSize)
  205. cache.pop_front();
  206. auto data = CResourceHandler::get()->load(rid)->readAll();
  207. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  208. return cache.back().getCopy();
  209. }
  210. };
  211. enum class DefType : uint32_t
  212. {
  213. SPELL = 0x40,
  214. SPRITE = 0x41,
  215. CREATURE = 0x42,
  216. MAP = 0x43,
  217. MAP_HERO = 0x44,
  218. TERRAIN = 0x45,
  219. CURSOR = 0x46,
  220. INTERFACE = 0x47,
  221. SPRITE_FRAME = 0x48,
  222. BATTLE_HERO = 0x49
  223. };
  224. static CFileCache animationCache;
  225. /*************************************************************************
  226. * DefFile, class used for def loading *
  227. *************************************************************************/
  228. bool operator== (const SDL_Color & lhs, const SDL_Color & rhs)
  229. {
  230. return (lhs.a == rhs.a) && (lhs.b == rhs.b) &&(lhs.g == rhs.g) &&(lhs.r == rhs.r);
  231. }
  232. CDefFile::CDefFile(std::string Name):
  233. data(nullptr),
  234. palette(nullptr)
  235. {
  236. #if 0
  237. static SDL_Color H3_ORIG_PALETTE[8] =
  238. {
  239. { 0, 255, 255, SDL_ALPHA_OPAQUE},
  240. {255, 150, 255, SDL_ALPHA_OPAQUE},
  241. {255, 100, 255, SDL_ALPHA_OPAQUE},
  242. {255, 50, 255, SDL_ALPHA_OPAQUE},
  243. {255, 0, 255, SDL_ALPHA_OPAQUE},
  244. {255, 255, 0, SDL_ALPHA_OPAQUE},
  245. {180, 0, 255, SDL_ALPHA_OPAQUE},
  246. { 0, 255, 0, SDL_ALPHA_OPAQUE}
  247. };
  248. #endif // 0
  249. //First 8 colors in def palette used for transparency
  250. static SDL_Color H3Palette[8] =
  251. {
  252. { 0, 0, 0, 0},// 100% - transparency
  253. { 0, 0, 0, 32},// 75% - shadow border,
  254. { 0, 0, 0, 64},// TODO: find exact value
  255. { 0, 0, 0, 128},// TODO: for transparency
  256. { 0, 0, 0, 128},// 50% - shadow body
  257. { 0, 0, 0, 0},// 100% - selection highlight
  258. { 0, 0, 0, 128},// 50% - shadow body below selection
  259. { 0, 0, 0, 64} // 75% - shadow border below selection
  260. };
  261. data = animationCache.getCachedFile(ResourceID(std::string("SPRITES/") + Name, EResType::ANIMATION));
  262. palette = std::unique_ptr<SDL_Color[]>(new SDL_Color[256]);
  263. int it = 0;
  264. ui32 type = read_le_u32(data.get() + it);
  265. it+=4;
  266. //int width = read_le_u32(data + it); it+=4;//not used
  267. //int height = read_le_u32(data + it); it+=4;
  268. it+=8;
  269. ui32 totalBlocks = read_le_u32(data.get() + it);
  270. it+=4;
  271. for (ui32 i= 0; i<256; i++)
  272. {
  273. palette[i].r = data[it++];
  274. palette[i].g = data[it++];
  275. palette[i].b = data[it++];
  276. palette[i].a = SDL_ALPHA_OPAQUE;
  277. }
  278. switch(static_cast<DefType>(type))
  279. {
  280. case DefType::SPELL:
  281. palette[0] = H3Palette[0];
  282. break;
  283. case DefType::SPRITE:
  284. case DefType::SPRITE_FRAME:
  285. for(ui32 i= 0; i<8; i++)
  286. palette[i] = H3Palette[i];
  287. break;
  288. case DefType::CREATURE:
  289. palette[0] = H3Palette[0];
  290. palette[1] = H3Palette[1];
  291. palette[4] = H3Palette[4];
  292. palette[5] = H3Palette[5];
  293. palette[6] = H3Palette[6];
  294. palette[7] = H3Palette[7];
  295. break;
  296. case DefType::MAP:
  297. case DefType::MAP_HERO:
  298. palette[0] = H3Palette[0];
  299. palette[1] = H3Palette[1];
  300. palette[4] = H3Palette[4];
  301. //5 = owner flag, handled separately
  302. break;
  303. case DefType::TERRAIN:
  304. palette[0] = H3Palette[0];
  305. palette[1] = H3Palette[1];
  306. palette[2] = H3Palette[2];
  307. palette[3] = H3Palette[3];
  308. palette[4] = H3Palette[4];
  309. break;
  310. case DefType::CURSOR:
  311. palette[0] = H3Palette[0];
  312. break;
  313. case DefType::INTERFACE:
  314. palette[0] = H3Palette[0];
  315. palette[1] = H3Palette[1];
  316. palette[4] = H3Palette[4];
  317. //player colors handled separately
  318. //TODO: disallow colorizing other def types
  319. break;
  320. case DefType::BATTLE_HERO:
  321. palette[0] = H3Palette[0];
  322. palette[1] = H3Palette[1];
  323. palette[4] = H3Palette[4];
  324. break;
  325. default:
  326. logAnim->error("Unknown def type %d in %s", type, Name);
  327. break;
  328. }
  329. for (ui32 i=0; i<totalBlocks; i++)
  330. {
  331. size_t blockID = read_le_u32(data.get() + it);
  332. it+=4;
  333. size_t totalEntries = read_le_u32(data.get() + it);
  334. it+=12;
  335. //8 unknown bytes - skipping
  336. //13 bytes for name of every frame in this block - not used, skipping
  337. it+= 13 * totalEntries;
  338. for (ui32 j=0; j<totalEntries; j++)
  339. {
  340. size_t currOffset = read_le_u32(data.get() + it);
  341. offset[blockID].push_back(currOffset);
  342. it += 4;
  343. }
  344. }
  345. }
  346. template<class ImageLoader>
  347. void CDefFile::loadFrame(size_t frame, size_t group, ImageLoader &loader) const
  348. {
  349. std::map<size_t, std::vector <size_t> >::const_iterator it;
  350. it = offset.find(group);
  351. assert (it != offset.end());
  352. const ui8 * FDef = data.get()+it->second[frame];
  353. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  354. SSpriteDef sprite;
  355. sprite.format = read_le_u32(&sd.format);
  356. sprite.fullWidth = read_le_u32(&sd.fullWidth);
  357. sprite.fullHeight = read_le_u32(&sd.fullHeight);
  358. sprite.width = read_le_u32(&sd.width);
  359. sprite.height = read_le_u32(&sd.height);
  360. sprite.leftMargin = read_le_u32(&sd.leftMargin);
  361. sprite.topMargin = read_le_u32(&sd.topMargin);
  362. ui32 currentOffset = sizeof(SSpriteDef);
  363. //special case for some "old" format defs (SGTWMTA.DEF and SGTWMTB.DEF)
  364. if(sprite.format == 1 && sprite.width > sprite.fullWidth && sprite.height > sprite.fullHeight)
  365. {
  366. sprite.leftMargin = 0;
  367. sprite.topMargin = 0;
  368. sprite.width = sprite.fullWidth;
  369. sprite.height = sprite.fullHeight;
  370. currentOffset -= 16;
  371. }
  372. const ui32 BaseOffset = currentOffset;
  373. loader.init(Point(sprite.width, sprite.height),
  374. Point(sprite.leftMargin, sprite.topMargin),
  375. Point(sprite.fullWidth, sprite.fullHeight), palette.get());
  376. switch(sprite.format)
  377. {
  378. case 0:
  379. {
  380. //pixel data is not compressed, copy data to surface
  381. for(ui32 i=0; i<sprite.height; i++)
  382. {
  383. loader.Load(sprite.width, FDef + currentOffset);
  384. currentOffset += sprite.width;
  385. loader.EndLine();
  386. }
  387. break;
  388. }
  389. case 1:
  390. {
  391. //for each line we have offset of pixel data
  392. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  393. currentOffset += sizeof(ui32) * sprite.height;
  394. for(ui32 i=0; i<sprite.height; i++)
  395. {
  396. //get position of the line
  397. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  398. ui32 TotalRowLength = 0;
  399. while(TotalRowLength<sprite.width)
  400. {
  401. ui8 segmentType = FDef[currentOffset++];
  402. ui32 length = FDef[currentOffset++] + 1;
  403. if(segmentType==0xFF)//Raw data
  404. {
  405. loader.Load(length, FDef + currentOffset);
  406. currentOffset+=length;
  407. }
  408. else// RLE
  409. {
  410. loader.Load(length, segmentType);
  411. }
  412. TotalRowLength += length;
  413. }
  414. loader.EndLine();
  415. }
  416. break;
  417. }
  418. case 2:
  419. {
  420. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  421. for(ui32 i=0; i<sprite.height; i++)
  422. {
  423. ui32 TotalRowLength=0;
  424. while(TotalRowLength<sprite.width)
  425. {
  426. ui8 segment=FDef[currentOffset++];
  427. ui8 code = segment / 32;
  428. ui8 length = (segment & 31) + 1;
  429. if(code==7)//Raw data
  430. {
  431. loader.Load(length, FDef + currentOffset);
  432. currentOffset += length;
  433. }
  434. else//RLE
  435. {
  436. loader.Load(length, code);
  437. }
  438. TotalRowLength+=length;
  439. }
  440. loader.EndLine();
  441. }
  442. break;
  443. }
  444. case 3:
  445. {
  446. for(ui32 i=0; i<sprite.height; i++)
  447. {
  448. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  449. ui32 TotalRowLength=0;
  450. while(TotalRowLength<sprite.width)
  451. {
  452. ui8 segment = FDef[currentOffset++];
  453. ui8 code = segment / 32;
  454. ui8 length = (segment & 31) + 1;
  455. if(code==7)//Raw data
  456. {
  457. loader.Load(length, FDef + currentOffset);
  458. currentOffset += length;
  459. }
  460. else//RLE
  461. {
  462. loader.Load(length, code);
  463. }
  464. TotalRowLength += length;
  465. }
  466. loader.EndLine();
  467. }
  468. break;
  469. }
  470. default:
  471. logGlobal->error("Error: unsupported format of def file: %d", sprite.format);
  472. break;
  473. }
  474. }
  475. CDefFile::~CDefFile() = default;
  476. const std::map<size_t, size_t > CDefFile::getEntries() const
  477. {
  478. std::map<size_t, size_t > ret;
  479. for (auto & elem : offset)
  480. ret[elem.first] = elem.second.size();
  481. return ret;
  482. }
  483. /*************************************************************************
  484. * Classes for image loaders - helpers for loading from def files *
  485. *************************************************************************/
  486. SDLImageLoader::SDLImageLoader(SDLImage * Img):
  487. image(Img),
  488. lineStart(nullptr),
  489. position(nullptr)
  490. {
  491. }
  492. void SDLImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  493. {
  494. //Init image
  495. image->surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SpriteSize.x, SpriteSize.y, 8, 0, 0, 0, 0);
  496. image->margins = Margins;
  497. image->fullSize = FullSize;
  498. //Prepare surface
  499. SDL_Palette * p = SDL_AllocPalette(256);
  500. SDL_SetPaletteColors(p, pal, 0, 256);
  501. SDL_SetSurfacePalette(image->surf, p);
  502. SDL_FreePalette(p);
  503. SDL_LockSurface(image->surf);
  504. lineStart = position = (ui8*)image->surf->pixels;
  505. }
  506. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  507. {
  508. if (size)
  509. {
  510. memcpy((void *)position, data, size);
  511. position += size;
  512. }
  513. }
  514. inline void SDLImageLoader::Load(size_t size, ui8 color)
  515. {
  516. if (size)
  517. {
  518. memset((void *)position, color, size);
  519. position += size;
  520. }
  521. }
  522. inline void SDLImageLoader::EndLine()
  523. {
  524. lineStart += image->surf->pitch;
  525. position = lineStart;
  526. }
  527. SDLImageLoader::~SDLImageLoader()
  528. {
  529. SDL_UnlockSurface(image->surf);
  530. SDL_SetColorKey(image->surf, SDL_TRUE, 0);
  531. //TODO: RLE if compressed and bpp>1
  532. }
  533. ////////////////////////////////////////////////////////////////////////////////
  534. CompImageLoader::CompImageLoader(CompImage * Img):
  535. image(Img),
  536. position(nullptr),
  537. entry(nullptr),
  538. currentLine(0)
  539. {
  540. }
  541. void CompImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  542. {
  543. image->sprite = Rect(Margins, SpriteSize);
  544. image->fullSize = FullSize;
  545. if (SpriteSize.x && SpriteSize.y)
  546. {
  547. image->palette = new SDL_Color[256];
  548. memcpy((void*)image->palette, (void*)pal, 256*sizeof(SDL_Color));
  549. //Allocate enought space for worst possible case, c-style malloc used due to resizing after load
  550. image->surf = (ui8*)malloc(SpriteSize.x*SpriteSize.y*3);
  551. image->line = new ui32[SpriteSize.y+1];
  552. image->line[0] = 0;
  553. position = image->surf;
  554. }
  555. }
  556. inline void CompImageLoader::NewEntry(ui8 color, size_t size)
  557. {
  558. assert(color != 0xff);
  559. assert(size && size<256);
  560. entry = position;
  561. entry[0] = color;
  562. entry[1] = size;
  563. position +=2;
  564. }
  565. inline void CompImageLoader::NewEntry(const ui8 * &data, size_t size)
  566. {
  567. assert(size && size<256);
  568. entry = position;
  569. entry[0] = 0xff;
  570. entry[1] = size;
  571. position +=2;
  572. memcpy(position, data, size);
  573. position+=size;
  574. data+=size;
  575. }
  576. inline ui8 CompImageLoader::typeOf(ui8 color)
  577. {
  578. if (color == 0)
  579. return 0;
  580. if (image->palette[color].a != 255)
  581. return 1;
  582. return 2;
  583. }
  584. inline void CompImageLoader::Load(size_t size, const ui8 * data)
  585. {
  586. while (size)
  587. {
  588. //Try to compress data
  589. while(true)
  590. {
  591. ui8 color = data[0];
  592. if (color != 0xff)
  593. {
  594. size_t runLength = 1;
  595. while (runLength < size && color == data[runLength])
  596. runLength++;
  597. if (runLength > 1 && runLength < 255)//Row of one color found - use RLE
  598. {
  599. Load(runLength, color);
  600. data += runLength;
  601. size -= runLength;
  602. if (!size)
  603. return;
  604. }
  605. else
  606. break;
  607. }
  608. else
  609. break;
  610. }
  611. //Select length for new raw entry
  612. size_t runLength = 1;
  613. ui8 color = data[0];
  614. ui8 type = typeOf(color);
  615. ui8 color2;
  616. ui8 type2;
  617. if (size > 1)
  618. {
  619. do
  620. {
  621. color2 = data[runLength];
  622. type2 = typeOf(color2);
  623. runLength++;
  624. }
  625. //While we have data of this type and different colors
  626. while ((runLength < size) && (type == type2) && ( (color2 != 0xff) || (color2 != color)));
  627. }
  628. size -= runLength;
  629. //add data to last entry
  630. if (entry && entry[0] == 0xff && type == typeOf(entry[2]))
  631. {
  632. size_t toCopy = std::min<size_t>(runLength, 255 - entry[1]);
  633. runLength -= toCopy;
  634. entry[1] += toCopy;
  635. memcpy(position, data, toCopy);
  636. data+=toCopy;
  637. position+=toCopy;
  638. }
  639. //Create new entries
  640. while (runLength > 255)
  641. {
  642. NewEntry(data, 255);
  643. runLength -= 255;
  644. }
  645. if (runLength)
  646. NewEntry(data, runLength);
  647. }
  648. }
  649. inline void CompImageLoader::Load(size_t size, ui8 color)
  650. {
  651. if (!size)
  652. return;
  653. if (color==0xff)
  654. {
  655. auto tmpbuf = new ui8[size];
  656. memset((void*)tmpbuf, color, size);
  657. Load(size, tmpbuf);
  658. delete [] tmpbuf;
  659. return;
  660. }
  661. //Current entry is RLE with same color as new block
  662. if (entry && entry[0] == color)
  663. {
  664. size_t toCopy = std::min<size_t>(size, 255 - entry[1]);
  665. size -= toCopy;
  666. entry[1] += toCopy;
  667. }
  668. //Create new entries
  669. while (size > 255)
  670. {
  671. NewEntry(color, 255);
  672. size -= 255;
  673. }
  674. if (size)
  675. NewEntry(color, size);
  676. }
  677. void CompImageLoader::EndLine()
  678. {
  679. currentLine++;
  680. image->line[currentLine] = position - image->surf;
  681. entry = nullptr;
  682. }
  683. CompImageLoader::~CompImageLoader()
  684. {
  685. if (!image->surf)
  686. return;
  687. ui8* newPtr = (ui8*)realloc((void*)image->surf, position - image->surf);
  688. if (newPtr)
  689. image->surf = newPtr;
  690. }
  691. /*************************************************************************
  692. * Classes for images, support loading from file and drawing on surface *
  693. *************************************************************************/
  694. IImage::IImage() = default;
  695. IImage::~IImage() = default;
  696. SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group, bool compressed)
  697. : surf(nullptr),
  698. margins(0, 0),
  699. fullSize(0, 0)
  700. {
  701. SDLImageLoader loader(this);
  702. data->loadFrame(frame, group, loader);
  703. }
  704. SDLImage::SDLImage(SDL_Surface * from, bool extraRef)
  705. : surf(nullptr),
  706. margins(0, 0),
  707. fullSize(0, 0)
  708. {
  709. surf = from;
  710. if (extraRef)
  711. surf->refcount++;
  712. fullSize.x = surf->w;
  713. fullSize.y = surf->h;
  714. }
  715. SDLImage::SDLImage(const JsonNode & conf)
  716. : surf(nullptr),
  717. margins(0, 0),
  718. fullSize(0, 0)
  719. {
  720. std::string filename = conf["file"].String();
  721. surf = BitmapHandler::loadBitmap(filename);
  722. if(surf == nullptr)
  723. return;
  724. const JsonNode & jsonMargins = conf["margins"];
  725. margins.x = jsonMargins["left"].Integer();
  726. margins.y = jsonMargins["top"].Integer();
  727. fullSize.x = conf["width"].Integer();
  728. fullSize.y = conf["height"].Integer();
  729. if(fullSize.x == 0)
  730. {
  731. fullSize.x = margins.x + surf->w + jsonMargins["right"].Integer();
  732. }
  733. if(fullSize.y == 0)
  734. {
  735. fullSize.y = margins.y + surf->h + jsonMargins["bottom"].Integer();
  736. }
  737. }
  738. SDLImage::SDLImage(std::string filename, bool compressed)
  739. : surf(nullptr),
  740. margins(0, 0),
  741. fullSize(0, 0)
  742. {
  743. surf = BitmapHandler::loadBitmap(filename);
  744. if (surf == nullptr)
  745. {
  746. logGlobal->error("Error: failed to load image %s", filename);
  747. return;
  748. }
  749. else
  750. {
  751. fullSize.x = surf->w;
  752. fullSize.y = surf->h;
  753. }
  754. if (compressed)
  755. {
  756. SDL_Surface *temp = surf;
  757. // add RLE flag
  758. if (surf->format->palette)
  759. {
  760. CSDL_Ext::setColorKey(temp,temp->format->palette->colors[0]);
  761. }
  762. SDL_SetSurfaceRLE(temp, SDL_RLEACCEL);
  763. // convert surface to enable RLE
  764. surf = SDL_ConvertSurface(temp, temp->format, temp->flags);
  765. SDL_FreeSurface(temp);
  766. }
  767. }
  768. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  769. {
  770. if(!surf)
  771. return;
  772. Rect destRect(posX, posY, surf->w, surf->h);
  773. draw(where, &destRect, src);
  774. }
  775. void SDLImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  776. {
  777. if (!surf)
  778. return;
  779. Rect sourceRect(0, 0, surf->w, surf->h);
  780. Point destShift(0, 0);
  781. if(src)
  782. {
  783. if(src->x < margins.x)
  784. destShift.x += margins.x - src->x;
  785. if(src->y < margins.y)
  786. destShift.y += margins.y - src->y;
  787. sourceRect = Rect(*src) & Rect(margins.x, margins.y, surf->w, surf->h);
  788. sourceRect -= margins;
  789. }
  790. else
  791. destShift = margins;
  792. Rect destRect(destShift.x, destShift.y, surf->w, surf->h);
  793. if(dest)
  794. {
  795. destRect.x += dest->x;
  796. destRect.y += dest->y;
  797. }
  798. if(surf->format->BitsPerPixel == 8)
  799. {
  800. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  801. }
  802. else
  803. {
  804. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  805. }
  806. }
  807. std::shared_ptr<IImage> SDLImage::scaleFast(float scale) const
  808. {
  809. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, surf->w * scale, surf->h * scale);
  810. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  811. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  812. else if(scaled->format && scaled->format->Amask)
  813. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  814. else
  815. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  816. SDLImage * ret = new SDLImage(scaled, false);
  817. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  818. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  819. ret->margins.x = (int) round((float)margins.x * scale);
  820. ret->margins.y = (int) round((float)margins.y * scale);
  821. return std::shared_ptr<IImage>(ret);
  822. }
  823. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  824. {
  825. SDL_SaveBMP(surf, path.string().c_str());
  826. }
  827. void SDLImage::playerColored(PlayerColor player)
  828. {
  829. graphics->blueToPlayersAdv(surf, player);
  830. }
  831. void SDLImage::setFlagColor(PlayerColor player)
  832. {
  833. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  834. CSDL_Ext::setPlayerColor(surf, player);
  835. }
  836. int SDLImage::width() const
  837. {
  838. return fullSize.x;
  839. }
  840. int SDLImage::height() const
  841. {
  842. return fullSize.y;
  843. }
  844. void SDLImage::horizontalFlip()
  845. {
  846. margins.y = fullSize.y - surf->h - margins.y;
  847. //todo: modify in-place
  848. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  849. SDL_FreeSurface(surf);
  850. surf = flipped;
  851. }
  852. void SDLImage::verticalFlip()
  853. {
  854. margins.x = fullSize.x - surf->w - margins.x;
  855. //todo: modify in-place
  856. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  857. SDL_FreeSurface(surf);
  858. surf = flipped;
  859. }
  860. void SDLImage::shiftPalette(int from, int howMany)
  861. {
  862. //works with at most 16 colors, if needed more -> increase values
  863. assert(howMany < 16);
  864. if(surf->format->palette)
  865. {
  866. SDL_Color palette[16];
  867. for(int i=0; i<howMany; ++i)
  868. {
  869. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  870. }
  871. SDL_SetColors(surf, palette, from, howMany);
  872. }
  873. }
  874. void SDLImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  875. {
  876. if(surf->format->palette)
  877. {
  878. SDL_SetColors(surf, const_cast<SDL_Color *>(borderPallete.data()), 5, 3);
  879. }
  880. }
  881. SDLImage::~SDLImage()
  882. {
  883. SDL_FreeSurface(surf);
  884. }
  885. CompImage::CompImage(const CDefFile *data, size_t frame, size_t group):
  886. surf(nullptr),
  887. line(nullptr),
  888. palette(nullptr)
  889. {
  890. CompImageLoader loader(this);
  891. data->loadFrame(frame, group, loader);
  892. }
  893. CompImage::CompImage(SDL_Surface * surf)
  894. {
  895. //TODO
  896. assert(0);
  897. }
  898. void CompImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  899. {
  900. Rect dest(posX,posY, width(), height());
  901. draw(where, &dest, src, alpha);
  902. }
  903. void CompImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  904. {
  905. int rotation = 0; //TODO
  906. //rotation & 2 = horizontal rotation
  907. //rotation & 4 = vertical rotation
  908. if (!surf)
  909. return;
  910. Rect sourceRect(sprite);
  911. //TODO: rotation and scaling
  912. if (src)
  913. sourceRect = sourceRect & *src;
  914. //Limit source rect to sizes of surface
  915. sourceRect = sourceRect & Rect(0, 0, where->w, where->h);
  916. //Starting point on SDL surface
  917. Point dst(sourceRect.x,sourceRect.y);
  918. if (dest)
  919. {
  920. dst.x += dest->x;
  921. dst.y += dest->y;
  922. }
  923. if (rotation & 2)
  924. dst.y += sourceRect.h;
  925. if (rotation & 4)
  926. dst.x += sourceRect.w;
  927. sourceRect -= sprite.topLeft();
  928. for (int currY = 0; currY <sourceRect.h; currY++)
  929. {
  930. ui8* data = surf + line[currY+sourceRect.y];
  931. ui8 type = *(data++);
  932. ui8 size = *(data++);
  933. int currX = sourceRect.x;
  934. //Skip blocks until starting position reached
  935. while ( currX > size )
  936. {
  937. currX -= size;
  938. if (type == 0xff)
  939. data += size;
  940. type = *(data++);
  941. size = *(data++);
  942. }
  943. //This block will be shown partially - calculate size\position
  944. size -= currX;
  945. if (type == 0xff)
  946. data += currX;
  947. currX = 0;
  948. ui8 bpp = where->format->BytesPerPixel;
  949. //Calculate position for blitting: pixels + Y + X
  950. ui8* blitPos = (ui8*) where->pixels;
  951. if (rotation & 4)
  952. blitPos += (dst.y - currY) * where->pitch;
  953. else
  954. blitPos += (dst.y + currY) * where->pitch;
  955. blitPos += dst.x * bpp;
  956. //Blit blocks that must be fully visible
  957. while (currX + size < sourceRect.w)
  958. {
  959. //blit block, pointers will be modified if needed
  960. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  961. currX += size;
  962. type = *(data++);
  963. size = *(data++);
  964. }
  965. //Blit last, semi-visible block
  966. size = sourceRect.w - currX;
  967. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  968. }
  969. }
  970. std::shared_ptr<IImage> CompImage::scaleFast(float scale) const
  971. {
  972. //todo: CompImage::scaleFast
  973. logAnim->error("CompImage::scaleFast is not implemented");
  974. return nullptr;
  975. }
  976. #define CASEBPP(x,y) case x: BlitBlock<x,y>(type, size, data, dest, alpha); break
  977. //FIXME: better way to get blitter
  978. void CompImage::BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const
  979. {
  980. assert(bpp>1 && bpp<5);
  981. if (rotated)
  982. switch (bpp)
  983. {
  984. CASEBPP(2,1);
  985. CASEBPP(3,1);
  986. CASEBPP(4,1);
  987. }
  988. else
  989. switch (bpp)
  990. {
  991. CASEBPP(2,1);
  992. CASEBPP(3,1);
  993. CASEBPP(4,1);
  994. }
  995. }
  996. #undef CASEBPP
  997. //Blit one block from RLE-d surface
  998. template<int bpp, int dir>
  999. void CompImage::BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const
  1000. {
  1001. //Raw data
  1002. if (type == 0xff)
  1003. {
  1004. ui8 color = *data;
  1005. if (alpha != 255)//Per-surface alpha is set
  1006. {
  1007. for (size_t i=0; i<size; i++)
  1008. {
  1009. SDL_Color col = palette[*(data++)];
  1010. col.a = (ui32)col.a*alpha/255;
  1011. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  1012. }
  1013. return;
  1014. }
  1015. if (palette[color].a == 255)
  1016. {
  1017. //Put row of RGB data
  1018. for (size_t i=0; i<size; i++)
  1019. ColorPutter<bpp, 1>::PutColor(dest, palette[*(data++)]);
  1020. }
  1021. else
  1022. {
  1023. //Put row of RGBA data
  1024. for (size_t i=0; i<size; i++)
  1025. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[*(data++)]);
  1026. }
  1027. }
  1028. //RLE-d sequence
  1029. else
  1030. {
  1031. if (alpha != 255 && palette[type].a !=0)//Per-surface alpha is set
  1032. {
  1033. SDL_Color col = palette[type];
  1034. col.a = (int)col.a*(255-alpha)/255;
  1035. for (size_t i=0; i<size; i++)
  1036. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  1037. return;
  1038. }
  1039. switch (palette[type].a)
  1040. {
  1041. case 0:
  1042. {
  1043. //Skip row
  1044. dest += size*bpp;
  1045. break;
  1046. }
  1047. case 255:
  1048. {
  1049. //Put RGB row
  1050. ColorPutter<bpp, 1>::PutColorRow(dest, palette[type], size);
  1051. break;
  1052. }
  1053. default:
  1054. {
  1055. //Put RGBA row
  1056. for (size_t i=0; i<size; i++)
  1057. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[type]);
  1058. break;
  1059. }
  1060. }
  1061. }
  1062. }
  1063. void CompImage::playerColored(PlayerColor player)
  1064. {
  1065. SDL_Color *pal = nullptr;
  1066. if(player < PlayerColor::PLAYER_LIMIT)
  1067. {
  1068. pal = graphics->playerColorPalette + 32*player.getNum();
  1069. }
  1070. else if(player == PlayerColor::NEUTRAL)
  1071. {
  1072. pal = graphics->neutralColorPalette;
  1073. }
  1074. else
  1075. assert(0);
  1076. for(int i=0; i<32; ++i)
  1077. {
  1078. CSDL_Ext::colorAssign(palette[224+i],pal[i]);
  1079. }
  1080. }
  1081. void CompImage::setFlagColor(PlayerColor player)
  1082. {
  1083. logAnim->error("CompImage::setFlagColor is not implemented");
  1084. }
  1085. int CompImage::width() const
  1086. {
  1087. return fullSize.x;
  1088. }
  1089. int CompImage::height() const
  1090. {
  1091. return fullSize.y;
  1092. }
  1093. CompImage::~CompImage()
  1094. {
  1095. free(surf);
  1096. delete [] line;
  1097. delete [] palette;
  1098. }
  1099. void CompImage::horizontalFlip()
  1100. {
  1101. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1102. }
  1103. void CompImage::verticalFlip()
  1104. {
  1105. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1106. }
  1107. void CompImage::shiftPalette(int from, int howMany)
  1108. {
  1109. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1110. }
  1111. void CompImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  1112. {
  1113. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1114. }
  1115. void CompImage::exportBitmap(const boost::filesystem::path & path) const
  1116. {
  1117. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1118. }
  1119. /*************************************************************************
  1120. * CAnimation for animations handling, can load part of file if needed *
  1121. *************************************************************************/
  1122. std::shared_ptr<IImage> CAnimation::getFromExtraDef(std::string filename)
  1123. {
  1124. size_t pos = filename.find(':');
  1125. if (pos == -1)
  1126. return nullptr;
  1127. CAnimation anim(filename.substr(0, pos));
  1128. pos++;
  1129. size_t frame = atoi(filename.c_str()+pos);
  1130. size_t group = 0;
  1131. pos = filename.find(':', pos);
  1132. if (pos != -1)
  1133. {
  1134. pos++;
  1135. group = frame;
  1136. frame = atoi(filename.c_str()+pos);
  1137. }
  1138. anim.load(frame ,group);
  1139. auto ret = anim.images[group][frame];
  1140. anim.images.clear();
  1141. return ret;
  1142. }
  1143. bool CAnimation::loadFrame(size_t frame, size_t group)
  1144. {
  1145. if(size(group) <= frame)
  1146. {
  1147. printError(frame, group, "LoadFrame");
  1148. return false;
  1149. }
  1150. auto image = getImage(frame, group, false);
  1151. if(image)
  1152. {
  1153. return true;
  1154. }
  1155. //try to get image from def
  1156. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  1157. {
  1158. if(defFile)
  1159. {
  1160. auto frameList = defFile->getEntries();
  1161. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  1162. {
  1163. if(compressed)
  1164. images[group][frame] = std::make_shared<CompImage>(defFile, frame, group);
  1165. else
  1166. images[group][frame] = std::make_shared<SDLImage>(defFile, frame, group);
  1167. return true;
  1168. }
  1169. }
  1170. // still here? image is missing
  1171. printError(frame, group, "LoadFrame");
  1172. images[group][frame] = std::make_shared<SDLImage>("DEFAULT", compressed);
  1173. }
  1174. else //load from separate file
  1175. {
  1176. auto img = getFromExtraDef(source[group][frame]["file"].String());
  1177. if(!img)
  1178. img = std::make_shared<SDLImage>(source[group][frame]);
  1179. images[group][frame] = img;
  1180. return true;
  1181. }
  1182. return false;
  1183. }
  1184. bool CAnimation::unloadFrame(size_t frame, size_t group)
  1185. {
  1186. auto image = getImage(frame, group, false);
  1187. if(image)
  1188. {
  1189. images[group].erase(frame);
  1190. if(images[group].empty())
  1191. images.erase(group);
  1192. return true;
  1193. }
  1194. return false;
  1195. }
  1196. void CAnimation::initFromJson(const JsonNode & config)
  1197. {
  1198. std::string basepath;
  1199. basepath = config["basepath"].String();
  1200. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  1201. base["margins"] = config["margins"];
  1202. base["width"] = config["width"];
  1203. base["height"] = config["height"];
  1204. for(const JsonNode & group : config["sequences"].Vector())
  1205. {
  1206. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  1207. source[groupID].clear();
  1208. for(const JsonNode & frame : group["frames"].Vector())
  1209. {
  1210. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  1211. JsonUtils::inherit(toAdd, base);
  1212. toAdd["file"].String() = basepath + frame.String();
  1213. source[groupID].push_back(toAdd);
  1214. }
  1215. }
  1216. for(const JsonNode & node : config["images"].Vector())
  1217. {
  1218. size_t group = node["group"].Integer();
  1219. size_t frame = node["frame"].Integer();
  1220. if (source[group].size() <= frame)
  1221. source[group].resize(frame+1);
  1222. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  1223. JsonUtils::inherit(toAdd, base);
  1224. toAdd["file"].String() = basepath + node["file"].String();
  1225. source[group][frame] = toAdd;
  1226. }
  1227. }
  1228. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  1229. {
  1230. if(images.empty())
  1231. {
  1232. logGlobal->error("Nothing to export, animation is empty");
  1233. return;
  1234. }
  1235. boost::filesystem::path actualPath = path / "SPRITES" / name;
  1236. boost::filesystem::create_directories(actualPath);
  1237. size_t counter = 0;
  1238. for(const auto & groupPair : images)
  1239. {
  1240. size_t group = groupPair.first;
  1241. for(const auto & imagePair : groupPair.second)
  1242. {
  1243. size_t frame = imagePair.first;
  1244. const auto img = imagePair.second;
  1245. boost::format fmt("%d_%d.bmp");
  1246. fmt % group % frame;
  1247. img->exportBitmap(actualPath / fmt.str());
  1248. counter++;
  1249. }
  1250. }
  1251. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  1252. }
  1253. void CAnimation::init()
  1254. {
  1255. if(defFile)
  1256. {
  1257. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  1258. for (auto & defEntry : defEntries)
  1259. source[defEntry.first].resize(defEntry.second);
  1260. }
  1261. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  1262. if (vstd::contains(graphics->imageLists, resID.getName()))
  1263. initFromJson(graphics->imageLists[resID.getName()]);
  1264. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  1265. for(auto & loader : configList)
  1266. {
  1267. auto stream = loader->load(resID);
  1268. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  1269. stream->read(textData.get(), stream->getSize());
  1270. const JsonNode config((char*)textData.get(), stream->getSize());
  1271. initFromJson(config);
  1272. }
  1273. }
  1274. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  1275. {
  1276. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  1277. }
  1278. CAnimation::CAnimation(std::string Name, bool Compressed):
  1279. name(Name),
  1280. compressed(Compressed),
  1281. preloaded(false),
  1282. defFile(nullptr)
  1283. {
  1284. size_t dotPos = name.find_last_of('.');
  1285. if ( dotPos!=-1 )
  1286. name.erase(dotPos);
  1287. std::transform(name.begin(), name.end(), name.begin(), toupper);
  1288. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  1289. if(CResourceHandler::get()->existsResource(resource))
  1290. defFile = new CDefFile(name);
  1291. init();
  1292. if(source.empty())
  1293. logAnim->error("Animation %s failed to load", Name);
  1294. }
  1295. CAnimation::CAnimation():
  1296. name(""),
  1297. compressed(false),
  1298. preloaded(false),
  1299. defFile(nullptr)
  1300. {
  1301. init();
  1302. }
  1303. CAnimation::~CAnimation()
  1304. {
  1305. if(defFile)
  1306. delete defFile;
  1307. }
  1308. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  1309. {
  1310. //todo: clone actual loaded Image object
  1311. JsonNode clone(source[sourceGroup][sourceFrame]);
  1312. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  1313. {
  1314. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  1315. clone["file"].String() = temp;
  1316. }
  1317. source[targetGroup].push_back(clone);
  1318. size_t index = source[targetGroup].size() - 1;
  1319. if(preloaded)
  1320. load(index, targetGroup);
  1321. }
  1322. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  1323. {
  1324. if (source[group].size() <= frame)
  1325. source[group].resize(frame+1);
  1326. source[group][frame]["file"].String() = filename;
  1327. //FIXME: update image if already loaded
  1328. }
  1329. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  1330. {
  1331. auto groupIter = images.find(group);
  1332. if (groupIter != images.end())
  1333. {
  1334. auto imageIter = groupIter->second.find(frame);
  1335. if (imageIter != groupIter->second.end())
  1336. return imageIter->second;
  1337. }
  1338. if (verbose)
  1339. printError(frame, group, "GetImage");
  1340. return nullptr;
  1341. }
  1342. void CAnimation::load()
  1343. {
  1344. for (auto & elem : source)
  1345. for (size_t image=0; image < elem.second.size(); image++)
  1346. loadFrame(image, elem.first);
  1347. }
  1348. void CAnimation::unload()
  1349. {
  1350. for (auto & elem : source)
  1351. for (size_t image=0; image < elem.second.size(); image++)
  1352. unloadFrame(image, elem.first);
  1353. }
  1354. void CAnimation::preload()
  1355. {
  1356. if(!preloaded)
  1357. {
  1358. preloaded = true;
  1359. load();
  1360. }
  1361. }
  1362. void CAnimation::loadGroup(size_t group)
  1363. {
  1364. if (vstd::contains(source, group))
  1365. for (size_t image=0; image < source[group].size(); image++)
  1366. loadFrame(image, group);
  1367. }
  1368. void CAnimation::unloadGroup(size_t group)
  1369. {
  1370. if (vstd::contains(source, group))
  1371. for (size_t image=0; image < source[group].size(); image++)
  1372. unloadFrame(image, group);
  1373. }
  1374. void CAnimation::load(size_t frame, size_t group)
  1375. {
  1376. loadFrame(frame, group);
  1377. }
  1378. void CAnimation::unload(size_t frame, size_t group)
  1379. {
  1380. unloadFrame(frame, group);
  1381. }
  1382. size_t CAnimation::size(size_t group) const
  1383. {
  1384. auto iter = source.find(group);
  1385. if (iter != source.end())
  1386. return iter->second.size();
  1387. return 0;
  1388. }
  1389. void CAnimation::horizontalFlip()
  1390. {
  1391. for(auto & group : images)
  1392. for(auto & image : group.second)
  1393. image.second->horizontalFlip();
  1394. }
  1395. void CAnimation::verticalFlip()
  1396. {
  1397. for(auto & group : images)
  1398. for(auto & image : group.second)
  1399. image.second->verticalFlip();
  1400. }
  1401. void CAnimation::playerColored(PlayerColor player)
  1402. {
  1403. for(auto & group : images)
  1404. for(auto & image : group.second)
  1405. image.second->playerColored(player);
  1406. }
  1407. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  1408. {
  1409. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  1410. {
  1411. duplicateImage(sourceGroup, frame, targetGroup);
  1412. auto image = getImage(frame, targetGroup);
  1413. image->verticalFlip();
  1414. }
  1415. }
  1416. float CFadeAnimation::initialCounter() const
  1417. {
  1418. if (fadingMode == EMode::OUT)
  1419. return 1.0f;
  1420. return 0.0f;
  1421. }
  1422. void CFadeAnimation::update()
  1423. {
  1424. if (!fading)
  1425. return;
  1426. if (fadingMode == EMode::OUT)
  1427. fadingCounter -= delta;
  1428. else
  1429. fadingCounter += delta;
  1430. if (isFinished())
  1431. {
  1432. fading = false;
  1433. if (shouldFreeSurface)
  1434. {
  1435. SDL_FreeSurface(fadingSurface);
  1436. fadingSurface = nullptr;
  1437. }
  1438. }
  1439. }
  1440. bool CFadeAnimation::isFinished() const
  1441. {
  1442. if (fadingMode == EMode::OUT)
  1443. return fadingCounter <= 0.0f;
  1444. return fadingCounter >= 1.0f;
  1445. }
  1446. CFadeAnimation::CFadeAnimation()
  1447. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  1448. fadingMode(EMode::NONE)
  1449. {
  1450. }
  1451. CFadeAnimation::~CFadeAnimation()
  1452. {
  1453. if (fadingSurface && shouldFreeSurface)
  1454. SDL_FreeSurface(fadingSurface);
  1455. }
  1456. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  1457. {
  1458. if (fading)
  1459. {
  1460. // in that case, immediately finish the previous fade
  1461. // (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))
  1462. logGlobal->warn("Tried to init fading animation that is already running.");
  1463. if (fadingSurface && shouldFreeSurface)
  1464. SDL_FreeSurface(fadingSurface);
  1465. }
  1466. if (animDelta <= 0.0f)
  1467. {
  1468. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  1469. animDelta = DEFAULT_DELTA;
  1470. }
  1471. if (sourceSurface)
  1472. fadingSurface = sourceSurface;
  1473. delta = animDelta;
  1474. fadingMode = mode;
  1475. fadingCounter = initialCounter();
  1476. fading = true;
  1477. shouldFreeSurface = freeSurfaceAtEnd;
  1478. }
  1479. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1480. {
  1481. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1482. {
  1483. fading = false;
  1484. return;
  1485. }
  1486. CSDL_Ext::setAlpha(fadingSurface, fadingCounter * 255);
  1487. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1488. CSDL_Ext::setAlpha(fadingSurface, 255);
  1489. }