CAnimation.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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. CSDL_Ext::colorSetAlpha(palette[i],255);
  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_SetColors(image->surf, pal, 0, 256);
  311. SDL_LockSurface(image->surf);
  312. lineStart = position = (ui8*)image->surf->pixels;
  313. }
  314. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  315. {
  316. if (size)
  317. {
  318. memcpy((void *)position, data, size);
  319. position += size;
  320. }
  321. }
  322. inline void SDLImageLoader::Load(size_t size, ui8 color)
  323. {
  324. if (size)
  325. {
  326. memset((void *)position, color, size);
  327. position += size;
  328. }
  329. }
  330. inline void SDLImageLoader::EndLine()
  331. {
  332. lineStart += image->surf->pitch;
  333. position = lineStart;
  334. }
  335. SDLImageLoader::~SDLImageLoader()
  336. {
  337. SDL_UnlockSurface(image->surf);
  338. SDL_SetColorKey(image->surf, SDL_SRCCOLORKEY, 0);
  339. //TODO: RLE if compressed and bpp>1
  340. }
  341. ////////////////////////////////////////////////////////////////////////////////
  342. CompImageLoader::CompImageLoader(CompImage * Img):
  343. image(Img),
  344. position(nullptr),
  345. entry(nullptr),
  346. currentLine(0)
  347. {
  348. }
  349. void CompImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  350. {
  351. image->sprite = Rect(Margins, SpriteSize);
  352. image->fullSize = FullSize;
  353. if (SpriteSize.x && SpriteSize.y)
  354. {
  355. image->palette = new SDL_Color[256];
  356. memcpy((void*)image->palette, (void*)pal, 256*sizeof(SDL_Color));
  357. //Allocate enought space for worst possible case, c-style malloc used due to resizing after load
  358. image->surf = (ui8*)malloc(SpriteSize.x*SpriteSize.y*3);
  359. image->line = new ui32[SpriteSize.y+1];
  360. image->line[0] = 0;
  361. position = image->surf;
  362. }
  363. }
  364. inline void CompImageLoader::NewEntry(ui8 color, size_t size)
  365. {
  366. assert(color != 0xff);
  367. assert(size && size<256);
  368. entry = position;
  369. entry[0] = color;
  370. entry[1] = size;
  371. position +=2;
  372. }
  373. inline void CompImageLoader::NewEntry(const ui8 * &data, size_t size)
  374. {
  375. assert(size && size<256);
  376. entry = position;
  377. entry[0] = 0xff;
  378. entry[1] = size;
  379. position +=2;
  380. memcpy(position, data, size);
  381. position+=size;
  382. data+=size;
  383. }
  384. inline ui8 CompImageLoader::typeOf(ui8 color)
  385. {
  386. if (color == 0)
  387. return 0;
  388. #ifdef VCMI_SDL1
  389. if (image->palette[color].unused != 255)
  390. return 1;
  391. #else
  392. if (image->palette[color].a != 255)
  393. return 1;
  394. #endif // 0
  395. return 2;
  396. }
  397. inline void CompImageLoader::Load(size_t size, const ui8 * data)
  398. {
  399. while (size)
  400. {
  401. //Try to compress data
  402. while(true)
  403. {
  404. ui8 color = data[0];
  405. if (color != 0xff)
  406. {
  407. size_t runLength = 1;
  408. while (runLength < size && color == data[runLength])
  409. runLength++;
  410. if (runLength > 1 && runLength < 255)//Row of one color found - use RLE
  411. {
  412. Load(runLength, color);
  413. data += runLength;
  414. size -= runLength;
  415. if (!size)
  416. return;
  417. }
  418. else
  419. break;
  420. }
  421. else
  422. break;
  423. }
  424. //Select length for new raw entry
  425. size_t runLength = 1;
  426. ui8 color = data[0];
  427. ui8 type = typeOf(color);
  428. ui8 color2;
  429. ui8 type2;
  430. if (size > 1)
  431. {
  432. do
  433. {
  434. color2 = data[runLength];
  435. type2 = typeOf(color2);
  436. runLength++;
  437. }
  438. //While we have data of this type and different colors
  439. while ((runLength < size) && (type == type2) && ( (color2 != 0xff) || (color2 != color)));
  440. }
  441. size -= runLength;
  442. //add data to last entry
  443. if (entry && entry[0] == 0xff && type == typeOf(entry[2]))
  444. {
  445. size_t toCopy = std::min<size_t>(runLength, 255 - entry[1]);
  446. runLength -= toCopy;
  447. entry[1] += toCopy;
  448. memcpy(position, data, toCopy);
  449. data+=toCopy;
  450. position+=toCopy;
  451. }
  452. //Create new entries
  453. while (runLength > 255)
  454. {
  455. NewEntry(data, 255);
  456. runLength -= 255;
  457. }
  458. if (runLength)
  459. NewEntry(data, runLength);
  460. }
  461. }
  462. inline void CompImageLoader::Load(size_t size, ui8 color)
  463. {
  464. if (!size)
  465. return;
  466. if (color==0xff)
  467. {
  468. auto tmpbuf = new ui8[size];
  469. memset((void*)tmpbuf, color, size);
  470. Load(size, tmpbuf);
  471. delete [] tmpbuf;
  472. return;
  473. }
  474. //Current entry is RLE with same color as new block
  475. if (entry && entry[0] == color)
  476. {
  477. size_t toCopy = std::min<size_t>(size, 255 - entry[1]);
  478. size -= toCopy;
  479. entry[1] += toCopy;
  480. }
  481. //Create new entries
  482. while (size > 255)
  483. {
  484. NewEntry(color, 255);
  485. size -= 255;
  486. }
  487. if (size)
  488. NewEntry(color, size);
  489. }
  490. void CompImageLoader::EndLine()
  491. {
  492. currentLine++;
  493. image->line[currentLine] = position - image->surf;
  494. entry = nullptr;
  495. }
  496. CompImageLoader::~CompImageLoader()
  497. {
  498. if (!image->surf)
  499. return;
  500. ui8* newPtr = (ui8*)realloc((void*)image->surf, position - image->surf);
  501. if (newPtr)
  502. image->surf = newPtr;
  503. }
  504. /*************************************************************************
  505. * Classes for images, support loading from file and drawing on surface *
  506. *************************************************************************/
  507. IImage::IImage():
  508. refCount(1)
  509. {
  510. }
  511. bool IImage::decreaseRef()
  512. {
  513. refCount--;
  514. return refCount <= 0;
  515. }
  516. void IImage::increaseRef()
  517. {
  518. refCount++;
  519. }
  520. SDLImage::SDLImage(CDefFile *data, size_t frame, size_t group, bool compressed):
  521. surf(nullptr)
  522. {
  523. SDLImageLoader loader(this);
  524. data->loadFrame(frame, group, loader);
  525. }
  526. SDLImage::SDLImage(SDL_Surface * from, bool extraRef):
  527. margins(0,0)
  528. {
  529. surf = from;
  530. if (extraRef)
  531. surf->refcount++;
  532. fullSize.x = surf->w;
  533. fullSize.y = surf->h;
  534. }
  535. SDLImage::SDLImage(std::string filename, bool compressed):
  536. margins(0,0)
  537. {
  538. surf = BitmapHandler::loadBitmap(filename);
  539. if (surf == nullptr)
  540. {
  541. logGlobal->errorStream() << "Error: failed to load image "<<filename;
  542. return;
  543. }
  544. else
  545. {
  546. fullSize.x = surf->w;
  547. fullSize.y = surf->h;
  548. }
  549. if (compressed)
  550. {
  551. SDL_Surface *temp = surf;
  552. // add RLE flag
  553. #ifdef VCMI_SDL1
  554. if (surf->format->palette)
  555. {
  556. const SDL_Color &c = temp->format->palette->colors[0];
  557. SDL_SetColorKey(temp, (SDL_SRCCOLORKEY | SDL_RLEACCEL),
  558. SDL_MapRGB(temp -> format, c.r, c.g, c.b));
  559. }
  560. else
  561. SDL_SetColorKey(temp, SDL_RLEACCEL, 0);
  562. #else
  563. if (surf->format->palette)
  564. {
  565. CSDL_Ext::setColorKey(temp,temp->format->palette->colors[0]);
  566. }
  567. SDL_SetSurfaceRLE(temp, SDL_RLEACCEL);
  568. #endif
  569. // convert surface to enable RLE
  570. surf = SDL_ConvertSurface(temp, temp->format, temp->flags);
  571. SDL_FreeSurface(temp);
  572. }
  573. }
  574. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 rotation) const
  575. {
  576. if (!surf)
  577. return;
  578. Rect sourceRect(margins.x, margins.y, surf->w, surf->h);
  579. //TODO: rotation and scaling
  580. if (src)
  581. {
  582. sourceRect = sourceRect & *src;
  583. }
  584. Rect destRect(posX, posY, surf->w, surf->h);
  585. destRect += sourceRect.topLeft();
  586. sourceRect -= margins;
  587. CSDL_Ext::blitSurface(surf, &sourceRect, where, &destRect);
  588. }
  589. void SDLImage::playerColored(PlayerColor player)
  590. {
  591. graphics->blueToPlayersAdv(surf, player);
  592. }
  593. int SDLImage::width() const
  594. {
  595. return fullSize.x;
  596. }
  597. int SDLImage::height() const
  598. {
  599. return fullSize.y;
  600. }
  601. SDLImage::~SDLImage()
  602. {
  603. SDL_FreeSurface(surf);
  604. }
  605. CompImage::CompImage(const CDefFile *data, size_t frame, size_t group):
  606. surf(nullptr),
  607. line(nullptr),
  608. palette(nullptr)
  609. {
  610. CompImageLoader loader(this);
  611. data->loadFrame(frame, group, loader);
  612. }
  613. CompImage::CompImage(SDL_Surface * surf)
  614. {
  615. //TODO
  616. assert(0);
  617. }
  618. void CompImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  619. {
  620. int rotation = 0; //TODO
  621. //rotation & 2 = horizontal rotation
  622. //rotation & 4 = vertical rotation
  623. if (!surf)
  624. return;
  625. Rect sourceRect(sprite);
  626. //TODO: rotation and scaling
  627. if (src)
  628. sourceRect = sourceRect & *src;
  629. //Limit source rect to sizes of surface
  630. sourceRect = sourceRect & Rect(0, 0, where->w, where->h);
  631. //Starting point on SDL surface
  632. Point dest(posX+sourceRect.x, posY+sourceRect.y);
  633. if (rotation & 2)
  634. dest.y += sourceRect.h;
  635. if (rotation & 4)
  636. dest.x += sourceRect.w;
  637. sourceRect -= sprite.topLeft();
  638. for (int currY = 0; currY <sourceRect.h; currY++)
  639. {
  640. ui8* data = surf + line[currY+sourceRect.y];
  641. ui8 type = *(data++);
  642. ui8 size = *(data++);
  643. int currX = sourceRect.x;
  644. //Skip blocks until starting position reached
  645. while ( currX > size )
  646. {
  647. currX -= size;
  648. if (type == 0xff)
  649. data += size;
  650. type = *(data++);
  651. size = *(data++);
  652. }
  653. //This block will be shown partially - calculate size\position
  654. size -= currX;
  655. if (type == 0xff)
  656. data += currX;
  657. currX = 0;
  658. ui8 bpp = where->format->BytesPerPixel;
  659. //Calculate position for blitting: pixels + Y + X
  660. ui8* blitPos = (ui8*) where->pixels;
  661. if (rotation & 4)
  662. blitPos += (dest.y - currY) * where->pitch;
  663. else
  664. blitPos += (dest.y + currY) * where->pitch;
  665. blitPos += dest.x * bpp;
  666. //Blit blocks that must be fully visible
  667. while (currX + size < sourceRect.w)
  668. {
  669. //blit block, pointers will be modified if needed
  670. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  671. currX += size;
  672. type = *(data++);
  673. size = *(data++);
  674. }
  675. //Blit last, semi-visible block
  676. size = sourceRect.w - currX;
  677. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  678. }
  679. }
  680. #define CASEBPP(x,y) case x: BlitBlock<x,y>(type, size, data, dest, alpha); break
  681. //FIXME: better way to get blitter
  682. void CompImage::BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const
  683. {
  684. assert(bpp>1 && bpp<5);
  685. if (rotated)
  686. switch (bpp)
  687. {
  688. CASEBPP(2,1);
  689. CASEBPP(3,1);
  690. CASEBPP(4,1);
  691. }
  692. else
  693. switch (bpp)
  694. {
  695. CASEBPP(2,1);
  696. CASEBPP(3,1);
  697. CASEBPP(4,1);
  698. }
  699. }
  700. #undef CASEBPP
  701. //Blit one block from RLE-d surface
  702. template<int bpp, int dir>
  703. void CompImage::BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const
  704. {
  705. //Raw data
  706. if (type == 0xff)
  707. {
  708. ui8 color = *data;
  709. if (alpha != 255)//Per-surface alpha is set
  710. {
  711. for (size_t i=0; i<size; i++)
  712. {
  713. SDL_Color col = palette[*(data++)];
  714. #ifdef VCMI_SDL1
  715. col.unused = (ui32)col.unused*alpha/255;
  716. #else
  717. col.a = (ui32)col.a*alpha/255;
  718. #endif // 0
  719. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  720. }
  721. return;
  722. }
  723. #ifdef VCMI_SDL1
  724. if (palette[color].unused == 255)
  725. #else
  726. if (palette[color].a == 255)
  727. #endif // 0
  728. {
  729. //Put row of RGB data
  730. for (size_t i=0; i<size; i++)
  731. ColorPutter<bpp, 1>::PutColor(dest, palette[*(data++)]);
  732. }
  733. else
  734. {
  735. //Put row of RGBA data
  736. for (size_t i=0; i<size; i++)
  737. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[*(data++)]);
  738. }
  739. }
  740. //RLE-d sequence
  741. else
  742. {
  743. #ifdef VCMI_SDL1
  744. if (alpha != 255 && palette[type].unused !=0)//Per-surface alpha is set
  745. {
  746. SDL_Color col = palette[type];
  747. col.unused = (int)col.unused*(255-alpha)/255;
  748. for (size_t i=0; i<size; i++)
  749. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  750. return;
  751. }
  752. switch (palette[type].unused)
  753. #else
  754. if (alpha != 255 && palette[type].a !=0)//Per-surface alpha is set
  755. {
  756. SDL_Color col = palette[type];
  757. col.a = (int)col.a*(255-alpha)/255;
  758. for (size_t i=0; i<size; i++)
  759. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  760. return;
  761. }
  762. switch (palette[type].a)
  763. #endif // 0
  764. {
  765. case 0:
  766. {
  767. //Skip row
  768. dest += size*bpp;
  769. break;
  770. }
  771. case 255:
  772. {
  773. //Put RGB row
  774. ColorPutter<bpp, 1>::PutColorRow(dest, palette[type], size);
  775. break;
  776. }
  777. default:
  778. {
  779. //Put RGBA row
  780. for (size_t i=0; i<size; i++)
  781. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[type]);
  782. break;
  783. }
  784. }
  785. }
  786. }
  787. void CompImage::playerColored(PlayerColor player)
  788. {
  789. SDL_Color *pal = nullptr;
  790. if(player < PlayerColor::PLAYER_LIMIT)
  791. {
  792. pal = graphics->playerColorPalette + 32*player.getNum();
  793. }
  794. else if(player == PlayerColor::NEUTRAL)
  795. {
  796. pal = graphics->neutralColorPalette;
  797. }
  798. else
  799. assert(0);
  800. for(int i=0; i<32; ++i)
  801. {
  802. CSDL_Ext::colorAssign(palette[224+i],pal[i]);
  803. }
  804. }
  805. int CompImage::width() const
  806. {
  807. return fullSize.x;
  808. }
  809. int CompImage::height() const
  810. {
  811. return fullSize.y;
  812. }
  813. CompImage::~CompImage()
  814. {
  815. free(surf);
  816. delete [] line;
  817. delete [] palette;
  818. }
  819. /*************************************************************************
  820. * CAnimation for animations handling, can load part of file if needed *
  821. *************************************************************************/
  822. IImage * CAnimation::getFromExtraDef(std::string filename)
  823. {
  824. size_t pos = filename.find(':');
  825. if (pos == -1)
  826. return nullptr;
  827. CAnimation anim(filename.substr(0, pos));
  828. pos++;
  829. size_t frame = atoi(filename.c_str()+pos);
  830. size_t group = 0;
  831. pos = filename.find(':', pos);
  832. if (pos != -1)
  833. {
  834. group = frame;
  835. frame = atoi(filename.c_str()+pos);
  836. }
  837. anim.load(frame ,group);
  838. IImage * ret = anim.images[group][frame];
  839. anim.images.clear();
  840. return ret;
  841. }
  842. bool CAnimation::loadFrame(CDefFile * file, size_t frame, size_t group)
  843. {
  844. if (size(group) <= frame)
  845. {
  846. printError(frame, group, "LoadFrame");
  847. return false;
  848. }
  849. IImage *image = getImage(frame, group, false);
  850. if (image)
  851. {
  852. image->increaseRef();
  853. return true;
  854. }
  855. //try to get image from def
  856. if (source[group][frame].getType() == JsonNode::DATA_NULL)
  857. {
  858. if (file)
  859. {
  860. auto frameList = file->getEntries();
  861. if (vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  862. {
  863. if (compressed)
  864. images[group][frame] = new CompImage(file, frame, group);
  865. else
  866. images[group][frame] = new SDLImage(file, frame, group);
  867. return true;
  868. }
  869. }
  870. // still here? image is missing
  871. printError(frame, group, "LoadFrame");
  872. images[group][frame] = new SDLImage("DEFAULT", compressed);
  873. }
  874. else //load from separate file
  875. {
  876. std::string filename = source[group][frame].Struct().find("file")->second.String();
  877. IImage * img = getFromExtraDef(filename);
  878. if (!img)
  879. img = new SDLImage(filename, compressed);
  880. images[group][frame] = img;
  881. return true;
  882. }
  883. return false;
  884. }
  885. bool CAnimation::unloadFrame(size_t frame, size_t group)
  886. {
  887. IImage *image = getImage(frame, group, false);
  888. if (image)
  889. {
  890. //decrease ref count for image and delete if needed
  891. if (image->decreaseRef())
  892. {
  893. delete image;
  894. images[group].erase(frame);
  895. }
  896. if (images[group].empty())
  897. images.erase(group);
  898. return true;
  899. }
  900. return false;
  901. }
  902. void CAnimation::initFromJson(const JsonNode & config)
  903. {
  904. std::string basepath;
  905. basepath = config["basepath"].String();
  906. for(const JsonNode &group : config["sequences"].Vector())
  907. {
  908. size_t groupID = group["group"].Float();//TODO: string-to-value conversion("moving" -> MOVING)
  909. source[groupID].clear();
  910. for(const JsonNode &frame : group["frames"].Vector())
  911. {
  912. source[groupID].push_back(JsonNode());
  913. std::string filename = frame.String();
  914. source[groupID].back()["file"].String() = basepath + filename;
  915. }
  916. }
  917. for(const JsonNode &node : config["images"].Vector())
  918. {
  919. size_t group = node["group"].Float();
  920. size_t frame = node["frame"].Float();
  921. if (source[group].size() <= frame)
  922. source[group].resize(frame+1);
  923. source[group][frame] = node;
  924. std::string filename = node["file"].String();
  925. source[group][frame]["file"].String() = basepath + filename;
  926. }
  927. }
  928. void CAnimation::init(CDefFile * file)
  929. {
  930. if (file)
  931. {
  932. const std::map<size_t, size_t> defEntries = file->getEntries();
  933. for (auto & defEntry : defEntries)
  934. source[defEntry.first].resize(defEntry.second);
  935. }
  936. ResourceID resID(std::string("SPRITES/") + name, EResType::TEXT);
  937. if (vstd::contains(graphics->imageLists, resID.getName()))
  938. initFromJson(graphics->imageLists[resID.getName()]);
  939. auto configList = CResourceHandler::get()->getResourcesWithName(resID);
  940. for(auto & loader : configList)
  941. {
  942. auto stream = loader->load(resID);
  943. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  944. stream->read(textData.get(), stream->getSize());
  945. const JsonNode config((char*)textData.get(), stream->getSize());
  946. initFromJson(config);
  947. }
  948. }
  949. CDefFile * CAnimation::getFile() const
  950. {
  951. ResourceID identifier(std::string("SPRITES/") + name, EResType::ANIMATION);
  952. if (CResourceHandler::get()->existsResource(identifier))
  953. return new CDefFile(name);
  954. return nullptr;
  955. }
  956. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  957. {
  958. logGlobal->errorStream() << type <<" error: Request for frame not present in CAnimation! "
  959. <<"\tFile name: "<<name<<" Group: "<<group<<" Frame: "<<frame;
  960. }
  961. CAnimation::CAnimation(std::string Name, bool Compressed):
  962. name(Name),
  963. compressed(Compressed)
  964. {
  965. size_t dotPos = name.find_last_of('.');
  966. if ( dotPos!=-1 )
  967. name.erase(dotPos);
  968. std::transform(name.begin(), name.end(), name.begin(), toupper);
  969. CDefFile * file = getFile();
  970. init(file);
  971. delete file;
  972. loadedAnims.insert(this);
  973. }
  974. CAnimation::CAnimation():
  975. name(""),
  976. compressed(false)
  977. {
  978. init(nullptr);
  979. loadedAnims.insert(this);
  980. }
  981. CAnimation::~CAnimation()
  982. {
  983. if (!images.empty())
  984. {
  985. logGlobal->warnStream()<<"Warning: not all frames were unloaded from "<<name;
  986. for (auto & elem : images)
  987. for (auto & _image : elem.second)
  988. delete _image.second;
  989. }
  990. loadedAnims.erase(this);
  991. }
  992. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  993. {
  994. if (source[group].size() <= frame)
  995. source[group].resize(frame+1);
  996. source[group][frame]["file"].String() = filename;
  997. //FIXME: update image if already loaded
  998. }
  999. IImage * CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  1000. {
  1001. auto groupIter = images.find(group);
  1002. if (groupIter != images.end())
  1003. {
  1004. auto imageIter = groupIter->second.find(frame);
  1005. if (imageIter != groupIter->second.end())
  1006. return imageIter->second;
  1007. }
  1008. if (verbose)
  1009. printError(frame, group, "GetImage");
  1010. return nullptr;
  1011. }
  1012. void CAnimation::load()
  1013. {
  1014. CDefFile * file = getFile();
  1015. for (auto & elem : source)
  1016. for (size_t image=0; image < elem.second.size(); image++)
  1017. loadFrame(file, image, elem.first);
  1018. delete file;
  1019. }
  1020. void CAnimation::unload()
  1021. {
  1022. for (auto & elem : source)
  1023. for (size_t image=0; image < elem.second.size(); image++)
  1024. unloadFrame(image, elem.first);
  1025. }
  1026. void CAnimation::loadGroup(size_t group)
  1027. {
  1028. CDefFile * file = getFile();
  1029. if (vstd::contains(source, group))
  1030. for (size_t image=0; image < source[group].size(); image++)
  1031. loadFrame(file, image, group);
  1032. delete file;
  1033. }
  1034. void CAnimation::unloadGroup(size_t group)
  1035. {
  1036. if (vstd::contains(source, group))
  1037. for (size_t image=0; image < source[group].size(); image++)
  1038. unloadFrame(image, group);
  1039. }
  1040. void CAnimation::load(size_t frame, size_t group)
  1041. {
  1042. CDefFile * file = getFile();
  1043. loadFrame(file, frame, group);
  1044. delete file;
  1045. }
  1046. void CAnimation::unload(size_t frame, size_t group)
  1047. {
  1048. unloadFrame(frame, group);
  1049. }
  1050. size_t CAnimation::size(size_t group) const
  1051. {
  1052. auto iter = source.find(group);
  1053. if (iter != source.end())
  1054. return iter->second.size();
  1055. return 0;
  1056. }
  1057. std::set<CAnimation*> CAnimation::loadedAnims;
  1058. void CAnimation::getAnimInfo()
  1059. {
  1060. logGlobal->errorStream()<<"Animation stats: Loaded "<<loadedAnims.size()<<" total";
  1061. for (auto anim : loadedAnims)
  1062. {
  1063. logGlobal->errorStream()<<"Name: "<<anim->name<<" Groups: "<<anim->images.size();
  1064. if (!anim->images.empty())
  1065. logGlobal->errorStream()<<", "<<anim->images.begin()->second.size()<<" image loaded in group "<< anim->images.begin()->first;
  1066. }
  1067. }
  1068. float CFadeAnimation::initialCounter() const
  1069. {
  1070. if (fadingMode == EMode::OUT)
  1071. return 1.0f;
  1072. return 0.0f;
  1073. }
  1074. void CFadeAnimation::update()
  1075. {
  1076. if (!fading)
  1077. return;
  1078. if (fadingMode == EMode::OUT)
  1079. fadingCounter -= delta;
  1080. else
  1081. fadingCounter += delta;
  1082. if (isFinished())
  1083. {
  1084. fading = false;
  1085. if (shouldFreeSurface)
  1086. {
  1087. SDL_FreeSurface(fadingSurface);
  1088. fadingSurface = nullptr;
  1089. }
  1090. }
  1091. }
  1092. bool CFadeAnimation::isFinished() const
  1093. {
  1094. if (fadingMode == EMode::OUT)
  1095. return fadingCounter <= 0.0f;
  1096. return fadingCounter >= 1.0f;
  1097. }
  1098. CFadeAnimation::CFadeAnimation()
  1099. : fadingSurface(nullptr),
  1100. fading(false),
  1101. fadingMode(EMode::NONE)
  1102. {
  1103. }
  1104. CFadeAnimation::~CFadeAnimation()
  1105. {
  1106. if (fadingSurface && shouldFreeSurface)
  1107. SDL_FreeSurface(fadingSurface);
  1108. }
  1109. void CFadeAnimation::init(EMode mode, SDL_Surface * sourceSurface, bool freeSurfaceAtEnd /* = false */, float animDelta /* = DEFAULT_DELTA */)
  1110. {
  1111. if (fading)
  1112. {
  1113. // in that case, immediately finish the previous fade
  1114. // (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))
  1115. logGlobal->warnStream() << "Tried to init fading animation that is already running.";
  1116. if (fadingSurface && shouldFreeSurface)
  1117. SDL_FreeSurface(fadingSurface);
  1118. }
  1119. if (animDelta <= 0.0f)
  1120. {
  1121. logGlobal->warnStream() << "Fade anim: delta should be positive; " << animDelta << " given.";
  1122. animDelta = DEFAULT_DELTA;
  1123. }
  1124. if (sourceSurface)
  1125. fadingSurface = sourceSurface;
  1126. delta = animDelta;
  1127. fadingMode = mode;
  1128. fadingCounter = initialCounter();
  1129. fading = true;
  1130. shouldFreeSurface = freeSurfaceAtEnd;
  1131. }
  1132. void CFadeAnimation::draw(SDL_Surface * targetSurface, const SDL_Rect * sourceRect, SDL_Rect * destRect)
  1133. {
  1134. if (!fading || !fadingSurface || fadingMode == EMode::NONE)
  1135. {
  1136. fading = false;
  1137. return;
  1138. }
  1139. SDL_SetSurfaceAlphaMod(fadingSurface, fadingCounter * 255);
  1140. SDL_BlitSurface(fadingSurface, sourceRect, targetSurface, destRect);
  1141. SDL_SetSurfaceAlphaMod(fadingSurface, 255);
  1142. }