CAnimation.cpp 40 KB

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