2
0

CAnimation.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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. }