CAnimation.cpp 30 KB

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