CAnimation.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  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_Extensions.h"
  13. #include "SDL_Pixels.h"
  14. #include "ColorFilter.h"
  15. #include "../CBitmapHandler.h"
  16. #include "../Graphics.h"
  17. #include "../../lib/filesystem/Filesystem.h"
  18. #include "../../lib/filesystem/ISimpleResourceLoader.h"
  19. #include "../../lib/JsonNode.h"
  20. #include "../../lib/CRandomGenerator.h"
  21. #include "../../lib/vcmi_endian.h"
  22. #include <SDL_surface.h>
  23. class SDLImageLoader;
  24. typedef std::map <size_t, std::vector <JsonNode> > source_map;
  25. typedef std::map<size_t, IImage* > image_map;
  26. typedef std::map<size_t, image_map > group_map;
  27. /// Class for def loading
  28. /// After loading will store general info (palette and frame offsets) and pointer to file itself
  29. class CDefFile
  30. {
  31. private:
  32. PACKED_STRUCT_BEGIN
  33. struct SSpriteDef
  34. {
  35. ui32 size;
  36. ui32 format; /// format in which pixel data is stored
  37. ui32 fullWidth; /// full width and height of frame, including borders
  38. ui32 fullHeight;
  39. ui32 width; /// width and height of pixel data, borders excluded
  40. ui32 height;
  41. si32 leftMargin;
  42. si32 topMargin;
  43. } PACKED_STRUCT_END;
  44. //offset[group][frame] - offset of frame data in file
  45. std::map<size_t, std::vector <size_t> > offset;
  46. std::unique_ptr<ui8[]> data;
  47. std::unique_ptr<SDL_Color[]> palette;
  48. public:
  49. CDefFile(std::string Name);
  50. ~CDefFile();
  51. //load frame as SDL_Surface
  52. template<class ImageLoader>
  53. void loadFrame(size_t frame, size_t group, ImageLoader &loader) const;
  54. const std::map<size_t, size_t> getEntries() const;
  55. };
  56. /*
  57. * Wrapper around SDL_Surface
  58. */
  59. class SDLImage : public IImage
  60. {
  61. public:
  62. const static int DEFAULT_PALETTE_COLORS = 256;
  63. //Surface without empty borders
  64. SDL_Surface * surf;
  65. //size of left and top borders
  66. Point margins;
  67. //total size including borders
  68. Point fullSize;
  69. public:
  70. //Load image from def file
  71. SDLImage(CDefFile *data, size_t frame, size_t group=0);
  72. //Load from bitmap file
  73. SDLImage(std::string filename);
  74. SDLImage(const JsonNode & conf);
  75. //Create using existing surface, extraRef will increase refcount on SDL_Surface
  76. SDLImage(SDL_Surface * from, bool extraRef);
  77. ~SDLImage();
  78. // Keep the original palette, in order to do color switching operation
  79. void savePalette();
  80. void draw(SDL_Surface * where, int posX=0, int posY=0, const Rect *src=nullptr) const override;
  81. void draw(SDL_Surface * where, const Rect * dest, const Rect * src) const override;
  82. std::shared_ptr<IImage> scaleFast(const Point & size) const override;
  83. void exportBitmap(const boost::filesystem::path & path) const override;
  84. void playerColored(PlayerColor player) override;
  85. void setFlagColor(PlayerColor player) override;
  86. bool isTransparent(const Point & coords) const override;
  87. Point dimensions() const override;
  88. void horizontalFlip() override;
  89. void verticalFlip() override;
  90. void shiftPalette(int from, int howMany) override;
  91. void adjustPalette(const ColorFilter & shifter, size_t colorsToSkip) override;
  92. void resetPalette(int colorID) override;
  93. void resetPalette() override;
  94. void setAlpha(uint8_t value) override;
  95. void setSpecialPallete(const SpecialPalette & SpecialPalette) override;
  96. friend class SDLImageLoader;
  97. private:
  98. SDL_Palette * originalPalette;
  99. };
  100. class SDLImageLoader
  101. {
  102. SDLImage * image;
  103. ui8 * lineStart;
  104. ui8 * position;
  105. public:
  106. //load size raw pixels from data
  107. inline void Load(size_t size, const ui8 * data);
  108. //set size pixels to color
  109. inline void Load(size_t size, ui8 color=0);
  110. inline void EndLine();
  111. //init image with these sizes and palette
  112. inline void init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal);
  113. SDLImageLoader(SDLImage * Img);
  114. ~SDLImageLoader();
  115. };
  116. std::shared_ptr<IImage> IImage::createFromFile( const std::string & path )
  117. {
  118. return std::shared_ptr<IImage>(new SDLImage(path));
  119. }
  120. std::shared_ptr<IImage> IImage::createFromSurface( SDL_Surface * source )
  121. {
  122. return std::shared_ptr<IImage>(new SDLImage(source, true));
  123. }
  124. // Extremely simple file cache. TODO: smarter, more general solution
  125. class CFileCache
  126. {
  127. static const int cacheSize = 50; //Max number of cached files
  128. struct FileData
  129. {
  130. ResourceID name;
  131. size_t size;
  132. std::unique_ptr<ui8[]> data;
  133. std::unique_ptr<ui8[]> getCopy()
  134. {
  135. auto ret = std::unique_ptr<ui8[]>(new ui8[size]);
  136. std::copy(data.get(), data.get() + size, ret.get());
  137. return ret;
  138. }
  139. FileData(ResourceID name_, size_t size_, std::unique_ptr<ui8[]> data_):
  140. name{std::move(name_)},
  141. size{size_},
  142. data{std::move(data_)}
  143. {}
  144. };
  145. std::deque<FileData> cache;
  146. public:
  147. std::unique_ptr<ui8[]> getCachedFile(ResourceID rid)
  148. {
  149. for(auto & file : cache)
  150. {
  151. if (file.name == rid)
  152. return file.getCopy();
  153. }
  154. // Still here? Cache miss
  155. if (cache.size() > cacheSize)
  156. cache.pop_front();
  157. auto data = CResourceHandler::get()->load(rid)->readAll();
  158. cache.emplace_back(std::move(rid), data.second, std::move(data.first));
  159. return cache.back().getCopy();
  160. }
  161. };
  162. enum class DefType : uint32_t
  163. {
  164. SPELL = 0x40,
  165. SPRITE = 0x41,
  166. CREATURE = 0x42,
  167. MAP = 0x43,
  168. MAP_HERO = 0x44,
  169. TERRAIN = 0x45,
  170. CURSOR = 0x46,
  171. INTERFACE = 0x47,
  172. SPRITE_FRAME = 0x48,
  173. BATTLE_HERO = 0x49
  174. };
  175. static CFileCache animationCache;
  176. /*************************************************************************
  177. * DefFile, class used for def loading *
  178. *************************************************************************/
  179. bool operator== (const SDL_Color & lhs, const SDL_Color & rhs)
  180. {
  181. return (lhs.a == rhs.a) && (lhs.b == rhs.b) &&(lhs.g == rhs.g) &&(lhs.r == rhs.r);
  182. }
  183. CDefFile::CDefFile(std::string Name):
  184. data(nullptr),
  185. palette(nullptr)
  186. {
  187. //First 8 colors in def palette used for transparency
  188. static SDL_Color H3Palette[8] =
  189. {
  190. { 0, 0, 0, 0},// transparency ( used in most images )
  191. { 0, 0, 0, 64},// shadow border ( used in battle, adventure map def's )
  192. { 0, 0, 0, 64},// shadow border ( used in fog-of-war def's )
  193. { 0, 0, 0, 128},// shadow body ( used in fog-of-war def's )
  194. { 0, 0, 0, 128},// shadow body ( used in battle, adventure map def's )
  195. { 0, 0, 0, 0},// selection ( used in battle def's )
  196. { 0, 0, 0, 128},// shadow body below selection ( used in battle def's )
  197. { 0, 0, 0, 64} // shadow border below selection ( used in battle def's )
  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. int IImage::width() const
  477. {
  478. return dimensions().x;
  479. }
  480. int IImage::height() const
  481. {
  482. return dimensions().y;
  483. }
  484. SDLImage::SDLImage(CDefFile * data, size_t frame, size_t group)
  485. : surf(nullptr),
  486. margins(0, 0),
  487. fullSize(0, 0),
  488. originalPalette(nullptr)
  489. {
  490. SDLImageLoader loader(this);
  491. data->loadFrame(frame, group, loader);
  492. savePalette();
  493. }
  494. SDLImage::SDLImage(SDL_Surface * from, bool extraRef)
  495. : surf(nullptr),
  496. margins(0, 0),
  497. fullSize(0, 0),
  498. originalPalette(nullptr)
  499. {
  500. surf = from;
  501. if (surf == nullptr)
  502. return;
  503. savePalette();
  504. if (extraRef)
  505. surf->refcount++;
  506. fullSize.x = surf->w;
  507. fullSize.y = surf->h;
  508. }
  509. SDLImage::SDLImage(const JsonNode & conf)
  510. : surf(nullptr),
  511. margins(0, 0),
  512. fullSize(0, 0),
  513. originalPalette(nullptr)
  514. {
  515. std::string filename = conf["file"].String();
  516. surf = BitmapHandler::loadBitmap(filename);
  517. if(surf == nullptr)
  518. return;
  519. savePalette();
  520. const JsonNode & jsonMargins = conf["margins"];
  521. margins.x = static_cast<int>(jsonMargins["left"].Integer());
  522. margins.y = static_cast<int>(jsonMargins["top"].Integer());
  523. fullSize.x = static_cast<int>(conf["width"].Integer());
  524. fullSize.y = static_cast<int>(conf["height"].Integer());
  525. if(fullSize.x == 0)
  526. {
  527. fullSize.x = margins.x + surf->w + (int)jsonMargins["right"].Integer();
  528. }
  529. if(fullSize.y == 0)
  530. {
  531. fullSize.y = margins.y + surf->h + (int)jsonMargins["bottom"].Integer();
  532. }
  533. }
  534. SDLImage::SDLImage(std::string filename)
  535. : surf(nullptr),
  536. margins(0, 0),
  537. fullSize(0, 0),
  538. originalPalette(nullptr)
  539. {
  540. surf = BitmapHandler::loadBitmap(filename);
  541. if(surf == nullptr)
  542. {
  543. logGlobal->error("Error: failed to load image %s", filename);
  544. return;
  545. }
  546. else
  547. {
  548. savePalette();
  549. fullSize.x = surf->w;
  550. fullSize.y = surf->h;
  551. }
  552. }
  553. void SDLImage::draw(SDL_Surface *where, int posX, int posY, const Rect *src) const
  554. {
  555. if(!surf)
  556. return;
  557. Rect destRect(posX, posY, surf->w, surf->h);
  558. draw(where, &destRect, src);
  559. }
  560. void SDLImage::draw(SDL_Surface* where, const Rect * dest, const Rect* src) const
  561. {
  562. if (!surf)
  563. return;
  564. Rect sourceRect(0, 0, surf->w, surf->h);
  565. Point destShift(0, 0);
  566. if(src)
  567. {
  568. if(src->x < margins.x)
  569. destShift.x += margins.x - src->x;
  570. if(src->y < margins.y)
  571. destShift.y += margins.y - src->y;
  572. sourceRect = Rect(*src).intersect(Rect(margins.x, margins.y, surf->w, surf->h));
  573. sourceRect -= margins;
  574. }
  575. else
  576. destShift = margins;
  577. if(dest)
  578. destShift += dest->topLeft();
  579. uint8_t perSurfaceAlpha;
  580. if (SDL_GetSurfaceAlphaMod(surf, &perSurfaceAlpha) != 0)
  581. logGlobal->error("SDL_GetSurfaceAlphaMod faied! %s", SDL_GetError());
  582. if(surf->format->BitsPerPixel == 8 && perSurfaceAlpha == SDL_ALPHA_OPAQUE)
  583. {
  584. CSDL_Ext::blit8bppAlphaTo24bpp(surf, sourceRect, where, destShift);
  585. }
  586. else
  587. {
  588. CSDL_Ext::blitSurface(surf, sourceRect, where, destShift);
  589. }
  590. }
  591. std::shared_ptr<IImage> SDLImage::scaleFast(const Point & size) const
  592. {
  593. float scaleX = float(size.x) / width();
  594. float scaleY = float(size.y) / height();
  595. auto scaled = CSDL_Ext::scaleSurfaceFast(surf, (int)(surf->w * scaleX), (int)(surf->h * scaleY));
  596. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  597. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  598. else if(scaled->format && scaled->format->Amask)
  599. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  600. else
  601. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  602. SDLImage * ret = new SDLImage(scaled, false);
  603. ret->fullSize.x = (int) round((float)fullSize.x * scaleX);
  604. ret->fullSize.y = (int) round((float)fullSize.y * scaleY);
  605. ret->margins.x = (int) round((float)margins.x * scaleX);
  606. ret->margins.y = (int) round((float)margins.y * scaleY);
  607. return std::shared_ptr<IImage>(ret);
  608. }
  609. void SDLImage::exportBitmap(const boost::filesystem::path& path) const
  610. {
  611. SDL_SaveBMP(surf, path.string().c_str());
  612. }
  613. void SDLImage::playerColored(PlayerColor player)
  614. {
  615. graphics->blueToPlayersAdv(surf, player);
  616. }
  617. void SDLImage::setAlpha(uint8_t value)
  618. {
  619. CSDL_Ext::setAlpha (surf, value);
  620. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_BLEND);
  621. }
  622. void SDLImage::setFlagColor(PlayerColor player)
  623. {
  624. if(player < PlayerColor::PLAYER_LIMIT || player==PlayerColor::NEUTRAL)
  625. CSDL_Ext::setPlayerColor(surf, player);
  626. }
  627. bool SDLImage::isTransparent(const Point & coords) const
  628. {
  629. return CSDL_Ext::isTransparent(surf, coords.x, coords.y);
  630. }
  631. Point SDLImage::dimensions() const
  632. {
  633. return fullSize;
  634. }
  635. void SDLImage::horizontalFlip()
  636. {
  637. margins.y = fullSize.y - surf->h - margins.y;
  638. //todo: modify in-place
  639. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  640. SDL_FreeSurface(surf);
  641. surf = flipped;
  642. }
  643. void SDLImage::verticalFlip()
  644. {
  645. margins.x = fullSize.x - surf->w - margins.x;
  646. //todo: modify in-place
  647. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  648. SDL_FreeSurface(surf);
  649. surf = flipped;
  650. }
  651. // Keep the original palette, in order to do color switching operation
  652. void SDLImage::savePalette()
  653. {
  654. // For some images that don't have palette, skip this
  655. if(surf->format->palette == nullptr)
  656. return;
  657. if(originalPalette == nullptr)
  658. originalPalette = SDL_AllocPalette(DEFAULT_PALETTE_COLORS);
  659. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, DEFAULT_PALETTE_COLORS);
  660. }
  661. void SDLImage::shiftPalette(int from, int howMany)
  662. {
  663. //works with at most 16 colors, if needed more -> increase values
  664. assert(howMany < 16);
  665. if(surf->format->palette)
  666. {
  667. SDL_Color palette[16];
  668. for(int i=0; i<howMany; ++i)
  669. {
  670. palette[(i+1)%howMany] = surf->format->palette->colors[from + i];
  671. }
  672. CSDL_Ext::setColors(surf, palette, from, howMany);
  673. }
  674. }
  675. void SDLImage::adjustPalette(const ColorFilter & shifter, size_t colorsToSkip)
  676. {
  677. if(originalPalette == nullptr)
  678. return;
  679. SDL_Palette* palette = surf->format->palette;
  680. // Note: here we skip first colors in the palette that are predefined in H3 images
  681. for(int i = colorsToSkip; i < palette->ncolors; i++)
  682. {
  683. palette->colors[i] = shifter.shiftColor(originalPalette->colors[i]);
  684. }
  685. }
  686. void SDLImage::resetPalette()
  687. {
  688. if(originalPalette == nullptr)
  689. return;
  690. // Always keept the original palette not changed, copy a new palette to assign to surface
  691. SDL_SetPaletteColors(surf->format->palette, originalPalette->colors, 0, originalPalette->ncolors);
  692. }
  693. void SDLImage::resetPalette( int colorID )
  694. {
  695. if(originalPalette == nullptr)
  696. return;
  697. // Always keept the original palette not changed, copy a new palette to assign to surface
  698. SDL_SetPaletteColors(surf->format->palette, originalPalette->colors + colorID, colorID, 1);
  699. }
  700. void SDLImage::setSpecialPallete(const IImage::SpecialPalette & SpecialPalette)
  701. {
  702. if(surf->format->palette)
  703. {
  704. CSDL_Ext::setColors(surf, const_cast<SDL_Color *>(SpecialPalette.data()), 1, 7);
  705. }
  706. }
  707. SDLImage::~SDLImage()
  708. {
  709. SDL_FreeSurface(surf);
  710. if(originalPalette != nullptr)
  711. {
  712. SDL_FreePalette(originalPalette);
  713. originalPalette = nullptr;
  714. }
  715. }
  716. std::shared_ptr<IImage> CAnimation::getFromExtraDef(std::string filename)
  717. {
  718. size_t pos = filename.find(':');
  719. if (pos == -1)
  720. return nullptr;
  721. CAnimation anim(filename.substr(0, pos));
  722. pos++;
  723. size_t frame = atoi(filename.c_str()+pos);
  724. size_t group = 0;
  725. pos = filename.find(':', pos);
  726. if (pos != -1)
  727. {
  728. pos++;
  729. group = frame;
  730. frame = atoi(filename.c_str()+pos);
  731. }
  732. anim.load(frame ,group);
  733. auto ret = anim.images[group][frame];
  734. anim.images.clear();
  735. return ret;
  736. }
  737. bool CAnimation::loadFrame(size_t frame, size_t group)
  738. {
  739. if(size(group) <= frame)
  740. {
  741. printError(frame, group, "LoadFrame");
  742. return false;
  743. }
  744. auto image = getImage(frame, group, false);
  745. if(image)
  746. {
  747. return true;
  748. }
  749. //try to get image from def
  750. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  751. {
  752. if(defFile)
  753. {
  754. auto frameList = defFile->getEntries();
  755. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  756. {
  757. images[group][frame] = std::make_shared<SDLImage>(defFile.get(), frame, group);
  758. return true;
  759. }
  760. }
  761. // still here? image is missing
  762. printError(frame, group, "LoadFrame");
  763. images[group][frame] = std::make_shared<SDLImage>("DEFAULT");
  764. }
  765. else //load from separate file
  766. {
  767. auto img = getFromExtraDef(source[group][frame]["file"].String());
  768. if(!img)
  769. img = std::make_shared<SDLImage>(source[group][frame]);
  770. images[group][frame] = img;
  771. return true;
  772. }
  773. return false;
  774. }
  775. bool CAnimation::unloadFrame(size_t frame, size_t group)
  776. {
  777. auto image = getImage(frame, group, false);
  778. if(image)
  779. {
  780. images[group].erase(frame);
  781. if(images[group].empty())
  782. images.erase(group);
  783. return true;
  784. }
  785. return false;
  786. }
  787. void CAnimation::initFromJson(const JsonNode & config)
  788. {
  789. std::string basepath;
  790. basepath = config["basepath"].String();
  791. JsonNode base(JsonNode::JsonType::DATA_STRUCT);
  792. base["margins"] = config["margins"];
  793. base["width"] = config["width"];
  794. base["height"] = config["height"];
  795. for(const JsonNode & group : config["sequences"].Vector())
  796. {
  797. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  798. source[groupID].clear();
  799. for(const JsonNode & frame : group["frames"].Vector())
  800. {
  801. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  802. JsonUtils::inherit(toAdd, base);
  803. toAdd["file"].String() = basepath + frame.String();
  804. source[groupID].push_back(toAdd);
  805. }
  806. }
  807. for(const JsonNode & node : config["images"].Vector())
  808. {
  809. size_t group = node["group"].Integer();
  810. size_t frame = node["frame"].Integer();
  811. if (source[group].size() <= frame)
  812. source[group].resize(frame+1);
  813. JsonNode toAdd(JsonNode::JsonType::DATA_STRUCT);
  814. JsonUtils::inherit(toAdd, base);
  815. toAdd["file"].String() = basepath + node["file"].String();
  816. source[group][frame] = toAdd;
  817. }
  818. }
  819. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  820. {
  821. if(images.empty())
  822. {
  823. logGlobal->error("Nothing to export, animation is empty");
  824. return;
  825. }
  826. boost::filesystem::path actualPath = path / "SPRITES" / name;
  827. boost::filesystem::create_directories(actualPath);
  828. size_t counter = 0;
  829. for(const auto & groupPair : images)
  830. {
  831. size_t group = groupPair.first;
  832. for(const auto & imagePair : groupPair.second)
  833. {
  834. size_t frame = imagePair.first;
  835. const auto img = imagePair.second;
  836. boost::format fmt("%d_%d.bmp");
  837. fmt % group % frame;
  838. img->exportBitmap(actualPath / fmt.str());
  839. counter++;
  840. }
  841. }
  842. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  843. }
  844. void CAnimation::init()
  845. {
  846. if(defFile)
  847. {
  848. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  849. for (auto & defEntry : defEntries)
  850. source[defEntry.first].resize(defEntry.second);
  851. }
  852. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  853. if (vstd::contains(graphics->imageLists, resID.getName()))
  854. initFromJson(graphics->imageLists[resID.getName()]);
  855. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  856. for(auto & loader : configList)
  857. {
  858. auto stream = loader->load(resID);
  859. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  860. stream->read(textData.get(), stream->getSize());
  861. const JsonNode config((char*)textData.get(), stream->getSize());
  862. initFromJson(config);
  863. }
  864. }
  865. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  866. {
  867. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name, group, frame);
  868. }
  869. CAnimation::CAnimation(std::string Name):
  870. name(Name),
  871. preloaded(false),
  872. defFile()
  873. {
  874. size_t dotPos = name.find_last_of('.');
  875. if ( dotPos!=-1 )
  876. name.erase(dotPos);
  877. std::transform(name.begin(), name.end(), name.begin(), toupper);
  878. ResourceID resource(std::string("SPRITES/") + name, EResType::ANIMATION);
  879. if(CResourceHandler::get()->existsResource(resource))
  880. defFile = std::make_shared<CDefFile>(name);
  881. init();
  882. if(source.empty())
  883. logAnim->error("Animation %s failed to load", Name);
  884. }
  885. CAnimation::CAnimation():
  886. name(""),
  887. preloaded(false),
  888. defFile()
  889. {
  890. init();
  891. }
  892. CAnimation::~CAnimation() = default;
  893. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  894. {
  895. if(!source.count(sourceGroup))
  896. {
  897. logAnim->error("Group %d missing in %s", sourceGroup, name);
  898. return;
  899. }
  900. if(source[sourceGroup].size() <= sourceFrame)
  901. {
  902. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name);
  903. return;
  904. }
  905. //todo: clone actual loaded Image object
  906. JsonNode clone(source[sourceGroup][sourceFrame]);
  907. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  908. {
  909. std::string temp = name+":"+boost::lexical_cast<std::string>(sourceGroup)+":"+boost::lexical_cast<std::string>(sourceFrame);
  910. clone["file"].String() = temp;
  911. }
  912. source[targetGroup].push_back(clone);
  913. size_t index = source[targetGroup].size() - 1;
  914. if(preloaded)
  915. load(index, targetGroup);
  916. }
  917. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  918. {
  919. if (source[group].size() <= frame)
  920. source[group].resize(frame+1);
  921. source[group][frame]["file"].String() = filename;
  922. //FIXME: update image if already loaded
  923. }
  924. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  925. {
  926. auto groupIter = images.find(group);
  927. if (groupIter != images.end())
  928. {
  929. auto imageIter = groupIter->second.find(frame);
  930. if (imageIter != groupIter->second.end())
  931. return imageIter->second;
  932. }
  933. if (verbose)
  934. printError(frame, group, "GetImage");
  935. return nullptr;
  936. }
  937. void CAnimation::load()
  938. {
  939. for (auto & elem : source)
  940. for (size_t image=0; image < elem.second.size(); image++)
  941. loadFrame(image, elem.first);
  942. }
  943. void CAnimation::unload()
  944. {
  945. for (auto & elem : source)
  946. for (size_t image=0; image < elem.second.size(); image++)
  947. unloadFrame(image, elem.first);
  948. }
  949. void CAnimation::preload()
  950. {
  951. if(!preloaded)
  952. {
  953. preloaded = true;
  954. load();
  955. }
  956. }
  957. void CAnimation::loadGroup(size_t group)
  958. {
  959. if (vstd::contains(source, group))
  960. for (size_t image=0; image < source[group].size(); image++)
  961. loadFrame(image, group);
  962. }
  963. void CAnimation::unloadGroup(size_t group)
  964. {
  965. if (vstd::contains(source, group))
  966. for (size_t image=0; image < source[group].size(); image++)
  967. unloadFrame(image, group);
  968. }
  969. void CAnimation::load(size_t frame, size_t group)
  970. {
  971. loadFrame(frame, group);
  972. }
  973. void CAnimation::unload(size_t frame, size_t group)
  974. {
  975. unloadFrame(frame, group);
  976. }
  977. size_t CAnimation::size(size_t group) const
  978. {
  979. auto iter = source.find(group);
  980. if (iter != source.end())
  981. return iter->second.size();
  982. return 0;
  983. }
  984. void CAnimation::horizontalFlip()
  985. {
  986. for(auto & group : images)
  987. for(auto & image : group.second)
  988. image.second->horizontalFlip();
  989. }
  990. void CAnimation::verticalFlip()
  991. {
  992. for(auto & group : images)
  993. for(auto & image : group.second)
  994. image.second->verticalFlip();
  995. }
  996. void CAnimation::playerColored(PlayerColor player)
  997. {
  998. for(auto & group : images)
  999. for(auto & image : group.second)
  1000. image.second->playerColored(player);
  1001. }
  1002. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  1003. {
  1004. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  1005. {
  1006. duplicateImage(sourceGroup, frame, targetGroup);
  1007. auto image = getImage(frame, targetGroup);
  1008. image->verticalFlip();
  1009. }
  1010. }
  1011. float CFadeAnimation::initialCounter() const
  1012. {
  1013. if (fadingMode == EMode::OUT)
  1014. return 1.0f;
  1015. return 0.0f;
  1016. }
  1017. void CFadeAnimation::update()
  1018. {
  1019. if (!fading)
  1020. return;
  1021. if (fadingMode == EMode::OUT)
  1022. fadingCounter -= delta;
  1023. else
  1024. fadingCounter += delta;
  1025. if (isFinished())
  1026. {
  1027. fading = false;
  1028. if (shouldFreeSurface)
  1029. {
  1030. SDL_FreeSurface(fadingSurface);
  1031. fadingSurface = nullptr;
  1032. }
  1033. }
  1034. }
  1035. bool CFadeAnimation::isFinished() const
  1036. {
  1037. if (fadingMode == EMode::OUT)
  1038. return fadingCounter <= 0.0f;
  1039. return fadingCounter >= 1.0f;
  1040. }
  1041. CFadeAnimation::CFadeAnimation()
  1042. : delta(0), fadingSurface(nullptr), fading(false), fadingCounter(0), shouldFreeSurface(false),
  1043. fadingMode(EMode::NONE)
  1044. {
  1045. }
  1046. CFadeAnimation::~CFadeAnimation()
  1047. {
  1048. if (fadingSurface && shouldFreeSurface)
  1049. SDL_FreeSurface(fadingSurface);
  1050. }
  1051. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd, float animDelta)
  1052. {
  1053. if (fading)
  1054. {
  1055. // in that case, immediately finish the previous fade
  1056. // (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))
  1057. logGlobal->warn("Tried to init fading animation that is already running.");
  1058. if (fadingSurface && shouldFreeSurface)
  1059. SDL_FreeSurface(fadingSurface);
  1060. }
  1061. if (animDelta <= 0.0f)
  1062. {
  1063. logGlobal->warn("Fade anim: delta should be positive; %f given.", animDelta);
  1064. animDelta = DEFAULT_DELTA;
  1065. }
  1066. if (sourceSurface)
  1067. fadingSurface = sourceSurface;
  1068. delta = animDelta;
  1069. fadingMode = mode;
  1070. fadingCounter = initialCounter();
  1071. fading = true;
  1072. shouldFreeSurface = freeSurfaceAtEnd;
  1073. }
  1074. void CFadeAnimation::draw(SDL_Surface * targetSurface, const Point &targetPoint)
  1075. {
  1076. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1077. {
  1078. fading = false;
  1079. return;
  1080. }
  1081. CSDL_Ext::setAlpha(fadingSurface, (int)(fadingCounter * 255));
  1082. CSDL_Ext::blitSurface(fadingSurface, targetSurface, targetPoint); //FIXME
  1083. CSDL_Ext::setAlpha(fadingSurface, 255);
  1084. }