CAnimation.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788
  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. //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():
  695. refCount(1)
  696. {
  697. }
  698. bool IImage::decreaseRef()
  699. {
  700. refCount--;
  701. return refCount <= 0;
  702. }
  703. void IImage::increaseRef()
  704. {
  705. refCount++;
  706. }
  707. SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group, bool compressed)
  708. : surf(nullptr),
  709. margins(0, 0),
  710. fullSize(0, 0)
  711. {
  712. SDLImageLoader loader(this);
  713. data->loadFrame(frame, group, loader);
  714. }
  715. SDLImage::SDLImage(SDL_Surface * from, bool extraRef)
  716. : surf(nullptr),
  717. margins(0, 0),
  718. fullSize(0, 0)
  719. {
  720. surf = from;
  721. if (extraRef)
  722. surf->refcount++;
  723. fullSize.x = surf->w;
  724. fullSize.y = surf->h;
  725. }
  726. SDLImage::SDLImage(const JsonNode & conf)
  727. : surf(nullptr),
  728. margins(0, 0),
  729. fullSize(0, 0)
  730. {
  731. std::string filename = conf["file"].String();
  732. surf = BitmapHandler::loadBitmap(filename);
  733. if(surf == nullptr)
  734. return;
  735. const JsonNode & jsonMargins = conf["margins"];
  736. margins.x = jsonMargins["left"].Integer();
  737. margins.y = jsonMargins["top"].Integer();
  738. fullSize.x = conf["width"].Integer();
  739. fullSize.y = conf["height"].Integer();
  740. if(fullSize.x == 0)
  741. {
  742. fullSize.x = margins.x + surf->w + jsonMargins["right"].Integer();
  743. }
  744. if(fullSize.y == 0)
  745. {
  746. fullSize.y = margins.y + surf->h + jsonMargins["bottom"].Integer();
  747. }
  748. }
  749. SDLImage::SDLImage(std::string filename, bool compressed)
  750. : surf(nullptr),
  751. margins(0, 0),
  752. fullSize(0, 0)
  753. {
  754. surf = BitmapHandler::loadBitmap(filename);
  755. if (surf == nullptr)
  756. {
  757. logGlobal->error("Error: failed to load image %s", filename);
  758. return;
  759. }
  760. else
  761. {
  762. fullSize.x = surf->w;
  763. fullSize.y = surf->h;
  764. }
  765. if (compressed)
  766. {
  767. SDL_Surface *temp = surf;
  768. // add RLE flag
  769. if (surf->format->palette)
  770. {
  771. CSDL_Ext::setColorKey(temp,temp->format->palette->colors[0]);
  772. }
  773. SDL_SetSurfaceRLE(temp, SDL_RLEACCEL);
  774. // convert surface to enable RLE
  775. surf = SDL_ConvertSurface(temp, temp->format, temp->flags);
  776. SDL_FreeSurface(temp);
  777. }
  778. }
  779. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  780. {
  781. if(!surf)
  782. return;
  783. Rect destRect(posX, posY, surf->w, surf->h);
  784. draw(where, &destRect, src);
  785. }
  786. void SDLImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  787. {
  788. if (!surf)
  789. return;
  790. Rect sourceRect(0, 0, surf->w, surf->h);
  791. Point destShift(0, 0);
  792. if(src)
  793. {
  794. if(src->x < margins.x)
  795. destShift.x += margins.x - src->x;
  796. if(src->y < margins.y)
  797. destShift.y += margins.y - src->y;
  798. sourceRect = Rect(*src) & Rect(margins.x, margins.y, surf->w, surf->h);
  799. sourceRect -= margins;
  800. }
  801. else
  802. destShift = margins;
  803. Rect destRect(destShift.x, destShift.y, surf->w, surf->h);
  804. if(dest)
  805. {
  806. destRect.x += dest->x;
  807. destRect.y += dest->y;
  808. }
  809. if(surf->format->BitsPerPixel == 8)
  810. {
  811. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  812. }
  813. else
  814. {
  815. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  816. }
  817. }
  818. std::unique_ptr<IImage> SDLImage::scaleFast(float scale) const
  819. {
  820. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, surf->w * scale, surf->h * scale);
  821. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  822. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  823. else if(scaled->format && scaled->format->Amask)
  824. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  825. else
  826. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  827. SDLImage * ret = new SDLImage(scaled, false);
  828. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  829. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  830. ret->margins.x = (int) round((float)margins.x * scale);
  831. ret->margins.y = (int) round((float)margins.y * scale);
  832. return std::unique_ptr<IImage>(ret);
  833. }
  834. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  835. {
  836. SDL_SaveBMP(surf, path.string().c_str());
  837. }
  838. void SDLImage::playerColored(PlayerColor player)
  839. {
  840. graphics->blueToPlayersAdv(surf, player);
  841. }
  842. void SDLImage::setFlagColor(PlayerColor player)
  843. {
  844. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  845. CSDL_Ext::setPlayerColor(surf, player);
  846. }
  847. int SDLImage::width() const
  848. {
  849. return fullSize.x;
  850. }
  851. int SDLImage::height() const
  852. {
  853. return fullSize.y;
  854. }
  855. void SDLImage::horizontalFlip()
  856. {
  857. margins.y = fullSize.y - surf->h - margins.y;
  858. //todo: modify in-place
  859. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  860. SDL_FreeSurface(surf);
  861. surf = flipped;
  862. }
  863. void SDLImage::verticalFlip()
  864. {
  865. margins.x = fullSize.x - surf->w - margins.x;
  866. //todo: modify in-place
  867. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  868. SDL_FreeSurface(surf);
  869. surf = flipped;
  870. }
  871. void SDLImage::shiftPalette(int from, int howMany)
  872. {
  873. //works with at most 16 colors, if needed more -> increase values
  874. assert(howMany < 16);
  875. if(surf->format->palette)
  876. {
  877. SDL_Color palette[16];
  878. for(int i=0; i<howMany; ++i)
  879. {
  880. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  881. }
  882. SDL_SetColors(surf, palette, from, howMany);
  883. }
  884. }
  885. void SDLImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  886. {
  887. if(surf->format->palette)
  888. {
  889. SDL_SetColors(surf, const_cast<SDL_Color *>(borderPallete.data()), 5, 3);
  890. }
  891. }
  892. SDLImage::~SDLImage()
  893. {
  894. SDL_FreeSurface(surf);
  895. }
  896. CompImage::CompImage(const CDefFile *data, size_t frame, size_t group):
  897. surf(nullptr),
  898. line(nullptr),
  899. palette(nullptr)
  900. {
  901. CompImageLoader loader(this);
  902. data->loadFrame(frame, group, loader);
  903. }
  904. CompImage::CompImage(SDL_Surface * surf)
  905. {
  906. //TODO
  907. assert(0);
  908. }
  909. void CompImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  910. {
  911. Rect dest(posX,posY, width(), height());
  912. draw(where, &dest, src, alpha);
  913. }
  914. void CompImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  915. {
  916. int rotation = 0; //TODO
  917. //rotation & 2 = horizontal rotation
  918. //rotation & 4 = vertical rotation
  919. if (!surf)
  920. return;
  921. Rect sourceRect(sprite);
  922. //TODO: rotation and scaling
  923. if (src)
  924. sourceRect = sourceRect & *src;
  925. //Limit source rect to sizes of surface
  926. sourceRect = sourceRect & Rect(0, 0, where->w, where->h);
  927. //Starting point on SDL surface
  928. Point dst(sourceRect.x,sourceRect.y);
  929. if (dest)
  930. {
  931. dst.x += dest->x;
  932. dst.y += dest->y;
  933. }
  934. if (rotation & 2)
  935. dst.y += sourceRect.h;
  936. if (rotation & 4)
  937. dst.x += sourceRect.w;
  938. sourceRect -= sprite.topLeft();
  939. for (int currY = 0; currY <sourceRect.h; currY++)
  940. {
  941. ui8* data = surf + line[currY+sourceRect.y];
  942. ui8 type = *(data++);
  943. ui8 size = *(data++);
  944. int currX = sourceRect.x;
  945. //Skip blocks until starting position reached
  946. while ( currX > size )
  947. {
  948. currX -= size;
  949. if (type == 0xff)
  950. data += size;
  951. type = *(data++);
  952. size = *(data++);
  953. }
  954. //This block will be shown partially - calculate size\position
  955. size -= currX;
  956. if (type == 0xff)
  957. data += currX;
  958. currX = 0;
  959. ui8 bpp = where->format->BytesPerPixel;
  960. //Calculate position for blitting: pixels + Y + X
  961. ui8* blitPos = (ui8*) where->pixels;
  962. if (rotation & 4)
  963. blitPos += (dst.y - currY) * where->pitch;
  964. else
  965. blitPos += (dst.y + currY) * where->pitch;
  966. blitPos += dst.x * bpp;
  967. //Blit blocks that must be fully visible
  968. while (currX + size < sourceRect.w)
  969. {
  970. //blit block, pointers will be modified if needed
  971. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  972. currX += size;
  973. type = *(data++);
  974. size = *(data++);
  975. }
  976. //Blit last, semi-visible block
  977. size = sourceRect.w - currX;
  978. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  979. }
  980. }
  981. std::unique_ptr<IImage> CompImage::scaleFast(float scale) const
  982. {
  983. //todo: CompImage::scaleFast
  984. logAnim->error("CompImage::scaleFast is not implemented");
  985. return nullptr;
  986. }
  987. #define CASEBPP(x,y) case x: BlitBlock<x,y>(type, size, data, dest, alpha); break
  988. //FIXME: better way to get blitter
  989. void CompImage::BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const
  990. {
  991. assert(bpp>1 && bpp<5);
  992. if (rotated)
  993. switch (bpp)
  994. {
  995. CASEBPP(2,1);
  996. CASEBPP(3,1);
  997. CASEBPP(4,1);
  998. }
  999. else
  1000. switch (bpp)
  1001. {
  1002. CASEBPP(2,1);
  1003. CASEBPP(3,1);
  1004. CASEBPP(4,1);
  1005. }
  1006. }
  1007. #undef CASEBPP
  1008. //Blit one block from RLE-d surface
  1009. template<int bpp, int dir>
  1010. void CompImage::BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const
  1011. {
  1012. //Raw data
  1013. if (type == 0xff)
  1014. {
  1015. ui8 color = *data;
  1016. if (alpha != 255)//Per-surface alpha is set
  1017. {
  1018. for (size_t i=0; i<size; i++)
  1019. {
  1020. SDL_Color col = palette[*(data++)];
  1021. col.a = (ui32)col.a*alpha/255;
  1022. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  1023. }
  1024. return;
  1025. }
  1026. if (palette[color].a == 255)
  1027. {
  1028. //Put row of RGB data
  1029. for (size_t i=0; i<size; i++)
  1030. ColorPutter<bpp, 1>::PutColor(dest, palette[*(data++)]);
  1031. }
  1032. else
  1033. {
  1034. //Put row of RGBA data
  1035. for (size_t i=0; i<size; i++)
  1036. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[*(data++)]);
  1037. }
  1038. }
  1039. //RLE-d sequence
  1040. else
  1041. {
  1042. if (alpha != 255 && palette[type].a !=0)//Per-surface alpha is set
  1043. {
  1044. SDL_Color col = palette[type];
  1045. col.a = (int)col.a*(255-alpha)/255;
  1046. for (size_t i=0; i<size; i++)
  1047. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  1048. return;
  1049. }
  1050. switch (palette[type].a)
  1051. {
  1052. case 0:
  1053. {
  1054. //Skip row
  1055. dest += size*bpp;
  1056. break;
  1057. }
  1058. case 255:
  1059. {
  1060. //Put RGB row
  1061. ColorPutter<bpp, 1>::PutColorRow(dest, palette[type], size);
  1062. break;
  1063. }
  1064. default:
  1065. {
  1066. //Put RGBA row
  1067. for (size_t i=0; i<size; i++)
  1068. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[type]);
  1069. break;
  1070. }
  1071. }
  1072. }
  1073. }
  1074. void CompImage::playerColored(PlayerColor player)
  1075. {
  1076. SDL_Color *pal = nullptr;
  1077. if(player < PlayerColor::PLAYER_LIMIT)
  1078. {
  1079. pal = graphics->playerColorPalette + 32*player.getNum();
  1080. }
  1081. else if(player == PlayerColor::NEUTRAL)
  1082. {
  1083. pal = graphics->neutralColorPalette;
  1084. }
  1085. else
  1086. assert(0);
  1087. for(int i=0; i<32; ++i)
  1088. {
  1089. CSDL_Ext::colorAssign(palette[224+i],pal[i]);
  1090. }
  1091. }
  1092. void CompImage::setFlagColor(PlayerColor player)
  1093. {
  1094. logAnim->error("CompImage::setFlagColor is not implemented");
  1095. }
  1096. int CompImage::width() const
  1097. {
  1098. return fullSize.x;
  1099. }
  1100. int CompImage::height() const
  1101. {
  1102. return fullSize.y;
  1103. }
  1104. CompImage::~CompImage()
  1105. {
  1106. free(surf);
  1107. delete [] line;
  1108. delete [] palette;
  1109. }
  1110. void CompImage::horizontalFlip()
  1111. {
  1112. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1113. }
  1114. void CompImage::verticalFlip()
  1115. {
  1116. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1117. }
  1118. void CompImage::shiftPalette(int from, int howMany)
  1119. {
  1120. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1121. }
  1122. void CompImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  1123. {
  1124. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1125. }
  1126. void CompImage::exportBitmap(const boost::filesystem::path & path) const
  1127. {
  1128. logAnim->error("%s is not implemented", BOOST_CURRENT_FUNCTION);
  1129. }
  1130. /*************************************************************************
  1131. * CAnimation for animations handling, can load part of file if needed *
  1132. *************************************************************************/
  1133. IImage * CAnimation::getFromExtraDef(std::string filename)
  1134. {
  1135. size_t pos = filename.find(':');
  1136. if (pos == -1)
  1137. return nullptr;
  1138. CAnimation anim(filename.substr(0, pos));
  1139. pos++;
  1140. size_t frame = atoi(filename.c_str()+pos);
  1141. size_t group = 0;
  1142. pos = filename.find(':', pos);
  1143. if (pos != -1)
  1144. {
  1145. pos++;
  1146. group = frame;
  1147. frame = atoi(filename.c_str()+pos);
  1148. }
  1149. anim.load(frame ,group);
  1150. IImage * ret = anim.images[group][frame];
  1151. anim.images.clear();
  1152. return ret;
  1153. }
  1154. bool CAnimation::loadFrame(size_t frame, size_t group)
  1155. {
  1156. if(size(group) <= frame)
  1157. {
  1158. printError(frame, group, "LoadFrame");
  1159. return false;
  1160. }
  1161. IImage * image = getImage(frame, group, false);
  1162. if(image)
  1163. {
  1164. image->increaseRef();
  1165. return true;
  1166. }
  1167. //try to get image from def
  1168. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  1169. {
  1170. if(defFile)
  1171. {
  1172. auto frameList = defFile->getEntries();
  1173. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  1174. {
  1175. if(compressed)
  1176. images[group][frame] = new CompImage(defFile, frame, group);
  1177. else
  1178. images[group][frame] = new SDLImage(defFile, frame, group);
  1179. return true;
  1180. }
  1181. }
  1182. // still here? image is missing
  1183. printError(frame, group, "LoadFrame");
  1184. images[group][frame] = new SDLImage("DEFAULT", compressed);
  1185. }
  1186. else //load from separate file
  1187. {
  1188. IImage * img = getFromExtraDef(source[group][frame]["file"].String());
  1189. if(!img)
  1190. img = new SDLImage(source[group][frame]);
  1191. images[group][frame] = img;
  1192. return true;
  1193. }
  1194. return false;
  1195. }
  1196. bool CAnimation::unloadFrame(size_t frame, size_t group)
  1197. {
  1198. IImage *image = getImage(frame, group, false);
  1199. if (image)
  1200. {
  1201. //decrease ref count for image and delete if needed
  1202. if (image->decreaseRef())
  1203. {
  1204. delete image;
  1205. images[group].erase(frame);
  1206. }
  1207. if (images[group].empty())
  1208. images.erase(group);
  1209. return true;
  1210. }
  1211. return false;
  1212. }
  1213. void CAnimation::initFromJson(const JsonNode & config)
  1214. {
  1215. std::string basepath;
  1216. basepath = config["basepath"].String();
  1217. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  1218. base["margins"] = config["margins"];
  1219. base["width"] = config["width"];
  1220. base["height"] = config["height"];
  1221. for(const JsonNode & group : config["sequences"].Vector())
  1222. {
  1223. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  1224. source[groupID].clear();
  1225. for(const JsonNode & frame : group["frames"].Vector())
  1226. {
  1227. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  1228. JsonUtils::inherit(toAdd, base);
  1229. toAdd["file"].String() = basepath + frame.String();
  1230. source[groupID].push_back(toAdd);
  1231. }
  1232. }
  1233. for(const JsonNode & node : config["images"].Vector())
  1234. {
  1235. size_t group = node["group"].Integer();
  1236. size_t frame = node["frame"].Integer();
  1237. if (source[group].size() <= frame)
  1238. source[group].resize(frame+1);
  1239. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  1240. JsonUtils::inherit(toAdd, base);
  1241. toAdd["file"].String() = basepath + node["file"].String();
  1242. source[group][frame] = toAdd;
  1243. }
  1244. }
  1245. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  1246. {
  1247. if(images.empty())
  1248. {
  1249. logGlobal->error("Nothing to export, animation is empty");
  1250. return;
  1251. }
  1252. boost::filesystem::path actualPath = path / "SPRITES" / name;
  1253. boost::filesystem::create_directories(actualPath);
  1254. size_t counter = 0;
  1255. for(const auto & groupPair : images)
  1256. {
  1257. size_t group = groupPair.first;
  1258. for(const auto & imagePair : groupPair.second)
  1259. {
  1260. size_t frame = imagePair.first;
  1261. const IImage * img = imagePair.second;
  1262. boost::format fmt("%d_%d.bmp");
  1263. fmt % group % frame;
  1264. img->exportBitmap(actualPath / fmt.str());
  1265. counter++;
  1266. }
  1267. }
  1268. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  1269. }
  1270. void CAnimation::init()
  1271. {
  1272. if(defFile)
  1273. {
  1274. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  1275. for (auto & defEntry : defEntries)
  1276. source[defEntry.first].resize(defEntry.second);
  1277. }
  1278. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  1279. if (vstd::contains(graphics->imageLists, resID.getName()))
  1280. initFromJson(graphics->imageLists[resID.getName()]);
  1281. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  1282. for(auto & loader : configList)
  1283. {
  1284. auto stream = loader->load(resID);
  1285. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  1286. stream->read(textData.get(), stream->getSize());
  1287. const JsonNode config((char*)textData.get(), stream->getSize());
  1288. initFromJson(config);
  1289. }
  1290. }
  1291. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  1292. {
  1293. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  1294. }
  1295. CAnimation::CAnimation(std::string Name, bool Compressed):
  1296. name(Name),
  1297. compressed(Compressed),
  1298. preloaded(false),
  1299. defFile(nullptr)
  1300. {
  1301. size_t dotPos = name.find_last_of('.');
  1302. if ( dotPos!=-1 )
  1303. name.erase(dotPos);
  1304. std::transform(name.begin(), name.end(), name.begin(), toupper);
  1305. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  1306. if(CResourceHandler::get()->existsResource(resource))
  1307. defFile = new CDefFile(name);
  1308. init();
  1309. if(source.empty())
  1310. logAnim->error("Animation %s failed to load", Name);
  1311. }
  1312. CAnimation::CAnimation():
  1313. name(""),
  1314. compressed(false),
  1315. preloaded(false),
  1316. defFile(nullptr)
  1317. {
  1318. init();
  1319. }
  1320. CAnimation::~CAnimation()
  1321. {
  1322. if(preloaded)
  1323. unload();
  1324. if(!images.empty())
  1325. {
  1326. logGlobal->warn("Warning: not all frames were unloaded from %s", name);
  1327. for (auto & elem : images)
  1328. for (auto & _image : elem.second)
  1329. delete _image.second;
  1330. }
  1331. if(defFile)
  1332. delete defFile;
  1333. }
  1334. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  1335. {
  1336. //todo: clone actual loaded Image object
  1337. JsonNode clone(source[sourceGroup][sourceFrame]);
  1338. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  1339. {
  1340. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  1341. clone["file"].String() = temp;
  1342. }
  1343. source[targetGroup].push_back(clone);
  1344. size_t index = source[targetGroup].size() - 1;
  1345. if(preloaded)
  1346. load(index, targetGroup);
  1347. }
  1348. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  1349. {
  1350. if (source[group].size() <= frame)
  1351. source[group].resize(frame+1);
  1352. source[group][frame]["file"].String() = filename;
  1353. //FIXME: update image if already loaded
  1354. }
  1355. IImage * CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  1356. {
  1357. auto groupIter = images.find(group);
  1358. if (groupIter != images.end())
  1359. {
  1360. auto imageIter = groupIter->second.find(frame);
  1361. if (imageIter != groupIter->second.end())
  1362. return imageIter->second;
  1363. }
  1364. if (verbose)
  1365. printError(frame, group, "GetImage");
  1366. return nullptr;
  1367. }
  1368. void CAnimation::load()
  1369. {
  1370. for (auto & elem : source)
  1371. for (size_t image=0; image < elem.second.size(); image++)
  1372. loadFrame(image, elem.first);
  1373. }
  1374. void CAnimation::unload()
  1375. {
  1376. for (auto & elem : source)
  1377. for (size_t image=0; image < elem.second.size(); image++)
  1378. unloadFrame(image, elem.first);
  1379. }
  1380. void CAnimation::preload()
  1381. {
  1382. if(!preloaded)
  1383. {
  1384. preloaded = true;
  1385. load();
  1386. }
  1387. }
  1388. void CAnimation::loadGroup(size_t group)
  1389. {
  1390. if (vstd::contains(source, group))
  1391. for (size_t image=0; image < source[group].size(); image++)
  1392. loadFrame(image, group);
  1393. }
  1394. void CAnimation::unloadGroup(size_t group)
  1395. {
  1396. if (vstd::contains(source, group))
  1397. for (size_t image=0; image < source[group].size(); image++)
  1398. unloadFrame(image, group);
  1399. }
  1400. void CAnimation::load(size_t frame, size_t group)
  1401. {
  1402. loadFrame(frame, group);
  1403. }
  1404. void CAnimation::unload(size_t frame, size_t group)
  1405. {
  1406. unloadFrame(frame, group);
  1407. }
  1408. size_t CAnimation::size(size_t group) const
  1409. {
  1410. auto iter = source.find(group);
  1411. if (iter != source.end())
  1412. return iter->second.size();
  1413. return 0;
  1414. }
  1415. void CAnimation::horizontalFlip()
  1416. {
  1417. for(auto & group : images)
  1418. for(auto & image : group.second)
  1419. image.second->horizontalFlip();
  1420. }
  1421. void CAnimation::verticalFlip()
  1422. {
  1423. for(auto & group : images)
  1424. for(auto & image : group.second)
  1425. image.second->verticalFlip();
  1426. }
  1427. void CAnimation::playerColored(PlayerColor player)
  1428. {
  1429. for(auto & group : images)
  1430. for(auto & image : group.second)
  1431. image.second->playerColored(player);
  1432. }
  1433. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  1434. {
  1435. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  1436. {
  1437. duplicateImage(sourceGroup, frame, targetGroup);
  1438. IImage * image = getImage(frame, targetGroup);
  1439. image->verticalFlip();
  1440. }
  1441. }
  1442. float CFadeAnimation::initialCounter() const
  1443. {
  1444. if (fadingMode == EMode::OUT)
  1445. return 1.0f;
  1446. return 0.0f;
  1447. }
  1448. void CFadeAnimation::update()
  1449. {
  1450. if (!fading)
  1451. return;
  1452. if (fadingMode == EMode::OUT)
  1453. fadingCounter -= delta;
  1454. else
  1455. fadingCounter += delta;
  1456. if (isFinished())
  1457. {
  1458. fading = false;
  1459. if (shouldFreeSurface)
  1460. {
  1461. SDL_FreeSurface(fadingSurface);
  1462. fadingSurface = nullptr;
  1463. }
  1464. }
  1465. }
  1466. bool CFadeAnimation::isFinished() const
  1467. {
  1468. if (fadingMode == EMode::OUT)
  1469. return fadingCounter <= 0.0f;
  1470. return fadingCounter >= 1.0f;
  1471. }
  1472. CFadeAnimation::CFadeAnimation()
  1473. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  1474. fadingMode(EMode::NONE)
  1475. {
  1476. }
  1477. CFadeAnimation::~CFadeAnimation()
  1478. {
  1479. if (fadingSurface && shouldFreeSurface)
  1480. SDL_FreeSurface(fadingSurface);
  1481. }
  1482. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  1483. {
  1484. if (fading)
  1485. {
  1486. // in that case, immediately finish the previous fade
  1487. // (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))
  1488. logGlobal->warn("Tried to init fading animation that is already running.");
  1489. if (fadingSurface && shouldFreeSurface)
  1490. SDL_FreeSurface(fadingSurface);
  1491. }
  1492. if (animDelta <= 0.0f)
  1493. {
  1494. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  1495. animDelta = DEFAULT_DELTA;
  1496. }
  1497. if (sourceSurface)
  1498. fadingSurface = sourceSurface;
  1499. delta = animDelta;
  1500. fadingMode = mode;
  1501. fadingCounter = initialCounter();
  1502. fading = true;
  1503. shouldFreeSurface = freeSurfaceAtEnd;
  1504. }
  1505. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1506. {
  1507. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1508. {
  1509. fading = false;
  1510. return;
  1511. }
  1512. CSDL_Ext::setAlpha(fadingSurface, fadingCounter * 255);
  1513. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1514. CSDL_Ext::setAlpha(fadingSurface, 255);
  1515. }