CAnimation.cpp 36 KB

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