CAnimation.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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. typedef std::map <size_t, std::vector <JsonNode> > source_map;
  23. typedef std::map<size_t, IImage* > image_map;
  24. typedef std::map<size_t, image_map > group_map;
  25. /// Class for def loading
  26. /// After loading will store general info (palette and frame offsets) and pointer to file itself
  27. class CDefFile
  28. {
  29. private:
  30. struct SSpriteDef
  31. {
  32. ui32 size;
  33. ui32 format; /// format in which pixel data is stored
  34. ui32 fullWidth; /// full width and height of frame, including borders
  35. ui32 fullHeight;
  36. ui32 width; /// width and height of pixel data, borders excluded
  37. ui32 height;
  38. si32 leftMargin;
  39. si32 topMargin;
  40. } PACKED_STRUCT;
  41. //offset[group][frame] - offset of frame data in file
  42. std::map<size_t, std::vector <size_t> > offset;
  43. std::unique_ptr<ui8[]> data;
  44. std::unique_ptr<SDL_Color[]> palette;
  45. public:
  46. CDefFile(std::string Name);
  47. ~CDefFile();
  48. //load frame as SDL_Surface
  49. template<class ImageLoader>
  50. void loadFrame(size_t frame, size_t group, ImageLoader &loader) const;
  51. const std::map<size_t, size_t> getEntries() const;
  52. };
  53. /*
  54. * Wrapper around SDL_Surface
  55. */
  56. class SDLImage : public IImage
  57. {
  58. public:
  59. const static int DEFAULT_PALETTE_COLORS = 256;
  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);
  69. //Load from bitmap file
  70. SDLImage(std::string filename);
  71. SDLImage(const JsonNode & conf);
  72. //Create using existing surface, extraRef will increase refcount on SDL_Surface
  73. SDLImage(SDL_Surface * from, bool extraRef);
  74. ~SDLImage();
  75. // Keep the original palette, in order to do color switching operation
  76. void savePalette();
  77. void draw(SDL_Surface * where, int posX=0, int posY=0, Rect *src=nullptr, ui8 alpha=255) const override;
  78. void draw(SDL_Surface * where, SDL_Rect * dest, SDL_Rect * src, ui8 alpha=255) const override;
  79. std::shared_ptr<IImage> scaleFast(float scale) const override;
  80. void exportBitmap(const boost::filesystem::path & path) const override;
  81. void playerColored(PlayerColor player) override;
  82. void setFlagColor(PlayerColor player) override;
  83. int width() const override;
  84. int height() const override;
  85. void horizontalFlip() override;
  86. void verticalFlip() override;
  87. void shiftPalette(int from, int howMany) override;
  88. void adjustPalette(const ColorShifter * shifter) override;
  89. void resetPalette() override;
  90. void setBorderPallete(const BorderPallete & borderPallete) override;
  91. friend class SDLImageLoader;
  92. private:
  93. SDL_Palette * originalPalette;
  94. };
  95. class SDLImageLoader
  96. {
  97. SDLImage * image;
  98. ui8 * lineStart;
  99. ui8 * position;
  100. public:
  101. //load size raw pixels from data
  102. inline void Load(size_t size, const ui8 * data);
  103. //set size pixels to color
  104. inline void Load(size_t size, ui8 color=0);
  105. inline void EndLine();
  106. //init image with these sizes and palette
  107. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  108. SDLImageLoader(SDLImage * Img);
  109. ~SDLImageLoader();
  110. };
  111. // Extremely simple file cache. TODO: smarter, more general solution
  112. class CFileCache
  113. {
  114. static const int cacheSize = 50; //Max number of cached files
  115. struct FileData
  116. {
  117. ResourceID name;
  118. size_t size;
  119. std::unique_ptr<ui8[]> data;
  120. std::unique_ptr<ui8[]> getCopy()
  121. {
  122. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  123. std::copy(data.get(), data.get() + size, ret.get());
  124. return ret;
  125. }
  126. FileData(ResourceID name_, size_t size_, std::unique_ptr<ui8[]> data_):
  127. name{std::move(name_)},
  128. size{size_},
  129. data{std::move(data_)}
  130. {}
  131. };
  132. std::deque<FileData> cache;
  133. public:
  134. std::unique_ptr<ui8[]> getCachedFile(ResourceID rid)
  135. {
  136. for(auto & file : cache)
  137. {
  138. if (file.name == rid)
  139. return file.getCopy();
  140. }
  141. // Still here? Cache miss
  142. if (cache.size() > cacheSize)
  143. cache.pop_front();
  144. auto data = CResourceHandler::get()->load(rid)->readAll();
  145. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  146. return cache.back().getCopy();
  147. }
  148. };
  149. enum class DefType : uint32_t
  150. {
  151. SPELL = 0x40,
  152. SPRITE = 0x41,
  153. CREATURE = 0x42,
  154. MAP = 0x43,
  155. MAP_HERO = 0x44,
  156. TERRAIN = 0x45,
  157. CURSOR = 0x46,
  158. INTERFACE = 0x47,
  159. SPRITE_FRAME = 0x48,
  160. BATTLE_HERO = 0x49
  161. };
  162. static CFileCache animationCache;
  163. /*************************************************************************
  164. * DefFile, class used for def loading *
  165. *************************************************************************/
  166. bool operator== (const SDL_Color & lhs, const SDL_Color & rhs)
  167. {
  168. return (lhs.a == rhs.a) && (lhs.b == rhs.b) &&(lhs.g == rhs.g) &&(lhs.r == rhs.r);
  169. }
  170. CDefFile::CDefFile(std::string Name):
  171. data(nullptr),
  172. palette(nullptr)
  173. {
  174. #if 0
  175. static SDL_Color H3_ORIG_PALETTE[8] =
  176. {
  177. { 0, 255, 255, SDL_ALPHA_OPAQUE},
  178. {255, 150, 255, SDL_ALPHA_OPAQUE},
  179. {255, 100, 255, SDL_ALPHA_OPAQUE},
  180. {255, 50, 255, SDL_ALPHA_OPAQUE},
  181. {255, 0, 255, SDL_ALPHA_OPAQUE},
  182. {255, 255, 0, SDL_ALPHA_OPAQUE},
  183. {180, 0, 255, SDL_ALPHA_OPAQUE},
  184. { 0, 255, 0, SDL_ALPHA_OPAQUE}
  185. };
  186. #endif // 0
  187. //First 8 colors in def palette used for transparency
  188. static SDL_Color H3Palette[8] =
  189. {
  190. { 0, 0, 0, 0},// 100% - transparency
  191. { 0, 0, 0, 32},// 75% - shadow border,
  192. { 0, 0, 0, 64},// TODO: find exact value
  193. { 0, 0, 0, 128},// TODO: for transparency
  194. { 0, 0, 0, 128},// 50% - shadow body
  195. { 0, 0, 0, 0},// 100% - selection highlight
  196. { 0, 0, 0, 128},// 50% - shadow body below selection
  197. { 0, 0, 0, 64} // 75% - shadow border below selection
  198. };
  199. data = animationCache.getCachedFile(ResourceID(std::string("SPRITES/") + Name, EResType::ANIMATION));
  200. palette = std::unique_ptr<SDL_Color[]>(new SDL_Color[256]);
  201. int it = 0;
  202. ui32 type = read_le_u32(data.get() + it);
  203. it+=4;
  204. //int width = read_le_u32(data + it); it+=4;//not used
  205. //int height = read_le_u32(data + it); it+=4;
  206. it+=8;
  207. ui32 totalBlocks = read_le_u32(data.get() + it);
  208. it+=4;
  209. for (ui32 i= 0; i<256; i++)
  210. {
  211. palette[i].r = data[it++];
  212. palette[i].g = data[it++];
  213. palette[i].b = data[it++];
  214. palette[i].a = SDL_ALPHA_OPAQUE;
  215. }
  216. switch(static_cast<DefType>(type))
  217. {
  218. case DefType::SPELL:
  219. palette[0] = H3Palette[0];
  220. break;
  221. case DefType::SPRITE:
  222. case DefType::SPRITE_FRAME:
  223. for(ui32 i= 0; i<8; i++)
  224. palette[i] = H3Palette[i];
  225. break;
  226. case DefType::CREATURE:
  227. palette[0] = H3Palette[0];
  228. palette[1] = H3Palette[1];
  229. palette[4] = H3Palette[4];
  230. palette[5] = H3Palette[5];
  231. palette[6] = H3Palette[6];
  232. palette[7] = H3Palette[7];
  233. break;
  234. case DefType::MAP:
  235. case DefType::MAP_HERO:
  236. palette[0] = H3Palette[0];
  237. palette[1] = H3Palette[1];
  238. palette[4] = H3Palette[4];
  239. //5 = owner flag, handled separately
  240. break;
  241. case DefType::TERRAIN:
  242. palette[0] = H3Palette[0];
  243. palette[1] = H3Palette[1];
  244. palette[2] = H3Palette[2];
  245. palette[3] = H3Palette[3];
  246. palette[4] = H3Palette[4];
  247. break;
  248. case DefType::CURSOR:
  249. palette[0] = H3Palette[0];
  250. break;
  251. case DefType::INTERFACE:
  252. palette[0] = H3Palette[0];
  253. palette[1] = H3Palette[1];
  254. palette[4] = H3Palette[4];
  255. //player colors handled separately
  256. //TODO: disallow colorizing other def types
  257. break;
  258. case DefType::BATTLE_HERO:
  259. palette[0] = H3Palette[0];
  260. palette[1] = H3Palette[1];
  261. palette[4] = H3Palette[4];
  262. break;
  263. default:
  264. logAnim->error("Unknown def type %d in %s", type, Name);
  265. break;
  266. }
  267. for (ui32 i=0; i<totalBlocks; i++)
  268. {
  269. size_t blockID = read_le_u32(data.get() + it);
  270. it+=4;
  271. size_t totalEntries = read_le_u32(data.get() + it);
  272. it+=12;
  273. //8 unknown bytes - skipping
  274. //13 bytes for name of every frame in this block - not used, skipping
  275. it+= 13 * (int)totalEntries;
  276. for (ui32 j=0; j<totalEntries; j++)
  277. {
  278. size_t currOffset = read_le_u32(data.get() + it);
  279. offset[blockID].push_back(currOffset);
  280. it += 4;
  281. }
  282. }
  283. }
  284. template<class ImageLoader>
  285. void CDefFile::loadFrame(size_t frame, size_t group, ImageLoader &loader) const
  286. {
  287. std::map<size_t, std::vector <size_t> >::const_iterator it;
  288. it = offset.find(group);
  289. assert (it != offset.end());
  290. const ui8 * FDef = data.get()+it->second[frame];
  291. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  292. SSpriteDef sprite;
  293. sprite.format = read_le_u32(&sd.format);
  294. sprite.fullWidth = read_le_u32(&sd.fullWidth);
  295. sprite.fullHeight = read_le_u32(&sd.fullHeight);
  296. sprite.width = read_le_u32(&sd.width);
  297. sprite.height = read_le_u32(&sd.height);
  298. sprite.leftMargin = read_le_u32(&sd.leftMargin);
  299. sprite.topMargin = read_le_u32(&sd.topMargin);
  300. ui32 currentOffset = sizeof(SSpriteDef);
  301. //special case for some "old" format defs (SGTWMTA.DEF and SGTWMTB.DEF)
  302. if(sprite.format == 1 && sprite.width > sprite.fullWidth && sprite.height > sprite.fullHeight)
  303. {
  304. sprite.leftMargin = 0;
  305. sprite.topMargin = 0;
  306. sprite.width = sprite.fullWidth;
  307. sprite.height = sprite.fullHeight;
  308. currentOffset -= 16;
  309. }
  310. const ui32 BaseOffset = currentOffset;
  311. loader.init(Point(sprite.width, sprite.height),
  312. Point(sprite.leftMargin, sprite.topMargin),
  313. Point(sprite.fullWidth, sprite.fullHeight), palette.get());
  314. switch(sprite.format)
  315. {
  316. case 0:
  317. {
  318. //pixel data is not compressed, copy data to surface
  319. for(ui32 i=0; i<sprite.height; i++)
  320. {
  321. loader.Load(sprite.width, FDef + currentOffset);
  322. currentOffset += sprite.width;
  323. loader.EndLine();
  324. }
  325. break;
  326. }
  327. case 1:
  328. {
  329. //for each line we have offset of pixel data
  330. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  331. currentOffset += sizeof(ui32) * sprite.height;
  332. for(ui32 i=0; i<sprite.height; i++)
  333. {
  334. //get position of the line
  335. currentOffset=BaseOffset + read_le_u32(RWEntriesLoc + i);
  336. ui32 TotalRowLength = 0;
  337. while(TotalRowLength<sprite.width)
  338. {
  339. ui8 segmentType = FDef[currentOffset++];
  340. ui32 length = FDef[currentOffset++] + 1;
  341. if(segmentType==0xFF)//Raw data
  342. {
  343. loader.Load(length, FDef + currentOffset);
  344. currentOffset+=length;
  345. }
  346. else// RLE
  347. {
  348. loader.Load(length, segmentType);
  349. }
  350. TotalRowLength += length;
  351. }
  352. loader.EndLine();
  353. }
  354. break;
  355. }
  356. case 2:
  357. {
  358. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset);
  359. for(ui32 i=0; i<sprite.height; i++)
  360. {
  361. ui32 TotalRowLength=0;
  362. while(TotalRowLength<sprite.width)
  363. {
  364. ui8 segment=FDef[currentOffset++];
  365. ui8 code = segment / 32;
  366. ui8 length = (segment & 31) + 1;
  367. if(code==7)//Raw data
  368. {
  369. loader.Load(length, FDef + currentOffset);
  370. currentOffset += length;
  371. }
  372. else//RLE
  373. {
  374. loader.Load(length, code);
  375. }
  376. TotalRowLength+=length;
  377. }
  378. loader.EndLine();
  379. }
  380. break;
  381. }
  382. case 3:
  383. {
  384. for(ui32 i=0; i<sprite.height; i++)
  385. {
  386. currentOffset = BaseOffset + read_le_u16(FDef + BaseOffset+i*2*(sprite.width/32));
  387. ui32 TotalRowLength=0;
  388. while(TotalRowLength<sprite.width)
  389. {
  390. ui8 segment = FDef[currentOffset++];
  391. ui8 code = segment / 32;
  392. ui8 length = (segment & 31) + 1;
  393. if(code==7)//Raw data
  394. {
  395. loader.Load(length, FDef + currentOffset);
  396. currentOffset += length;
  397. }
  398. else//RLE
  399. {
  400. loader.Load(length, code);
  401. }
  402. TotalRowLength += length;
  403. }
  404. loader.EndLine();
  405. }
  406. break;
  407. }
  408. default:
  409. logGlobal->error("Error: unsupported format of def file: %d", sprite.format);
  410. break;
  411. }
  412. }
  413. CDefFile::~CDefFile() = default;
  414. const std::map<size_t, size_t > CDefFile::getEntries() const
  415. {
  416. std::map<size_t, size_t > ret;
  417. for (auto & elem : offset)
  418. ret[elem.first] = elem.second.size();
  419. return ret;
  420. }
  421. /*************************************************************************
  422. * Classes for image loaders - helpers for loading from def files *
  423. *************************************************************************/
  424. SDLImageLoader::SDLImageLoader(SDLImage * Img):
  425. image(Img),
  426. lineStart(nullptr),
  427. position(nullptr)
  428. {
  429. }
  430. void SDLImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  431. {
  432. //Init image
  433. image->surf = SDL_CreateRGBSurface(0, SpriteSize.x, SpriteSize.y, 8, 0, 0, 0, 0);
  434. image->margins = Margins;
  435. image->fullSize = FullSize;
  436. //Prepare surface
  437. SDL_Palette * p = SDL_AllocPalette(SDLImage::DEFAULT_PALETTE_COLORS);
  438. SDL_SetPaletteColors(p, pal, 0, SDLImage::DEFAULT_PALETTE_COLORS);
  439. SDL_SetSurfacePalette(image->surf, p);
  440. SDL_FreePalette(p);
  441. SDL_LockSurface(image->surf);
  442. lineStart = position = (ui8*)image->surf->pixels;
  443. }
  444. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  445. {
  446. if (size)
  447. {
  448. memcpy((void *)position, data, size);
  449. position += size;
  450. }
  451. }
  452. inline void SDLImageLoader::Load(size_t size, ui8 color)
  453. {
  454. if (size)
  455. {
  456. memset((void *)position, color, size);
  457. position += size;
  458. }
  459. }
  460. inline void SDLImageLoader::EndLine()
  461. {
  462. lineStart += image->surf->pitch;
  463. position = lineStart;
  464. }
  465. SDLImageLoader::~SDLImageLoader()
  466. {
  467. SDL_UnlockSurface(image->surf);
  468. SDL_SetColorKey(image->surf, SDL_TRUE, 0);
  469. //TODO: RLE if compressed and bpp>1
  470. }
  471. /*************************************************************************
  472. * Classes for images, support loading from file and drawing on surface *
  473. *************************************************************************/
  474. IImage::IImage() = default;
  475. IImage::~IImage() = default;
  476. SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group)
  477. : surf(nullptr),
  478. margins(0, 0),
  479. fullSize(0, 0),
  480. originalPalette(nullptr)
  481. {
  482. SDLImageLoader loader(this);
  483. data->loadFrame(frame, group, loader);
  484. savePalette();
  485. }
  486. SDLImage::SDLImage(SDL_Surface * from, bool extraRef)
  487. : surf(nullptr),
  488. margins(0, 0),
  489. fullSize(0, 0),
  490. originalPalette(nullptr)
  491. {
  492. surf = from;
  493. if (surf == nullptr)
  494. return;
  495. savePalette();
  496. if (extraRef)
  497. surf->refcount++;
  498. fullSize.x = surf->w;
  499. fullSize.y = surf->h;
  500. }
  501. SDLImage::SDLImage(const JsonNode & conf)
  502. : surf(nullptr),
  503. margins(0, 0),
  504. fullSize(0, 0),
  505. originalPalette(nullptr)
  506. {
  507. std::string filename = conf["file"].String();
  508. surf = BitmapHandler::loadBitmap(filename);
  509. if(surf == nullptr)
  510. return;
  511. savePalette();
  512. const JsonNode & jsonMargins = conf["margins"];
  513. margins.x = static_cast<int>(jsonMargins["left"].Integer());
  514. margins.y = static_cast<int>(jsonMargins["top"].Integer());
  515. fullSize.x = static_cast<int>(conf["width"].Integer());
  516. fullSize.y = static_cast<int>(conf["height"].Integer());
  517. if(fullSize.x == 0)
  518. {
  519. fullSize.x = margins.x + surf->w + (int)jsonMargins["right"].Integer();
  520. }
  521. if(fullSize.y == 0)
  522. {
  523. fullSize.y = margins.y + surf->h + (int)jsonMargins["bottom"].Integer();
  524. }
  525. }
  526. SDLImage::SDLImage(std::string filename)
  527. : surf(nullptr),
  528. margins(0, 0),
  529. fullSize(0, 0),
  530. originalPalette(nullptr)
  531. {
  532. surf = BitmapHandler::loadBitmap(filename);
  533. if(surf == nullptr)
  534. {
  535. logGlobal->error("Error: failed to load image %s", filename);
  536. return;
  537. }
  538. else
  539. {
  540. savePalette();
  541. fullSize.x = surf->w;
  542. fullSize.y = surf->h;
  543. }
  544. }
  545. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  546. {
  547. if(!surf)
  548. return;
  549. Rect destRect(posX, posY, surf->w, surf->h);
  550. draw(where, &destRect, src);
  551. }
  552. void SDLImage::draw(SDL_Surface* where, SDL_Rect* dest, SDL_Rect* src, ui8 alpha) const
  553. {
  554. if (!surf)
  555. return;
  556. Rect sourceRect(0, 0, surf->w, surf->h);
  557. Point destShift(0, 0);
  558. if(src)
  559. {
  560. if(src->x < margins.x)
  561. destShift.x += margins.x - src->x;
  562. if(src->y < margins.y)
  563. destShift.y += margins.y - src->y;
  564. sourceRect = Rect(*src) & Rect(margins.x, margins.y, surf->w, surf->h);
  565. sourceRect -= margins;
  566. }
  567. else
  568. destShift = margins;
  569. Rect destRect(destShift.x, destShift.y, surf->w, surf->h);
  570. if(dest)
  571. {
  572. destRect.x += dest->x;
  573. destRect.y += dest->y;
  574. }
  575. if(surf->format->BitsPerPixel == 8)
  576. {
  577. CSDL_Ext::blit8bppAlphaTo24bpp(surf, &sourceRect, where, &destRect);
  578. }
  579. else
  580. {
  581. SDL_UpperBlit(surf, &sourceRect, where, &destRect);
  582. }
  583. }
  584. std::shared_ptr<IImage> SDLImage::scaleFast(float scale) const
  585. {
  586. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, (int)(surf->w * scale), (int)(surf->h * scale));
  587. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  588. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  589. else if(scaled->format && scaled->format->Amask)
  590. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  591. else
  592. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  593. SDLImage * ret = new SDLImage(scaled, false);
  594. ret->fullSize.x = (int) round((float)fullSize.x * scale);
  595. ret->fullSize.y = (int) round((float)fullSize.y * scale);
  596. ret->margins.x = (int) round((float)margins.x * scale);
  597. ret->margins.y = (int) round((float)margins.y * scale);
  598. return std::shared_ptr<IImage>(ret);
  599. }
  600. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  601. {
  602. SDL_SaveBMP(surf, path.string().c_str());
  603. }
  604. void SDLImage::playerColored(PlayerColor player)
  605. {
  606. graphics->blueToPlayersAdv(surf, player);
  607. }
  608. void SDLImage::setFlagColor(PlayerColor player)
  609. {
  610. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  611. CSDL_Ext::setPlayerColor(surf, player);
  612. }
  613. int SDLImage::width() const
  614. {
  615. return fullSize.x;
  616. }
  617. int SDLImage::height() const
  618. {
  619. return fullSize.y;
  620. }
  621. void SDLImage::horizontalFlip()
  622. {
  623. margins.y = fullSize.y - surf->h - margins.y;
  624. //todo: modify in-place
  625. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  626. SDL_FreeSurface(surf);
  627. surf = flipped;
  628. }
  629. void SDLImage::verticalFlip()
  630. {
  631. margins.x = fullSize.x - surf->w - margins.x;
  632. //todo: modify in-place
  633. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  634. SDL_FreeSurface(surf);
  635. surf = flipped;
  636. }
  637. // Keep the original palette, in order to do color switching operation
  638. void SDLImage::savePalette()
  639. {
  640. // For some images that don't have palette, skip this
  641. if(surf->format->palette == nullptr)
  642. return;
  643. if(originalPalette == nullptr)
  644. originalPalette = SDL_AllocPalette(DEFAULT_PALETTE_COLORS);
  645. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, DEFAULT_PALETTE_COLORS);
  646. }
  647. void SDLImage::shiftPalette(int from, int howMany)
  648. {
  649. //works with at most 16 colors, if needed more -> increase values
  650. assert(howMany < 16);
  651. if(surf->format->palette)
  652. {
  653. SDL_Color palette[16];
  654. for(int i=0; i<howMany; ++i)
  655. {
  656. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  657. }
  658. SDL_SetColors(surf, palette, from, howMany);
  659. }
  660. }
  661. void SDLImage::adjustPalette(const ColorShifter * shifter)
  662. {
  663. if(originalPalette == nullptr)
  664. return;
  665. SDL_Palette* palette = surf->format->palette;
  666. // Note: here we skip the first 8 colors in the palette that predefined in H3Palette
  667. for(int i = 8; i < palette->ncolors; i++)
  668. {
  669. palette->colors[i] = shifter->shiftColor(originalPalette->colors[i]);
  670. }
  671. }
  672. void SDLImage::resetPalette()
  673. {
  674. if(originalPalette == nullptr)
  675. return;
  676. // Always keept the original palette not changed, copy a new palette to assign to surface
  677. SDL_SetPaletteColors(surf->format->palette, originalPalette->colors, 0, originalPalette->ncolors);
  678. }
  679. void SDLImage::setBorderPallete(const IImage::BorderPallete & borderPallete)
  680. {
  681. if(surf->format->palette)
  682. {
  683. SDL_SetColors(surf, const_cast<SDL_Color *>(borderPallete.data()), 5, 3);
  684. }
  685. }
  686. SDLImage::~SDLImage()
  687. {
  688. SDL_FreeSurface(surf);
  689. if(originalPalette != nullptr)
  690. {
  691. SDL_FreePalette(originalPalette);
  692. originalPalette = nullptr;
  693. }
  694. }
  695. std::shared_ptr<IImage> CAnimation::getFromExtraDef(std::string filename)
  696. {
  697. size_t pos = filename.find(':');
  698. if (pos == -1)
  699. return nullptr;
  700. CAnimation anim(filename.substr(0, pos));
  701. pos++;
  702. size_t frame = atoi(filename.c_str()+pos);
  703. size_t group = 0;
  704. pos = filename.find(':', pos);
  705. if (pos != -1)
  706. {
  707. pos++;
  708. group = frame;
  709. frame = atoi(filename.c_str()+pos);
  710. }
  711. anim.load(frame ,group);
  712. auto ret = anim.images[group][frame];
  713. anim.images.clear();
  714. return ret;
  715. }
  716. bool CAnimation::loadFrame(size_t frame, size_t group)
  717. {
  718. if(size(group) <= frame)
  719. {
  720. printError(frame, group, "LoadFrame");
  721. return false;
  722. }
  723. auto image = getImage(frame, group, false);
  724. if(image)
  725. {
  726. return true;
  727. }
  728. //try to get image from def
  729. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  730. {
  731. if(defFile)
  732. {
  733. auto frameList = defFile->getEntries();
  734. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  735. {
  736. images[group][frame] = std::make_shared<SDLImage>(defFile.get(), frame, group);
  737. return true;
  738. }
  739. }
  740. // still here? image is missing
  741. printError(frame, group, "LoadFrame");
  742. images[group][frame] = std::make_shared<SDLImage>("DEFAULT");
  743. }
  744. else //load from separate file
  745. {
  746. auto img = getFromExtraDef(source[group][frame]["file"].String());
  747. if(!img)
  748. img = std::make_shared<SDLImage>(source[group][frame]);
  749. images[group][frame] = img;
  750. return true;
  751. }
  752. return false;
  753. }
  754. bool CAnimation::unloadFrame(size_t frame, size_t group)
  755. {
  756. auto image = getImage(frame, group, false);
  757. if(image)
  758. {
  759. images[group].erase(frame);
  760. if(images[group].empty())
  761. images.erase(group);
  762. return true;
  763. }
  764. return false;
  765. }
  766. void CAnimation::initFromJson(const JsonNode & config)
  767. {
  768. std::string basepath;
  769. basepath = config["basepath"].String();
  770. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  771. base["margins"] = config["margins"];
  772. base["width"] = config["width"];
  773. base["height"] = config["height"];
  774. for(const JsonNode & group : config["sequences"].Vector())
  775. {
  776. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  777. source[groupID].clear();
  778. for(const JsonNode & frame : group["frames"].Vector())
  779. {
  780. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  781. JsonUtils::inherit(toAdd, base);
  782. toAdd["file"].String() = basepath + frame.String();
  783. source[groupID].push_back(toAdd);
  784. }
  785. }
  786. for(const JsonNode & node : config["images"].Vector())
  787. {
  788. size_t group = node["group"].Integer();
  789. size_t frame = node["frame"].Integer();
  790. if (source[group].size() <= frame)
  791. source[group].resize(frame+1);
  792. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  793. JsonUtils::inherit(toAdd, base);
  794. toAdd["file"].String() = basepath + node["file"].String();
  795. source[group][frame] = toAdd;
  796. }
  797. }
  798. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  799. {
  800. if(images.empty())
  801. {
  802. logGlobal->error("Nothing to export, animation is empty");
  803. return;
  804. }
  805. boost::filesystem::path actualPath = path / "SPRITES" / name;
  806. boost::filesystem::create_directories(actualPath);
  807. size_t counter = 0;
  808. for(const auto & groupPair : images)
  809. {
  810. size_t group = groupPair.first;
  811. for(const auto & imagePair : groupPair.second)
  812. {
  813. size_t frame = imagePair.first;
  814. const auto img = imagePair.second;
  815. boost::format fmt("%d_%d.bmp");
  816. fmt % group % frame;
  817. img->exportBitmap(actualPath / fmt.str());
  818. counter++;
  819. }
  820. }
  821. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  822. }
  823. void CAnimation::init()
  824. {
  825. if(defFile)
  826. {
  827. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  828. for (auto & defEntry : defEntries)
  829. source[defEntry.first].resize(defEntry.second);
  830. }
  831. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  832. if (vstd::contains(graphics->imageLists, resID.getName()))
  833. initFromJson(graphics->imageLists[resID.getName()]);
  834. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  835. for(auto & loader : configList)
  836. {
  837. auto stream = loader->load(resID);
  838. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  839. stream->read(textData.get(), stream->getSize());
  840. const JsonNode config((char*)textData.get(), stream->getSize());
  841. initFromJson(config);
  842. }
  843. }
  844. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  845. {
  846. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  847. }
  848. CAnimation::CAnimation(std::string Name):
  849. name(Name),
  850. preloaded(false),
  851. defFile()
  852. {
  853. size_t dotPos = name.find_last_of('.');
  854. if ( dotPos!=-1 )
  855. name.erase(dotPos);
  856. std::transform(name.begin(), name.end(), name.begin(), toupper);
  857. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  858. if(CResourceHandler::get()->existsResource(resource))
  859. defFile = std::make_shared<CDefFile>(name);
  860. init();
  861. if(source.empty())
  862. logAnim->error("Animation %s failed to load", Name);
  863. }
  864. CAnimation::CAnimation():
  865. name(""),
  866. preloaded(false),
  867. defFile()
  868. {
  869. init();
  870. }
  871. CAnimation::~CAnimation() = default;
  872. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  873. {
  874. if(!source.count(sourceGroup))
  875. {
  876. logAnim->error("Group %d missing in %s", sourceGroup, name);
  877. return;
  878. }
  879. if(source[sourceGroup].size() <= sourceFrame)
  880. {
  881. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name);
  882. return;
  883. }
  884. //todo: clone actual loaded Image object
  885. JsonNode clone(source[sourceGroup][sourceFrame]);
  886. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  887. {
  888. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  889. clone["file"].String() = temp;
  890. }
  891. source[targetGroup].push_back(clone);
  892. size_t index = source[targetGroup].size() - 1;
  893. if(preloaded)
  894. load(index, targetGroup);
  895. }
  896. void CAnimation::shiftColor(const ColorShifter * shifter)
  897. {
  898. for(auto groupIter = images.begin(); groupIter != images.end(); groupIter++)
  899. {
  900. for(auto frameIter = groupIter->second.begin(); frameIter != groupIter->second.end(); frameIter++)
  901. {
  902. std::shared_ptr<IImage> image = frameIter->second;
  903. image->adjustPalette(shifter);
  904. }
  905. }
  906. }
  907. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  908. {
  909. if (source[group].size() <= frame)
  910. source[group].resize(frame+1);
  911. source[group][frame]["file"].String() = filename;
  912. //FIXME: update image if already loaded
  913. }
  914. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  915. {
  916. auto groupIter = images.find(group);
  917. if (groupIter != images.end())
  918. {
  919. auto imageIter = groupIter->second.find(frame);
  920. if (imageIter != groupIter->second.end())
  921. return imageIter->second;
  922. }
  923. if (verbose)
  924. printError(frame, group, "GetImage");
  925. return nullptr;
  926. }
  927. void CAnimation::load()
  928. {
  929. for (auto & elem : source)
  930. for (size_t image=0; image < elem.second.size(); image++)
  931. loadFrame(image, elem.first);
  932. }
  933. void CAnimation::unload()
  934. {
  935. for (auto & elem : source)
  936. for (size_t image=0; image < elem.second.size(); image++)
  937. unloadFrame(image, elem.first);
  938. }
  939. void CAnimation::preload()
  940. {
  941. if(!preloaded)
  942. {
  943. preloaded = true;
  944. load();
  945. }
  946. }
  947. void CAnimation::loadGroup(size_t group)
  948. {
  949. if (vstd::contains(source, group))
  950. for (size_t image=0; image < source[group].size(); image++)
  951. loadFrame(image, group);
  952. }
  953. void CAnimation::unloadGroup(size_t group)
  954. {
  955. if (vstd::contains(source, group))
  956. for (size_t image=0; image < source[group].size(); image++)
  957. unloadFrame(image, group);
  958. }
  959. void CAnimation::load(size_t frame, size_t group)
  960. {
  961. loadFrame(frame, group);
  962. }
  963. void CAnimation::unload(size_t frame, size_t group)
  964. {
  965. unloadFrame(frame, group);
  966. }
  967. size_t CAnimation::size(size_t group) const
  968. {
  969. auto iter = source.find(group);
  970. if (iter != source.end())
  971. return iter->second.size();
  972. return 0;
  973. }
  974. void CAnimation::horizontalFlip()
  975. {
  976. for(auto & group : images)
  977. for(auto & image : group.second)
  978. image.second->horizontalFlip();
  979. }
  980. void CAnimation::verticalFlip()
  981. {
  982. for(auto & group : images)
  983. for(auto & image : group.second)
  984. image.second->verticalFlip();
  985. }
  986. void CAnimation::playerColored(PlayerColor player)
  987. {
  988. for(auto & group : images)
  989. for(auto & image : group.second)
  990. image.second->playerColored(player);
  991. }
  992. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  993. {
  994. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  995. {
  996. duplicateImage(sourceGroup, frame, targetGroup);
  997. auto image = getImage(frame, targetGroup);
  998. image->verticalFlip();
  999. }
  1000. }
  1001. float CFadeAnimation::initialCounter() const
  1002. {
  1003. if (fadingMode == EMode::OUT)
  1004. return 1.0f;
  1005. return 0.0f;
  1006. }
  1007. void CFadeAnimation::update()
  1008. {
  1009. if (!fading)
  1010. return;
  1011. if (fadingMode == EMode::OUT)
  1012. fadingCounter -= delta;
  1013. else
  1014. fadingCounter += delta;
  1015. if (isFinished())
  1016. {
  1017. fading = false;
  1018. if (shouldFreeSurface)
  1019. {
  1020. SDL_FreeSurface(fadingSurface);
  1021. fadingSurface = nullptr;
  1022. }
  1023. }
  1024. }
  1025. bool CFadeAnimation::isFinished() const
  1026. {
  1027. if (fadingMode == EMode::OUT)
  1028. return fadingCounter <= 0.0f;
  1029. return fadingCounter >= 1.0f;
  1030. }
  1031. CFadeAnimation::CFadeAnimation()
  1032. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  1033. fadingMode(EMode::NONE)
  1034. {
  1035. }
  1036. CFadeAnimation::~CFadeAnimation()
  1037. {
  1038. if (fadingSurface && shouldFreeSurface)
  1039. SDL_FreeSurface(fadingSurface);
  1040. }
  1041. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  1042. {
  1043. if (fading)
  1044. {
  1045. // in that case, immediately finish the previous fade
  1046. // (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))
  1047. logGlobal->warn("Tried to init fading animation that is already running.");
  1048. if (fadingSurface && shouldFreeSurface)
  1049. SDL_FreeSurface(fadingSurface);
  1050. }
  1051. if (animDelta <= 0.0f)
  1052. {
  1053. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  1054. animDelta = DEFAULT_DELTA;
  1055. }
  1056. if (sourceSurface)
  1057. fadingSurface = sourceSurface;
  1058. delta = animDelta;
  1059. fadingMode = mode;
  1060. fadingCounter = initialCounter();
  1061. fading = true;
  1062. shouldFreeSurface = freeSurfaceAtEnd;
  1063. }
  1064. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1065. {
  1066. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1067. {
  1068. fading = false;
  1069. return;
  1070. }
  1071. CSDL_Ext::setAlpha(fadingSurface, (int)(fadingCounter * 255));
  1072. SDL_BlitSurface(fadingSurface, const_cast<SDL_Rect *>(sourceRect), targetSurface, destRect); //FIXME
  1073. CSDL_Ext::setAlpha(fadingSurface, 255);
  1074. }