CAnimation.cpp 38 KB

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