CAnimation.cpp 39 KB

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