CAnimation.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775
  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::unique_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::unique_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. ui32 BaseOffset = sizeof(SSpriteDef);
  364. loader.init(Point(sprite.width, sprite.height),
  365. Point(sprite.leftMargin, sprite.topMargin),
  366. Point(sprite.fullWidth, sprite.fullHeight), palette.get());
  367. switch (sprite.format)
  368. {
  369. case 0:
  370. {
  371. //pixel data is not compressed, copy data to surface
  372. for (ui32 i=0; i<sprite.height; i++)
  373. {
  374. loader.Load(sprite.width, FDef + currentOffset);
  375. currentOffset += sprite.width;
  376. loader.EndLine();
  377. }
  378. break;
  379. }
  380. case 1:
  381. {
  382. //for each line we have offset of pixel data
  383. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  384. currentOffset += sizeof(ui32) * sprite.height;
  385. for (ui32 i=0; i<sprite.height; i++)
  386. {
  387. //get position of the line
  388. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  389. ui32 TotalRowLength = 0;
  390. while (TotalRowLength<sprite.width)
  391. {
  392. ui8 type=FDef[currentOffset++];
  393. ui32 length=FDef[currentOffset++] + 1;
  394. if (type==0xFF)//Raw data
  395. {
  396. loader.Load(length, FDef + currentOffset);
  397. currentOffset+=length;
  398. }
  399. else// RLE
  400. {
  401. loader.Load(length, type);
  402. }
  403. TotalRowLength += length;
  404. }
  405. loader.EndLine();
  406. }
  407. break;
  408. }
  409. case 2:
  410. {
  411. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  412. for (ui32 i=0; i<sprite.height; i++)
  413. {
  414. ui32 TotalRowLength=0;
  415. while (TotalRowLength<sprite.width)
  416. {
  417. ui8 SegmentType=FDef[currentOffset++];
  418. ui8 code = SegmentType / 32;
  419. ui8 length = (SegmentType & 31) + 1;
  420. if (code==7)//Raw data
  421. {
  422. loader.Load(length, FDef + currentOffset);
  423. currentOffset += length;
  424. }
  425. else//RLE
  426. {
  427. loader.Load(length, code);
  428. }
  429. TotalRowLength+=length;
  430. }
  431. loader.EndLine();
  432. }
  433. break;
  434. }
  435. case 3:
  436. {
  437. for (ui32 i=0; i<sprite.height; i++)
  438. {
  439. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  440. ui32 TotalRowLength=0;
  441. while (TotalRowLength<sprite.width)
  442. {
  443. ui8 segment = FDef[currentOffset++];
  444. ui8 code = segment / 32;
  445. ui8 length = (segment & 31) + 1;
  446. if (code==7)//Raw data
  447. {
  448. loader.Load(length, FDef + currentOffset);
  449. currentOffset += length;
  450. }
  451. else//RLE
  452. {
  453. loader.Load(length, code);
  454. }
  455. TotalRowLength += length;
  456. }
  457. loader.EndLine();
  458. }
  459. break;
  460. }
  461. default:
  462. logGlobal->error("Error: unsupported format of def file: %d", sprite.format);
  463. break;
  464. }
  465. }
  466. CDefFile::~CDefFile() = default;
  467. const std::map<size_t, size_t > CDefFile::getEntries() const
  468. {
  469. std::map<size_t, size_t > ret;
  470. for (auto & elem : offset)
  471. ret[elem.first] = elem.second.size();
  472. return ret;
  473. }
  474. /*************************************************************************
  475. * Classes for image loaders - helpers for loading from def files *
  476. *************************************************************************/
  477. SDLImageLoader::SDLImageLoader(SDLImage * Img):
  478. image(Img),
  479. lineStart(nullptr),
  480. position(nullptr)
  481. {
  482. }
  483. void SDLImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  484. {
  485. //Init image
  486. image->surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SpriteSize.x, SpriteSize.y, 8, 0, 0, 0, 0);
  487. image->margins = Margins;
  488. image->fullSize = FullSize;
  489. //Prepare surface
  490. SDL_Palette * p = SDL_AllocPalette(256);
  491. SDL_SetPaletteColors(p, pal, 0, 256);
  492. SDL_SetSurfacePalette(image->surf, p);
  493. SDL_FreePalette(p);
  494. SDL_LockSurface(image->surf);
  495. lineStart = position = (ui8*)image->surf->pixels;
  496. }
  497. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  498. {
  499. if (size)
  500. {
  501. memcpy((void *)position, data, size);
  502. position += size;
  503. }
  504. }
  505. inline void SDLImageLoader::Load(size_t size, ui8 color)
  506. {
  507. if (size)
  508. {
  509. memset((void *)position, color, size);
  510. position += size;
  511. }
  512. }
  513. inline void SDLImageLoader::EndLine()
  514. {
  515. lineStart += image->surf->pitch;
  516. position = lineStart;
  517. }
  518. SDLImageLoader::~SDLImageLoader()
  519. {
  520. SDL_UnlockSurface(image->surf);
  521. SDL_SetColorKey(image->surf, SDL_TRUE, 0);
  522. //TODO: RLE if compressed and bpp>1
  523. }
  524. ////////////////////////////////////////////////////////////////////////////////
  525. CompImageLoader::CompImageLoader(CompImage * Img):
  526. image(Img),
  527. position(nullptr),
  528. entry(nullptr),
  529. currentLine(0)
  530. {
  531. }
  532. void CompImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  533. {
  534. image->sprite = Rect(Margins, SpriteSize);
  535. image->fullSize = FullSize;
  536. if (SpriteSize.x && SpriteSize.y)
  537. {
  538. image->palette = new SDL_Color[256];
  539. memcpy((void*)image->palette, (void*)pal, 256*sizeof(SDL_Color));
  540. //Allocate enought space for worst possible case, c-style malloc used due to resizing after load
  541. image->surf = (ui8*)malloc(SpriteSize.x*SpriteSize.y*3);
  542. image->line = new ui32[SpriteSize.y+1];
  543. image->line[0] = 0;
  544. position = image->surf;
  545. }
  546. }
  547. inline void CompImageLoader::NewEntry(ui8 color, size_t size)
  548. {
  549. assert(color != 0xff);
  550. assert(size && size<256);
  551. entry = position;
  552. entry[0] = color;
  553. entry[1] = size;
  554. position +=2;
  555. }
  556. inline void CompImageLoader::NewEntry(const ui8 * &data, size_t size)
  557. {
  558. assert(size && size<256);
  559. entry = position;
  560. entry[0] = 0xff;
  561. entry[1] = size;
  562. position +=2;
  563. memcpy(position, data, size);
  564. position+=size;
  565. data+=size;
  566. }
  567. inline ui8 CompImageLoader::typeOf(ui8 color)
  568. {
  569. if (color == 0)
  570. return 0;
  571. if (image->palette[color].a != 255)
  572. return 1;
  573. return 2;
  574. }
  575. inline void CompImageLoader::Load(size_t size, const ui8 * data)
  576. {
  577. while (size)
  578. {
  579. //Try to compress data
  580. while(true)
  581. {
  582. ui8 color = data[0];
  583. if (color != 0xff)
  584. {
  585. size_t runLength = 1;
  586. while (runLength < size && color == data[runLength])
  587. runLength++;
  588. if (runLength > 1 && runLength < 255)//Row of one color found - use RLE
  589. {
  590. Load(runLength, color);
  591. data += runLength;
  592. size -= runLength;
  593. if (!size)
  594. return;
  595. }
  596. else
  597. break;
  598. }
  599. else
  600. break;
  601. }
  602. //Select length for new raw entry
  603. size_t runLength = 1;
  604. ui8 color = data[0];
  605. ui8 type = typeOf(color);
  606. ui8 color2;
  607. ui8 type2;
  608. if (size > 1)
  609. {
  610. do
  611. {
  612. color2 = data[runLength];
  613. type2 = typeOf(color2);
  614. runLength++;
  615. }
  616. //While we have data of this type and different colors
  617. while ((runLength < size) && (type == type2) && ( (color2 != 0xff) || (color2 != color)));
  618. }
  619. size -= runLength;
  620. //add data to last entry
  621. if (entry && entry[0] == 0xff && type == typeOf(entry[2]))
  622. {
  623. size_t toCopy = std::min<size_t>(runLength, 255 - entry[1]);
  624. runLength -= toCopy;
  625. entry[1] += toCopy;
  626. memcpy(position, data, toCopy);
  627. data+=toCopy;
  628. position+=toCopy;
  629. }
  630. //Create new entries
  631. while (runLength > 255)
  632. {
  633. NewEntry(data, 255);
  634. runLength -= 255;
  635. }
  636. if (runLength)
  637. NewEntry(data, runLength);
  638. }
  639. }
  640. inline void CompImageLoader::Load(size_t size, ui8 color)
  641. {
  642. if (!size)
  643. return;
  644. if (color==0xff)
  645. {
  646. auto tmpbuf = new ui8[size];
  647. memset((void*)tmpbuf, color, size);
  648. Load(size, tmpbuf);
  649. delete [] tmpbuf;
  650. return;
  651. }
  652. //Current entry is RLE with same color as new block
  653. if (entry && entry[0] == color)
  654. {
  655. size_t toCopy = std::min<size_t>(size, 255 - entry[1]);
  656. size -= toCopy;
  657. entry[1] += toCopy;
  658. }
  659. //Create new entries
  660. while (size > 255)
  661. {
  662. NewEntry(color, 255);
  663. size -= 255;
  664. }
  665. if (size)
  666. NewEntry(color, size);
  667. }
  668. void CompImageLoader::EndLine()
  669. {
  670. currentLine++;
  671. image->line[currentLine] = position - image->surf;
  672. entry = nullptr;
  673. }
  674. CompImageLoader::~CompImageLoader()
  675. {
  676. if (!image->surf)
  677. return;
  678. ui8* newPtr = (ui8*)realloc((void*)image->surf, position - image->surf);
  679. if (newPtr)
  680. image->surf = newPtr;
  681. }
  682. /*************************************************************************
  683. * Classes for images, support loading from file and drawing on surface *
  684. *************************************************************************/
  685. IImage::IImage():
  686. refCount(1)
  687. {
  688. }
  689. bool IImage::decreaseRef()
  690. {
  691. refCount--;
  692. return refCount <= 0;
  693. }
  694. void IImage::increaseRef()
  695. {
  696. refCount++;
  697. }
  698. SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group, bool compressed)
  699. : surf(nullptr),
  700. margins(0, 0),
  701. fullSize(0, 0)
  702. {
  703. SDLImageLoader loader(this);
  704. data->loadFrame(frame, group, loader);
  705. }
  706. SDLImage::SDLImage(SDL_Surface * from, bool extraRef)
  707. : surf(nullptr),
  708. margins(0, 0),
  709. fullSize(0, 0)
  710. {
  711. surf = from;
  712. if (extraRef)
  713. surf->refcount++;
  714. fullSize.x = surf->w;
  715. fullSize.y = surf->h;
  716. }
  717. SDLImage::SDLImage(const JsonNode & conf)
  718. : surf(nullptr),
  719. margins(0, 0),
  720. fullSize(0, 0)
  721. {
  722. std::string filename = conf["file"].String();
  723. surf = BitmapHandler::loadBitmap(filename);
  724. if(surf == nullptr)
  725. return;
  726. const JsonNode & jsonMargins = conf["margins"];
  727. margins.x = jsonMargins["left"].Integer();
  728. margins.y = jsonMargins["top"].Integer();
  729. fullSize.x = conf["width"].Integer();
  730. fullSize.y = conf["height"].Integer();
  731. if(fullSize.x == 0)
  732. {
  733. fullSize.x = margins.x + surf->w + jsonMargins["right"].Integer();
  734. }
  735. if(fullSize.y == 0)
  736. {
  737. fullSize.y = margins.y + surf->h + jsonMargins["bottom"].Integer();
  738. }
  739. }
  740. SDLImage::SDLImage(std::string filename, bool compressed)
  741. : surf(nullptr),
  742. margins(0, 0),
  743. fullSize(0, 0)
  744. {
  745. surf = BitmapHandler::loadBitmap(filename);
  746. if (surf == nullptr)
  747. {
  748. logGlobal->error("Error: failed to load image %s", filename);
  749. return;
  750. }
  751. else
  752. {
  753. fullSize.x = surf->w;
  754. fullSize.y = surf->h;
  755. }
  756. if (compressed)
  757. {
  758. SDL_Surface *temp = surf;
  759. // add RLE flag
  760. if (surf->format->palette)
  761. {
  762. CSDL_Ext::setColorKey(temp,temp->format->palette->colors[0]);
  763. }
  764. SDL_SetSurfaceRLE(temp, SDL_RLEACCEL);
  765. // convert surface to enable RLE
  766. surf = SDL_ConvertSurface(temp, temp->format, temp->flags);
  767. SDL_FreeSurface(temp);
  768. }
  769. }
  770. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  771. {
  772. if(!surf)
  773. return;
  774. Rect destRect(posX, posY, surf->w, surf->h);
  775. draw(where, &destRect, src);
  776. }
  777. void SDLImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  778. {
  779. if (!surf)
  780. return;
  781. Rect sourceRect(0, 0, surf->w, surf->h);
  782. Point destShift(0, 0);
  783. if(src)
  784. {
  785. if(src->x < margins.x)
  786. destShift.x += margins.x - src->x;
  787. if(src->y < margins.y)
  788. destShift.y += margins.y - src->y;
  789. sourceRect = Rect(*src) & Rect(margins.x, margins.y, surf->w, surf->h);
  790. sourceRect -= margins;
  791. }
  792. else
  793. destShift = margins;
  794. Rect destRect(destShift.x, destShift.y, surf->w, surf->h);
  795. if(dest)
  796. {
  797. destRect.x += dest->x;
  798. destRect.y += dest->y;
  799. }
  800. if(surf->format->BitsPerPixel == 8)
  801. {
  802. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  803. }
  804. else
  805. {
  806. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  807. }
  808. }
  809. std::unique_ptr<IImage> SDLImage::scaleFast(float scale) const
  810. {
  811. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, surf->w * scale, surf->h * scale);
  812. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  813. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  814. else if(scaled->format && scaled->format->Amask)
  815. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  816. else
  817. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  818. SDLImage * ret = new SDLImage(scaled, false);
  819. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  820. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  821. ret->margins.x = (int) round((float)margins.x * scale);
  822. ret->margins.y = (int) round((float)margins.y * scale);
  823. return std::unique_ptr<IImage>(ret);
  824. }
  825. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  826. {
  827. SDL_SaveBMP(surf, path.string().c_str());
  828. }
  829. void SDLImage::playerColored(PlayerColor player)
  830. {
  831. graphics->blueToPlayersAdv(surf, player);
  832. }
  833. void SDLImage::setFlagColor(PlayerColor player)
  834. {
  835. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  836. CSDL_Ext::setPlayerColor(surf, player);
  837. }
  838. int SDLImage::width() const
  839. {
  840. return fullSize.x;
  841. }
  842. int SDLImage::height() const
  843. {
  844. return fullSize.y;
  845. }
  846. void SDLImage::horizontalFlip()
  847. {
  848. margins.y = fullSize.y - surf->h - margins.y;
  849. //todo: modify in-place
  850. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  851. SDL_FreeSurface(surf);
  852. surf = flipped;
  853. }
  854. void SDLImage::verticalFlip()
  855. {
  856. margins.x = fullSize.x - surf->w - margins.x;
  857. //todo: modify in-place
  858. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  859. SDL_FreeSurface(surf);
  860. surf = flipped;
  861. }
  862. void SDLImage::shiftPalette(int from, int howMany)
  863. {
  864. //works with at most 16 colors, if needed more -> increase values
  865. assert(howMany < 16);
  866. if(surf->format->palette)
  867. {
  868. SDL_Color palette[16];
  869. for(int i=0; i<howMany; ++i)
  870. {
  871. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  872. }
  873. SDL_SetColors(surf, palette, from, howMany);
  874. }
  875. }
  876. void SDLImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  877. {
  878. if(surf->format->palette)
  879. {
  880. SDL_SetColors(surf, const_cast<SDL_Color *>(borderPallete.data()), 5, 3);
  881. }
  882. }
  883. SDLImage::~SDLImage()
  884. {
  885. SDL_FreeSurface(surf);
  886. }
  887. CompImage::CompImage(const CDefFile *data, size_t frame, size_t group):
  888. surf(nullptr),
  889. line(nullptr),
  890. palette(nullptr)
  891. {
  892. CompImageLoader loader(this);
  893. data->loadFrame(frame, group, loader);
  894. }
  895. CompImage::CompImage(SDL_Surface * surf)
  896. {
  897. //TODO
  898. assert(0);
  899. }
  900. void CompImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  901. {
  902. Rect dest(posX,posY, width(), height());
  903. draw(where, &dest, src, alpha);
  904. }
  905. void CompImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  906. {
  907. int rotation = 0; //TODO
  908. //rotation & 2 = horizontal rotation
  909. //rotation & 4 = vertical rotation
  910. if (!surf)
  911. return;
  912. Rect sourceRect(sprite);
  913. //TODO: rotation and scaling
  914. if (src)
  915. sourceRect = sourceRect & *src;
  916. //Limit source rect to sizes of surface
  917. sourceRect = sourceRect & Rect(0, 0, where->w, where->h);
  918. //Starting point on SDL surface
  919. Point dst(sourceRect.x,sourceRect.y);
  920. if (dest)
  921. {
  922. dst.x += dest->x;
  923. dst.y += dest->y;
  924. }
  925. if (rotation & 2)
  926. dst.y += sourceRect.h;
  927. if (rotation & 4)
  928. dst.x += sourceRect.w;
  929. sourceRect -= sprite.topLeft();
  930. for (int currY = 0; currY <sourceRect.h; currY++)
  931. {
  932. ui8* data = surf + line[currY+sourceRect.y];
  933. ui8 type = *(data++);
  934. ui8 size = *(data++);
  935. int currX = sourceRect.x;
  936. //Skip blocks until starting position reached
  937. while ( currX > size )
  938. {
  939. currX -= size;
  940. if (type == 0xff)
  941. data += size;
  942. type = *(data++);
  943. size = *(data++);
  944. }
  945. //This block will be shown partially - calculate size\position
  946. size -= currX;
  947. if (type == 0xff)
  948. data += currX;
  949. currX = 0;
  950. ui8 bpp = where->format->BytesPerPixel;
  951. //Calculate position for blitting: pixels + Y + X
  952. ui8* blitPos = (ui8*) where->pixels;
  953. if (rotation & 4)
  954. blitPos += (dst.y - currY) * where->pitch;
  955. else
  956. blitPos += (dst.y + currY) * where->pitch;
  957. blitPos += dst.x * bpp;
  958. //Blit blocks that must be fully visible
  959. while (currX + size < sourceRect.w)
  960. {
  961. //blit block, pointers will be modified if needed
  962. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  963. currX += size;
  964. type = *(data++);
  965. size = *(data++);
  966. }
  967. //Blit last, semi-visible block
  968. size = sourceRect.w - currX;
  969. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  970. }
  971. }
  972. std::unique_ptr<IImage> CompImage::scaleFast(float scale) const
  973. {
  974. //todo: CompImage::scaleFast
  975. logAnim->error("CompImage::scaleFast is not implemented");
  976. return nullptr;
  977. }
  978. #define CASEBPP(x,y) case x: BlitBlock<x,y>(type, size, data, dest, alpha); break
  979. //FIXME: better way to get blitter
  980. void CompImage::BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const
  981. {
  982. assert(bpp>1 && bpp<5);
  983. if (rotated)
  984. switch (bpp)
  985. {
  986. CASEBPP(2,1);
  987. CASEBPP(3,1);
  988. CASEBPP(4,1);
  989. }
  990. else
  991. switch (bpp)
  992. {
  993. CASEBPP(2,1);
  994. CASEBPP(3,1);
  995. CASEBPP(4,1);
  996. }
  997. }
  998. #undef CASEBPP
  999. //Blit one block from RLE-d surface
  1000. template<int bpp, int dir>
  1001. void CompImage::BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const
  1002. {
  1003. //Raw data
  1004. if (type == 0xff)
  1005. {
  1006. ui8 color = *data;
  1007. if (alpha != 255)//Per-surface alpha is set
  1008. {
  1009. for (size_t i=0; i<size; i++)
  1010. {
  1011. SDL_Color col = palette[*(data++)];
  1012. col.a = (ui32)col.a*alpha/255;
  1013. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  1014. }
  1015. return;
  1016. }
  1017. if (palette[color].a == 255)
  1018. {
  1019. //Put row of RGB data
  1020. for (size_t i=0; i<size; i++)
  1021. ColorPutter<bpp, 1>::PutColor(dest, palette[*(data++)]);
  1022. }
  1023. else
  1024. {
  1025. //Put row of RGBA data
  1026. for (size_t i=0; i<size; i++)
  1027. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[*(data++)]);
  1028. }
  1029. }
  1030. //RLE-d sequence
  1031. else
  1032. {
  1033. if (alpha != 255 && palette[type].a !=0)//Per-surface alpha is set
  1034. {
  1035. SDL_Color col = palette[type];
  1036. col.a = (int)col.a*(255-alpha)/255;
  1037. for (size_t i=0; i<size; i++)
  1038. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  1039. return;
  1040. }
  1041. switch (palette[type].a)
  1042. {
  1043. case 0:
  1044. {
  1045. //Skip row
  1046. dest += size*bpp;
  1047. break;
  1048. }
  1049. case 255:
  1050. {
  1051. //Put RGB row
  1052. ColorPutter<bpp, 1>::PutColorRow(dest, palette[type], size);
  1053. break;
  1054. }
  1055. default:
  1056. {
  1057. //Put RGBA row
  1058. for (size_t i=0; i<size; i++)
  1059. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[type]);
  1060. break;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. void CompImage::playerColored(PlayerColor player)
  1066. {
  1067. SDL_Color *pal = nullptr;
  1068. if(player < PlayerColor::PLAYER_LIMIT)
  1069. {
  1070. pal = graphics->playerColorPalette + 32*player.getNum();
  1071. }
  1072. else if(player == PlayerColor::NEUTRAL)
  1073. {
  1074. pal = graphics->neutralColorPalette;
  1075. }
  1076. else
  1077. assert(0);
  1078. for(int i=0; i<32; ++i)
  1079. {
  1080. CSDL_Ext::colorAssign(palette[224+i],pal[i]);
  1081. }
  1082. }
  1083. void CompImage::setFlagColor(PlayerColor player)
  1084. {
  1085. logAnim->error("CompImage::setFlagColor is not implemented");
  1086. }
  1087. int CompImage::width() const
  1088. {
  1089. return fullSize.x;
  1090. }
  1091. int CompImage::height() const
  1092. {
  1093. return fullSize.y;
  1094. }
  1095. CompImage::~CompImage()
  1096. {
  1097. free(surf);
  1098. delete [] line;
  1099. delete [] palette;
  1100. }
  1101. void CompImage::horizontalFlip()
  1102. {
  1103. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1104. }
  1105. void CompImage::verticalFlip()
  1106. {
  1107. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1108. }
  1109. void CompImage::shiftPalette(int from, int howMany)
  1110. {
  1111. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1112. }
  1113. void CompImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  1114. {
  1115. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1116. }
  1117. void CompImage::exportBitmap(const boost::filesystem::path & path) const
  1118. {
  1119. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1120. }
  1121. /*************************************************************************
  1122. * CAnimation for animations handling, can load part of file if needed *
  1123. *************************************************************************/
  1124. IImage * CAnimation::getFromExtraDef(std::string filename)
  1125. {
  1126. size_t pos = filename.find(':');
  1127. if (pos == -1)
  1128. return nullptr;
  1129. CAnimation anim(filename.substr(0, pos));
  1130. pos++;
  1131. size_t frame = atoi(filename.c_str()+pos);
  1132. size_t group = 0;
  1133. pos = filename.find(':', pos);
  1134. if (pos != -1)
  1135. {
  1136. pos++;
  1137. group = frame;
  1138. frame = atoi(filename.c_str()+pos);
  1139. }
  1140. anim.load(frame ,group);
  1141. IImage * ret = anim.images[group][frame];
  1142. anim.images.clear();
  1143. return ret;
  1144. }
  1145. bool CAnimation::loadFrame(size_t frame, size_t group)
  1146. {
  1147. if(size(group) <= frame)
  1148. {
  1149. printError(frame, group, "LoadFrame");
  1150. return false;
  1151. }
  1152. IImage * image = getImage(frame, group, false);
  1153. if(image)
  1154. {
  1155. image->increaseRef();
  1156. return true;
  1157. }
  1158. //try to get image from def
  1159. if(source[group][frame].getType() == JsonNode::DATA_NULL)
  1160. {
  1161. if(defFile)
  1162. {
  1163. auto frameList = defFile->getEntries();
  1164. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  1165. {
  1166. if(compressed)
  1167. images[group][frame] = new CompImage(defFile, frame, group);
  1168. else
  1169. images[group][frame] = new SDLImage(defFile, frame, group);
  1170. return true;
  1171. }
  1172. }
  1173. // still here? image is missing
  1174. printError(frame, group, "LoadFrame");
  1175. images[group][frame] = new SDLImage("DEFAULT", compressed);
  1176. }
  1177. else //load from separate file
  1178. {
  1179. IImage * img = getFromExtraDef(source[group][frame]["file"].String());
  1180. if(!img)
  1181. img = new SDLImage(source[group][frame]);
  1182. images[group][frame] = img;
  1183. return true;
  1184. }
  1185. return false;
  1186. }
  1187. bool CAnimation::unloadFrame(size_t frame, size_t group)
  1188. {
  1189. IImage *image = getImage(frame, group, false);
  1190. if (image)
  1191. {
  1192. //decrease ref count for image and delete if needed
  1193. if (image->decreaseRef())
  1194. {
  1195. delete image;
  1196. images[group].erase(frame);
  1197. }
  1198. if (images[group].empty())
  1199. images.erase(group);
  1200. return true;
  1201. }
  1202. return false;
  1203. }
  1204. void CAnimation::initFromJson(const JsonNode & config)
  1205. {
  1206. std::string basepath;
  1207. basepath = config["basepath"].String();
  1208. JsonNode base(JsonNode::DATA_STRUCT);
  1209. base["margins"] = config["margins"];
  1210. base["width"] = config["width"];
  1211. base["height"] = config["height"];
  1212. for(const JsonNode & group : config["sequences"].Vector())
  1213. {
  1214. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  1215. source[groupID].clear();
  1216. for(const JsonNode & frame : group["frames"].Vector())
  1217. {
  1218. JsonNode toAdd(JsonNode::DATA_STRUCT);
  1219. JsonUtils::inherit(toAdd, base);
  1220. toAdd["file"].String() = basepath + frame.String();
  1221. source[groupID].push_back(toAdd);
  1222. }
  1223. }
  1224. for(const JsonNode & node : config["images"].Vector())
  1225. {
  1226. size_t group = node["group"].Integer();
  1227. size_t frame = node["frame"].Integer();
  1228. if (source[group].size() <= frame)
  1229. source[group].resize(frame+1);
  1230. JsonNode toAdd(JsonNode::DATA_STRUCT);
  1231. JsonUtils::inherit(toAdd, base);
  1232. toAdd["file"].String() = basepath + node["file"].String();
  1233. source[group][frame] = toAdd;
  1234. }
  1235. }
  1236. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  1237. {
  1238. if(images.empty())
  1239. {
  1240. logGlobal->error("Nothing to export, animation is empty");
  1241. return;
  1242. }
  1243. boost::filesystem::path actualPath = path / "SPRITES" / name;
  1244. boost::filesystem::create_directories(actualPath);
  1245. size_t counter = 0;
  1246. for(const auto & groupPair : images)
  1247. {
  1248. size_t group = groupPair.first;
  1249. for(const auto & imagePair : groupPair.second)
  1250. {
  1251. size_t frame = imagePair.first;
  1252. const IImage * img = imagePair.second;
  1253. boost::format fmt("%d_%d.bmp");
  1254. fmt % group % frame;
  1255. img->exportBitmap(actualPath / fmt.str());
  1256. counter++;
  1257. }
  1258. }
  1259. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  1260. }
  1261. void CAnimation::init()
  1262. {
  1263. if(defFile)
  1264. {
  1265. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  1266. for (auto & defEntry : defEntries)
  1267. source[defEntry.first].resize(defEntry.second);
  1268. }
  1269. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  1270. if (vstd::contains(graphics->imageLists, resID.getName()))
  1271. initFromJson(graphics->imageLists[resID.getName()]);
  1272. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  1273. for(auto & loader : configList)
  1274. {
  1275. auto stream = loader->load(resID);
  1276. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  1277. stream->read(textData.get(), stream->getSize());
  1278. const JsonNode config((char*)textData.get(), stream->getSize());
  1279. initFromJson(config);
  1280. }
  1281. }
  1282. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  1283. {
  1284. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  1285. }
  1286. CAnimation::CAnimation(std::string Name, bool Compressed):
  1287. name(Name),
  1288. compressed(Compressed),
  1289. preloaded(false),
  1290. defFile(nullptr)
  1291. {
  1292. size_t dotPos = name.find_last_of('.');
  1293. if ( dotPos!=-1 )
  1294. name.erase(dotPos);
  1295. std::transform(name.begin(), name.end(), name.begin(), toupper);
  1296. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  1297. if(CResourceHandler::get()->existsResource(resource))
  1298. defFile = new CDefFile(name);
  1299. init();
  1300. if(source.empty())
  1301. logAnim->error("Animation %s failed to load", Name);
  1302. }
  1303. CAnimation::CAnimation():
  1304. name(""),
  1305. compressed(false),
  1306. preloaded(false),
  1307. defFile(nullptr)
  1308. {
  1309. init();
  1310. }
  1311. CAnimation::~CAnimation()
  1312. {
  1313. if(preloaded)
  1314. unload();
  1315. if(!images.empty())
  1316. {
  1317. logGlobal->warn("Warning: not all frames were unloaded from %s", name);
  1318. for (auto & elem : images)
  1319. for (auto & _image : elem.second)
  1320. delete _image.second;
  1321. }
  1322. if(defFile)
  1323. delete defFile;
  1324. }
  1325. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  1326. {
  1327. //todo: clone actual loaded Image object
  1328. JsonNode clone(source[sourceGroup][sourceFrame]);
  1329. if(clone.getType() == JsonNode::DATA_NULL)
  1330. {
  1331. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  1332. clone["file"].String() = temp;
  1333. }
  1334. source[targetGroup].push_back(clone);
  1335. size_t index = source[targetGroup].size() - 1;
  1336. if(preloaded)
  1337. load(index, targetGroup);
  1338. }
  1339. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  1340. {
  1341. if (source[group].size() <= frame)
  1342. source[group].resize(frame+1);
  1343. source[group][frame]["file"].String() = filename;
  1344. //FIXME: update image if already loaded
  1345. }
  1346. IImage * CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  1347. {
  1348. auto groupIter = images.find(group);
  1349. if (groupIter != images.end())
  1350. {
  1351. auto imageIter = groupIter->second.find(frame);
  1352. if (imageIter != groupIter->second.end())
  1353. return imageIter->second;
  1354. }
  1355. if (verbose)
  1356. printError(frame, group, "GetImage");
  1357. return nullptr;
  1358. }
  1359. void CAnimation::load()
  1360. {
  1361. for (auto & elem : source)
  1362. for (size_t image=0; image < elem.second.size(); image++)
  1363. loadFrame(image, elem.first);
  1364. }
  1365. void CAnimation::unload()
  1366. {
  1367. for (auto & elem : source)
  1368. for (size_t image=0; image < elem.second.size(); image++)
  1369. unloadFrame(image, elem.first);
  1370. }
  1371. void CAnimation::preload()
  1372. {
  1373. if(!preloaded)
  1374. {
  1375. preloaded = true;
  1376. load();
  1377. }
  1378. }
  1379. void CAnimation::loadGroup(size_t group)
  1380. {
  1381. if (vstd::contains(source, group))
  1382. for (size_t image=0; image < source[group].size(); image++)
  1383. loadFrame(image, group);
  1384. }
  1385. void CAnimation::unloadGroup(size_t group)
  1386. {
  1387. if (vstd::contains(source, group))
  1388. for (size_t image=0; image < source[group].size(); image++)
  1389. unloadFrame(image, group);
  1390. }
  1391. void CAnimation::load(size_t frame, size_t group)
  1392. {
  1393. loadFrame(frame, group);
  1394. }
  1395. void CAnimation::unload(size_t frame, size_t group)
  1396. {
  1397. unloadFrame(frame, group);
  1398. }
  1399. size_t CAnimation::size(size_t group) const
  1400. {
  1401. auto iter = source.find(group);
  1402. if (iter != source.end())
  1403. return iter->second.size();
  1404. return 0;
  1405. }
  1406. void CAnimation::horizontalFlip()
  1407. {
  1408. for(auto & group : images)
  1409. for(auto & image : group.second)
  1410. image.second->horizontalFlip();
  1411. }
  1412. void CAnimation::verticalFlip()
  1413. {
  1414. for(auto & group : images)
  1415. for(auto & image : group.second)
  1416. image.second->verticalFlip();
  1417. }
  1418. void CAnimation::playerColored(PlayerColor player)
  1419. {
  1420. for(auto & group : images)
  1421. for(auto & image : group.second)
  1422. image.second->playerColored(player);
  1423. }
  1424. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  1425. {
  1426. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  1427. {
  1428. duplicateImage(sourceGroup, frame, targetGroup);
  1429. IImage * image = getImage(frame, targetGroup);
  1430. image->verticalFlip();
  1431. }
  1432. }
  1433. float CFadeAnimation::initialCounter() const
  1434. {
  1435. if (fadingMode == EMode::OUT)
  1436. return 1.0f;
  1437. return 0.0f;
  1438. }
  1439. void CFadeAnimation::update()
  1440. {
  1441. if (!fading)
  1442. return;
  1443. if (fadingMode == EMode::OUT)
  1444. fadingCounter -= delta;
  1445. else
  1446. fadingCounter += delta;
  1447. if (isFinished())
  1448. {
  1449. fading = false;
  1450. if (shouldFreeSurface)
  1451. {
  1452. SDL_FreeSurface(fadingSurface);
  1453. fadingSurface = nullptr;
  1454. }
  1455. }
  1456. }
  1457. bool CFadeAnimation::isFinished() const
  1458. {
  1459. if (fadingMode == EMode::OUT)
  1460. return fadingCounter <= 0.0f;
  1461. return fadingCounter >= 1.0f;
  1462. }
  1463. CFadeAnimation::CFadeAnimation()
  1464. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  1465. fadingMode(EMode::NONE)
  1466. {
  1467. }
  1468. CFadeAnimation::~CFadeAnimation()
  1469. {
  1470. if (fadingSurface && shouldFreeSurface)
  1471. SDL_FreeSurface(fadingSurface);
  1472. }
  1473. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  1474. {
  1475. if (fading)
  1476. {
  1477. // in that case, immediately finish the previous fade
  1478. // (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))
  1479. logGlobal->warn("Tried to init fading animation that is already running.");
  1480. if (fadingSurface && shouldFreeSurface)
  1481. SDL_FreeSurface(fadingSurface);
  1482. }
  1483. if (animDelta <= 0.0f)
  1484. {
  1485. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  1486. animDelta = DEFAULT_DELTA;
  1487. }
  1488. if (sourceSurface)
  1489. fadingSurface = sourceSurface;
  1490. delta = animDelta;
  1491. fadingMode = mode;
  1492. fadingCounter = initialCounter();
  1493. fading = true;
  1494. shouldFreeSurface = freeSurfaceAtEnd;
  1495. }
  1496. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1497. {
  1498. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1499. {
  1500. fading = false;
  1501. return;
  1502. }
  1503. CSDL_Ext::setAlpha(fadingSurface, fadingCounter * 255);
  1504. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1505. CSDL_Ext::setAlpha(fadingSurface, 255);
  1506. }