CAnimation.cpp 30 KB

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