CAnimation.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. #include <boost/bind.hpp>
  2. #include <boost/algorithm/string/trim.hpp>
  3. #include <SDL_image.h>
  4. #include "../lib/CLodHandler.h"
  5. #include "../lib/JsonNode.h"
  6. #include "CBitmapHandler.h"
  7. #include "Graphics.h"
  8. #include "CAnimation.h"
  9. #include "SDL_Extensions.h"
  10. /*
  11. * CAnimation.cpp, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. extern DLL_EXPORT CLodHandler *spriteh;
  20. extern DLL_EXPORT CLodHandler *bitmaph;
  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. unsigned int 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. /*************************************************************************
  61. * DefFile, class used for def loading *
  62. *************************************************************************/
  63. size_t getPaletteSize(int type)
  64. {
  65. switch (type)
  66. {
  67. case 66: return 32;
  68. case 71: return 4;
  69. default: return 20;
  70. }
  71. }
  72. CDefFile::CDefFile(std::string Name):
  73. data(NULL),
  74. palette(NULL)
  75. {
  76. //First 8 colors in def palette used for transparency
  77. static SDL_Color H3Palette[8] =
  78. {
  79. { 0, 0, 0, 0},// 100% - transparency
  80. { 0, 0, 0, 192},// 75% - shadow border,
  81. { 0, 0, 0, 128},// TODO: find exact value
  82. { 0, 0, 0, 128},// TODO: for transparency
  83. { 0, 0, 0, 128},// 50% - shadow body
  84. { 0, 0, 0, 0},// 100% - selection highlight
  85. { 0, 0, 0, 128},// 50% - shadow body below selection
  86. { 0, 0, 0, 192} // 75% - shadow border below selection
  87. };
  88. data = spriteh->giveFile(Name, FILE_ANIMATION);
  89. palette = new SDL_Color[256];
  90. int it = 0;
  91. unsigned int type = readNormalNr(data, it);
  92. it+=4;
  93. //int width = readNormalNr(data, it); it+=4;//not used
  94. //int height = readNormalNr(data, it); it+=4;
  95. it+=8;
  96. unsigned int totalBlocks = readNormalNr(data, it);
  97. it+=4;
  98. for (unsigned int i= 0; i<256; i++)
  99. {
  100. palette[i].r = data[it++];
  101. palette[i].g = data[it++];
  102. palette[i].b = data[it++];
  103. palette[i].unused = 255;
  104. }
  105. memcpy(palette, H3Palette, getPaletteSize(type));//initialize shadow\selection colors
  106. for (unsigned int i=0; i<totalBlocks; i++)
  107. {
  108. size_t blockID = readNormalNr(data, it);
  109. it+=4;
  110. size_t totalEntries = readNormalNr(data, it);
  111. it+=12;
  112. //8 unknown bytes - skipping
  113. //13 bytes for name of every frame in this block - not used, skipping
  114. it+= 13 * totalEntries;
  115. for (unsigned int j=0; j<totalEntries; j++)
  116. {
  117. size_t currOffset = readNormalNr(data, it);
  118. offset[blockID].push_back(currOffset);
  119. it += 4;
  120. }
  121. }
  122. }
  123. template<class ImageLoader>
  124. void CDefFile::loadFrame(size_t frame, size_t group, ImageLoader &loader) const
  125. {
  126. std::map<size_t, std::vector <size_t> >::const_iterator it;
  127. it = offset.find(group);
  128. assert (it != offset.end());
  129. const ui8 * FDef = data+it->second[frame];
  130. const SSpriteDef sd = * reinterpret_cast<const SSpriteDef *>(FDef);
  131. SSpriteDef sprite;
  132. //sprite.size = SDL_SwapLE32(sd.size);//unused
  133. sprite.format = SDL_SwapLE32(sd.format);
  134. sprite.fullWidth = SDL_SwapLE32(sd.fullWidth);
  135. sprite.fullHeight = SDL_SwapLE32(sd.fullHeight);
  136. sprite.width = SDL_SwapLE32(sd.width);
  137. sprite.height = SDL_SwapLE32(sd.height);
  138. sprite.leftMargin = SDL_SwapLE32(sd.leftMargin);
  139. sprite.topMargin = SDL_SwapLE32(sd.topMargin);
  140. unsigned int currentOffset = sizeof(SSpriteDef);
  141. unsigned int BaseOffset = sizeof(SSpriteDef);
  142. loader.init(Point(sprite.width, sprite.height),
  143. Point(sprite.leftMargin, sprite.topMargin),
  144. Point(sprite.fullWidth, sprite.fullHeight), palette);
  145. switch (sprite.format)
  146. {
  147. case 0:
  148. {
  149. //pixel data is not compressed, copy data to surface
  150. for (unsigned int i=0; i<sprite.height; i++)
  151. {
  152. loader.Load(sprite.width, FDef[currentOffset]);
  153. currentOffset += sprite.width;
  154. loader.EndLine();
  155. }
  156. break;
  157. }
  158. case 1:
  159. {
  160. //for each line we have offset of pixel data
  161. const ui32 * RWEntriesLoc = reinterpret_cast<const ui32 *>(FDef+currentOffset);
  162. currentOffset += sizeof(ui32) * sprite.height;
  163. for (unsigned int i=0; i<sprite.height; i++)
  164. {
  165. //get position of the line
  166. currentOffset=BaseOffset + SDL_SwapLE32(read_unaligned_u32(RWEntriesLoc + i));
  167. unsigned int TotalRowLength = 0;
  168. while (TotalRowLength<sprite.width)
  169. {
  170. unsigned char type=FDef[currentOffset++];
  171. unsigned int length=FDef[currentOffset++] + 1;
  172. if (type==0xFF)//Raw data
  173. {
  174. loader.Load(length, FDef + currentOffset);
  175. currentOffset+=length;
  176. }
  177. else// RLE
  178. {
  179. loader.Load(length, type);
  180. }
  181. TotalRowLength += length;
  182. }
  183. loader.EndLine();
  184. }
  185. break;
  186. }
  187. case 2:
  188. {
  189. currentOffset = BaseOffset + SDL_SwapLE16(read_unaligned_u16(FDef + BaseOffset));
  190. for (unsigned int i=0; i<sprite.height; i++)
  191. {
  192. unsigned int TotalRowLength=0;
  193. while (TotalRowLength<sprite.width)
  194. {
  195. unsigned char SegmentType=FDef[currentOffset++];
  196. unsigned char code = SegmentType / 32;
  197. unsigned char length = (SegmentType & 31) + 1;
  198. if (code==7)//Raw data
  199. {
  200. loader.Load(length, FDef[currentOffset]);
  201. currentOffset += length;
  202. }
  203. else//RLE
  204. {
  205. loader.Load(length, code);
  206. }
  207. TotalRowLength+=length;
  208. }
  209. loader.EndLine();
  210. }
  211. break;
  212. }
  213. case 3:
  214. {
  215. for (unsigned int i=0; i<sprite.height; i++)
  216. {
  217. currentOffset = BaseOffset + SDL_SwapLE16(read_unaligned_u16(FDef + BaseOffset+i*2*(sprite.width/32)));
  218. unsigned int TotalRowLength=0;
  219. while (TotalRowLength<sprite.width)
  220. {
  221. unsigned char segment = FDef[currentOffset++];
  222. unsigned char code = segment / 32;
  223. unsigned char length = (segment & 31) + 1;
  224. if (code==7)//Raw data
  225. {
  226. loader.Load(length, FDef + currentOffset);
  227. currentOffset += length;
  228. }
  229. else//RLE
  230. {
  231. loader.Load(length, code);
  232. }
  233. TotalRowLength += length;
  234. }
  235. loader.EndLine();
  236. }
  237. break;
  238. }
  239. default:
  240. tlog0<<"Error: unsupported format of def file:"<<sprite.format<<"\n";
  241. break;
  242. }
  243. };
  244. CDefFile::~CDefFile()
  245. {
  246. delete[] data;
  247. delete[] palette;
  248. }
  249. const std::map<size_t, size_t > CDefFile::getEntries() const
  250. {
  251. std::map<size_t, size_t > ret;
  252. for (std::map<size_t, std::vector <size_t> >::const_iterator mapIt = offset.begin(); mapIt!=offset.end(); ++mapIt)
  253. ret[mapIt->first] = mapIt->second.size();
  254. return ret;
  255. }
  256. /*************************************************************************
  257. * Classes for image loaders - helpers for loading from def files *
  258. *************************************************************************/
  259. SDLImageLoader::SDLImageLoader(SDLImage * Img):
  260. image(Img),
  261. lineStart(NULL),
  262. position(NULL)
  263. {
  264. }
  265. void SDLImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  266. {
  267. //Init image
  268. image->surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SpriteSize.x, SpriteSize.y, 8, 0, 0, 0, 0);
  269. image->margins = Margins;
  270. image->fullSize = FullSize;
  271. //Prepare surface
  272. SDL_SetColors(image->surf, pal, 0, 256);
  273. SDL_LockSurface(image->surf);
  274. lineStart = position = (ui8*)image->surf->pixels;
  275. }
  276. inline void SDLImageLoader::Load(size_t size, const ui8 * data)
  277. {
  278. if (size)
  279. {
  280. memcpy((void *)position, data, size);
  281. position += size;
  282. }
  283. }
  284. inline void SDLImageLoader::Load(size_t size, ui8 color)
  285. {
  286. if (size)
  287. {
  288. memset((void *)position, color, size);
  289. position += size;
  290. }
  291. }
  292. inline void SDLImageLoader::EndLine()
  293. {
  294. lineStart += image->surf->pitch;
  295. position = lineStart;
  296. }
  297. SDLImageLoader::~SDLImageLoader()
  298. {
  299. SDL_UnlockSurface(image->surf);
  300. SDL_SetColorKey(image->surf, SDL_SRCCOLORKEY, 0);
  301. //TODO: RLE if compressed and bpp>1
  302. }
  303. ////////////////////////////////////////////////////////////////////////////////
  304. CompImageLoader::CompImageLoader(CompImage * Img):
  305. image(Img),
  306. position(NULL),
  307. entry(NULL),
  308. currentLine(0)
  309. {
  310. }
  311. void CompImageLoader::init(Point SpriteSize, Point Margins, Point FullSize, SDL_Color *pal)
  312. {
  313. image->sprite = Rect(Margins, SpriteSize);
  314. image->fullSize = FullSize;
  315. if (SpriteSize.x && SpriteSize.y)
  316. {
  317. image->palette = new SDL_Color[256];
  318. memcpy((void*)image->palette, (void*)pal, 256*sizeof(SDL_Color));
  319. //Allocate enought space for worst possible case, c-style malloc used due to resizing after load
  320. image->surf = (ui8*)malloc(SpriteSize.x*SpriteSize.y*3);
  321. image->line = new unsigned int[SpriteSize.y+1];
  322. image->line[0] = 0;
  323. position = image->surf;
  324. }
  325. }
  326. inline void CompImageLoader::NewEntry(ui8 color, size_t size)
  327. {
  328. assert(color != 0xff);
  329. assert(size && size<256);
  330. entry = position;
  331. entry[0] = color;
  332. entry[1] = size;
  333. position +=2;
  334. }
  335. inline void CompImageLoader::NewEntry(const ui8 * &data, size_t size)
  336. {
  337. assert(size && size<256);
  338. entry = position;
  339. entry[0] = 0xff;
  340. entry[1] = size;
  341. position +=2;
  342. memcpy(position, data, size);
  343. position+=size;
  344. data+=size;
  345. }
  346. inline ui8 CompImageLoader::typeOf(ui8 color)
  347. {
  348. if (color == 0)
  349. return 0;
  350. if (image->palette[color].unused != 255)
  351. return 1;
  352. return 2;
  353. }
  354. inline void CompImageLoader::Load(size_t size, const ui8 * data)
  355. {
  356. while (size)
  357. {
  358. //Try to compress data
  359. while(true)
  360. {
  361. ui8 color = data[0];
  362. if (color != 0xff)
  363. {
  364. size_t runLength = 1;
  365. while (runLength < size && color == data[runLength])
  366. runLength++;
  367. if (runLength > 1)//Row of one color found - use RLE
  368. {
  369. Load(runLength, color);
  370. data += runLength;
  371. size -= runLength;
  372. if (!size)
  373. return;
  374. }
  375. else
  376. break;
  377. }
  378. else
  379. break;
  380. }
  381. //Select length for new raw entry
  382. size_t runLength = 1;
  383. ui8 color = data[0];
  384. ui8 type = typeOf(color);
  385. ui8 color2;
  386. ui8 type2;
  387. if (size > 1)
  388. {
  389. do
  390. {
  391. color2 = data[runLength];
  392. type2 = typeOf(color2);
  393. runLength++;
  394. }
  395. //While we have data of this type and different colors
  396. while ((runLength < size) && (type == type2) && ( (color2 != 0xff) || (color2 != color)));
  397. }
  398. size -= runLength;
  399. //add data to last entry
  400. if (entry && entry[0] == 0xff && type == typeOf(entry[2]))
  401. {
  402. size_t toCopy = std::min<size_t>(runLength, 255 - entry[1]);
  403. runLength -= toCopy;
  404. entry[1] += toCopy;
  405. memcpy(position, data, toCopy);
  406. data+=toCopy;
  407. position+=toCopy;
  408. }
  409. //Create new entries
  410. while (runLength > 255)
  411. {
  412. NewEntry(data, 255);
  413. runLength -= 255;
  414. }
  415. if (runLength)
  416. NewEntry(data, runLength);
  417. }
  418. }
  419. inline void CompImageLoader::Load(size_t size, ui8 color)
  420. {
  421. if (!size)
  422. return;
  423. if (color==0xff)
  424. {
  425. ui8* tmpbuf = new ui8[size];
  426. memset((void*)tmpbuf, color, size);
  427. Load(size, tmpbuf);
  428. delete [] tmpbuf;
  429. return;
  430. }
  431. //Current entry is RLE with same color as new block
  432. if (entry && entry[0] == color)
  433. {
  434. size_t toCopy = std::min<size_t>(size, 255 - entry[1]);
  435. entry[1] = 255;
  436. size -= toCopy;
  437. entry[1] += toCopy;
  438. }
  439. //Create new entries
  440. while (size > 255)
  441. {
  442. NewEntry(color, 255);
  443. size -= 255;
  444. }
  445. if (size)
  446. NewEntry(color, size);
  447. }
  448. void CompImageLoader::EndLine()
  449. {
  450. currentLine++;
  451. image->line[currentLine] = position - image->surf;
  452. entry = NULL;
  453. }
  454. CompImageLoader::~CompImageLoader()
  455. {
  456. if (!image->surf)
  457. return;
  458. ui8* newPtr = (ui8*)realloc((void*)image->surf, position - image->surf);
  459. if (newPtr)
  460. image->surf = newPtr;
  461. }
  462. /*************************************************************************
  463. * Classes for images, support loading from file and drawing on surface *
  464. *************************************************************************/
  465. IImage::IImage():
  466. refCount(1)
  467. {
  468. }
  469. bool IImage::decreaseRef()
  470. {
  471. refCount--;
  472. return refCount <= 0;
  473. }
  474. void IImage::increaseRef()
  475. {
  476. refCount++;
  477. }
  478. SDLImage::SDLImage(CDefFile *data, size_t frame, size_t group, bool compressed):
  479. surf(NULL)
  480. {
  481. SDLImageLoader loader(this);
  482. data->loadFrame(frame, group, loader);
  483. }
  484. SDLImage::SDLImage(SDL_Surface * from, bool extraRef):
  485. margins(0,0)
  486. {
  487. surf = from;
  488. if (extraRef)
  489. surf->refcount++;
  490. fullSize.x = surf->w;
  491. fullSize.y = surf->h;
  492. }
  493. SDLImage::SDLImage(std::string filename, bool compressed):
  494. margins(0,0)
  495. {
  496. surf = BitmapHandler::loadBitmap(filename);
  497. if (surf == NULL)
  498. {
  499. tlog1 << "Error: failed to load image "<<filename<<"\n";
  500. }
  501. else
  502. {
  503. fullSize.x = surf->w;
  504. fullSize.y = surf->h;
  505. }
  506. if (compressed)
  507. {
  508. SDL_Surface *temp = surf;
  509. // add RLE flag
  510. if (surf->format->palette)
  511. {
  512. const SDL_Color &c = temp->format->palette->colors[0];
  513. SDL_SetColorKey(temp, (SDL_SRCCOLORKEY | SDL_RLEACCEL),
  514. SDL_MapRGB(temp -> format, c.r, c.g, c.b));
  515. }
  516. else
  517. SDL_SetColorKey(temp, SDL_RLEACCEL, 0);
  518. // convert surface to enable RLE
  519. surf = SDL_ConvertSurface(temp, temp->format, temp->flags);
  520. SDL_FreeSurface(temp);
  521. }
  522. }
  523. void SDLImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, unsigned char rotation) const
  524. {
  525. if (!surf)
  526. return;
  527. Rect sourceRect(margins.x, margins.y, surf->w, surf->h);
  528. //TODO: rotation and scaling
  529. if (src)
  530. {
  531. sourceRect = sourceRect & *src;
  532. }
  533. Rect destRect(posX, posY, surf->w, surf->h);
  534. destRect += sourceRect.topLeft();
  535. sourceRect -= margins;
  536. CSDL_Ext::blitSurface(surf, &sourceRect, where, &destRect);
  537. }
  538. void SDLImage::playerColored(int player)
  539. {
  540. graphics->blueToPlayersAdv(surf, player);
  541. }
  542. int SDLImage::width() const
  543. {
  544. return fullSize.x;
  545. }
  546. int SDLImage::height() const
  547. {
  548. return fullSize.y;
  549. }
  550. SDLImage::~SDLImage()
  551. {
  552. SDL_FreeSurface(surf);
  553. }
  554. CompImage::CompImage(const CDefFile *data, size_t frame, size_t group):
  555. surf(NULL),
  556. line(NULL),
  557. palette(NULL)
  558. {
  559. CompImageLoader loader(this);
  560. data->loadFrame(frame, group, loader);
  561. }
  562. CompImage::CompImage(SDL_Surface * surf)
  563. {
  564. //TODO
  565. assert(0);
  566. }
  567. void CompImage::draw(SDL_Surface *where, int posX, int posY, Rect *src, ui8 alpha) const
  568. {
  569. int rotation = 0; //TODO
  570. //rotation & 2 = horizontal rotation
  571. //rotation & 4 = vertical rotation
  572. if (!surf)
  573. return;
  574. Rect sourceRect(sprite);
  575. //TODO: rotation and scaling
  576. if (src)
  577. sourceRect = sourceRect & *src;
  578. //Limit source rect to sizes of surface
  579. sourceRect = sourceRect & Rect(0, 0, where->w, where->h);
  580. //Starting point on SDL surface
  581. Point dest(posX+sourceRect.x, posY+sourceRect.y);
  582. if (rotation & 2)
  583. dest.y += sourceRect.h;
  584. if (rotation & 4)
  585. dest.x += sourceRect.w;
  586. sourceRect -= sprite.topLeft();
  587. for (int currY = 0; currY <sourceRect.h; currY++)
  588. {
  589. ui8* data = surf + line[currY+sourceRect.y];
  590. ui8 type = *(data++);
  591. ui8 size = *(data++);
  592. int currX = sourceRect.x;
  593. //Skip blocks until starting position reached
  594. while ( currX > size )
  595. {
  596. currX -= size;
  597. if (type == 0xff)
  598. data += size;
  599. type = *(data++);
  600. size = *(data++);
  601. }
  602. //This block will be shown partially - calculate size\position
  603. size -= currX;
  604. if (type == 0xff)
  605. data += currX;
  606. currX = 0;
  607. ui8 bpp = where->format->BytesPerPixel;
  608. //Calculate position for blitting: pixels + Y + X
  609. ui8* blitPos = (ui8*) where->pixels;
  610. if (rotation & 4)
  611. blitPos += (dest.y - currY) * where->pitch;
  612. else
  613. blitPos += (dest.y + currY) * where->pitch;
  614. blitPos += dest.x * bpp;
  615. //Blit blocks that must be fully visible
  616. while (currX + size < sourceRect.w)
  617. {
  618. //blit block, pointers will be modified if needed
  619. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  620. currX += size;
  621. type = *(data++);
  622. size = *(data++);
  623. }
  624. //Blit last, semi-visible block
  625. size = sourceRect.w - currX;
  626. BlitBlockWithBpp(bpp, type, size, data, blitPos, alpha, rotation & 2);
  627. }
  628. }
  629. #define CASEBPP(x,y) case x: BlitBlock<x,y>(type, size, data, dest, alpha); break
  630. //FIXME: better way to get blitter
  631. void CompImage::BlitBlockWithBpp(ui8 bpp, ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha, bool rotated) const
  632. {
  633. assert(bpp>1 && bpp<5);
  634. if (rotated)
  635. switch (bpp)
  636. {
  637. CASEBPP(2,1);
  638. CASEBPP(3,1);
  639. CASEBPP(4,1);
  640. }
  641. else
  642. switch (bpp)
  643. {
  644. CASEBPP(2,1);
  645. CASEBPP(3,1);
  646. CASEBPP(4,1);
  647. }
  648. }
  649. #undef CASEBPP
  650. //Blit one block from RLE-d surface
  651. template<int bpp, int dir>
  652. void CompImage::BlitBlock(ui8 type, ui8 size, ui8 *&data, ui8 *&dest, ui8 alpha) const
  653. {
  654. //Raw data
  655. if (type == 0xff)
  656. {
  657. ui8 color = *data;
  658. if (alpha != 255)//Per-surface alpha is set
  659. {
  660. for (size_t i=0; i<size; i++)
  661. {
  662. SDL_Color col = palette[*(data++)];
  663. col.unused = (unsigned int)col.unused*(255-alpha)/255;
  664. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  665. }
  666. return;
  667. }
  668. if (palette[color].unused == 255)
  669. {
  670. //Put row of RGB data
  671. for (size_t i=0; i<size; i++)
  672. ColorPutter<bpp, 1>::PutColor(dest, palette[*(data++)]);
  673. }
  674. else
  675. {
  676. //Put row of RGBA data
  677. for (size_t i=0; i<size; i++)
  678. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[*(data++)]);
  679. }
  680. }
  681. //RLE-d sequence
  682. else
  683. {
  684. if (alpha != 255 && palette[type].unused !=0)//Per-surface alpha is set
  685. {
  686. SDL_Color col = palette[type];
  687. col.unused = (int)col.unused*(255-alpha)/255;
  688. for (size_t i=0; i<size; i++)
  689. ColorPutter<bpp, 1>::PutColorAlpha(dest, col);
  690. return;
  691. }
  692. switch (palette[type].unused)
  693. {
  694. case 0:
  695. {
  696. //Skip row
  697. dest += size*bpp;
  698. break;
  699. }
  700. case 255:
  701. {
  702. //Put RGB row
  703. ColorPutter<bpp, 1>::PutColorRow(dest, palette[type], size);
  704. break;
  705. }
  706. default:
  707. {
  708. //Put RGBA row
  709. for (size_t i=0; i<size; i++)
  710. ColorPutter<bpp, 1>::PutColorAlpha(dest, palette[type]);
  711. break;
  712. }
  713. }
  714. }
  715. }
  716. void CompImage::playerColored(int player)
  717. {
  718. SDL_Color *pal = NULL;
  719. if(player < PLAYER_LIMIT && player >= 0)
  720. {
  721. pal = graphics->playerColorPalette + 32*player;
  722. }
  723. else if(player == 255 || player == -1)
  724. {
  725. pal = graphics->neutralColorPalette;
  726. }
  727. else
  728. assert(0);
  729. for(int i=0; i<32; ++i)
  730. {
  731. palette[224+i].r = pal[i].r;
  732. palette[224+i].g = pal[i].g;
  733. palette[224+i].b = pal[i].b;
  734. palette[224+i].unused = pal[i].unused;
  735. }
  736. }
  737. int CompImage::width() const
  738. {
  739. return fullSize.x;
  740. }
  741. int CompImage::height() const
  742. {
  743. return fullSize.y;
  744. }
  745. CompImage::~CompImage()
  746. {
  747. free(surf);
  748. delete [] line;
  749. delete [] palette;
  750. }
  751. /*************************************************************************
  752. * CAnimation for animations handling, can load part of file if needed *
  753. *************************************************************************/
  754. IImage * CAnimation::getFromExtraDef(std::string filename)
  755. {
  756. size_t pos = filename.find(':');
  757. if (pos == -1)
  758. return NULL;
  759. CAnimation anim(filename.substr(0, pos));
  760. pos++;
  761. size_t frame = atoi(filename.c_str()+pos);
  762. size_t group = 0;
  763. pos = filename.find(':', pos);
  764. if (pos != -1)
  765. {
  766. group = frame;
  767. frame = atoi(filename.c_str()+pos);
  768. }
  769. anim.load(frame ,group);
  770. IImage * ret = anim.images[group][frame];
  771. anim.images.clear();
  772. return ret;
  773. }
  774. bool CAnimation::loadFrame(CDefFile * file, size_t frame, size_t group)
  775. {
  776. if (size(group) <= frame)
  777. {
  778. printError(frame, group, "LoadFrame");
  779. return false;
  780. }
  781. IImage *image = getImage(frame, group, false);
  782. if (image)
  783. {
  784. image->increaseRef();
  785. return true;
  786. }
  787. //try to get image from def
  788. if (source[group][frame].getType() == JsonNode::DATA_NULL)
  789. {
  790. if (compressed)
  791. images[group][frame] = new CompImage(file, frame, group);
  792. else
  793. images[group][frame] = new SDLImage(file, frame, group);
  794. }
  795. else //load from separate file
  796. {
  797. std::string filename = source[group][frame].Struct().find("file")->second.String();
  798. IImage * img = getFromExtraDef(filename);
  799. if (!img)
  800. img = new SDLImage(filename, compressed);
  801. images[group][frame] = img;
  802. return true;
  803. }
  804. return false;
  805. }
  806. bool CAnimation::unloadFrame(size_t frame, size_t group)
  807. {
  808. IImage *image = getImage(frame, group, false);
  809. if (image)
  810. {
  811. //decrease ref count for image and delete if needed
  812. if (image->decreaseRef())
  813. {
  814. delete image;
  815. images[group].erase(frame);
  816. }
  817. if (images[group].empty())
  818. images.erase(group);
  819. return true;
  820. }
  821. return false;
  822. }
  823. void CAnimation::init(CDefFile * file)
  824. {
  825. if (file)
  826. {
  827. const std::map<size_t, size_t> defEntries = file->getEntries();
  828. for (std::map<size_t, size_t>::const_iterator mapIt = defEntries.begin(); mapIt!=defEntries.end(); ++mapIt)
  829. source[mapIt->first].resize(mapIt->second);
  830. }
  831. if (spriteh->haveFile(name, FILE_TEXT))
  832. {
  833. std::string configFile = spriteh->getTextFile(name);
  834. const JsonNode config(configFile);
  835. std::string basepath;
  836. if (!config["basepath"].isNull())
  837. basepath = config["basepath"].String();
  838. if (!config["sequences"].isNull())
  839. {
  840. const JsonVector &groups = config["sequences"].Vector();
  841. for (JsonVector::const_iterator groupsIter = groups.begin(); groupsIter!=groups.end(); ++groupsIter)
  842. {
  843. JsonNode group = *groupsIter;
  844. size_t groupID = group["group"].Float();//TODO: string-to-value conversion
  845. source[groupID].clear();
  846. const JsonVector &frames = group["frames"].Vector();
  847. for (JsonVector::const_iterator framesIter = frames.begin(); framesIter!=frames.end(); ++framesIter)
  848. {
  849. const JsonNode &frame = *framesIter;
  850. source[groupID].push_back(frame);
  851. std::string filename = frame["file"].String();
  852. source[groupID].back()["file"].String() = basepath + filename;
  853. }
  854. }
  855. }
  856. if (!config["images"].isNull())
  857. {
  858. const JsonVector &vector = config["images"].Vector();
  859. for (JsonVector::const_iterator it = vector.begin(); it!=vector.end(); ++it)
  860. {
  861. const JsonNode &node = *it;
  862. size_t group=0;
  863. if (!node["group"].isNull())
  864. group = node["group"].Float();
  865. size_t frame = node["frame"].Float();
  866. if (source[group].size() <= frame)
  867. source[group].resize(frame+1);
  868. source[group][frame] = node;
  869. std::string filename = node["file"].String();
  870. source[group][frame]["file"].String() = basepath + filename;
  871. }
  872. }
  873. }
  874. }
  875. CDefFile * CAnimation::getFile() const
  876. {
  877. if (spriteh->haveFile(name, FILE_ANIMATION))
  878. return new CDefFile(name);
  879. return NULL;
  880. }
  881. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  882. {
  883. tlog0 << type <<" error: Request for frame not present in CAnimation!\n"
  884. <<"\tFile name: "<<name<<" Group: "<<group<<" Frame: "<<frame<<"\n";
  885. }
  886. CAnimation::CAnimation(std::string Name, bool Compressed):
  887. name(Name),
  888. compressed(Compressed)
  889. {
  890. size_t dotPos = name.find_last_of('.');
  891. if ( dotPos!=-1 )
  892. name.erase(dotPos);
  893. std::transform(name.begin(), name.end(), name.begin(), toupper);
  894. CDefFile * file = getFile();
  895. init(file);
  896. delete file;
  897. loadedAnims.insert(this);
  898. }
  899. CAnimation::CAnimation():
  900. name(""),
  901. compressed(false)
  902. {
  903. init(NULL);
  904. loadedAnims.insert(this);
  905. }
  906. CAnimation::~CAnimation()
  907. {
  908. if (!images.empty())
  909. {
  910. tlog2<<"Warning: not all frames were unloaded from "<<name<<"\n";
  911. for (group_map::iterator group = images.begin(); group != images.end(); ++group )
  912. for (image_map::iterator image = group->second.begin(); image != group->second.end(); ++image )
  913. delete image->second;
  914. }
  915. loadedAnims.erase(this);
  916. }
  917. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  918. {
  919. if (source[group].size() <= frame)
  920. source[group].resize(frame+1);
  921. source[group][frame]["file"].String() = filename;
  922. //FIXME: update image if already loaded
  923. }
  924. IImage * CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  925. {
  926. group_map::const_iterator groupIter = images.find(group);
  927. if (groupIter != images.end())
  928. {
  929. image_map::const_iterator imageIter = groupIter->second.find(frame);
  930. if (imageIter != groupIter->second.end())
  931. return imageIter->second;
  932. }
  933. if (verbose)
  934. printError(frame, group, "GetImage");
  935. return NULL;
  936. }
  937. void CAnimation::load()
  938. {
  939. CDefFile * file = getFile();
  940. for (source_map::iterator group = source.begin(); group != source.end(); ++group )
  941. for (size_t image=0; image < group->second.size(); image++)
  942. loadFrame(file, image, group->first);
  943. delete file;
  944. }
  945. void CAnimation::unload()
  946. {
  947. for (source_map::iterator group = source.begin(); group != source.end(); ++group )
  948. for (size_t image=0; image < group->second.size(); image++)
  949. unloadFrame(image, group->first);
  950. }
  951. void CAnimation::loadGroup(size_t group)
  952. {
  953. CDefFile * file = getFile();
  954. if (vstd::contains(source, group))
  955. for (size_t image=0; image < source[group].size(); image++)
  956. loadFrame(file, image, group);
  957. delete file;
  958. }
  959. void CAnimation::unloadGroup(size_t group)
  960. {
  961. if (vstd::contains(source, group))
  962. for (size_t image=0; image < source[group].size(); image++)
  963. unloadFrame(image, group);
  964. }
  965. void CAnimation::load(size_t frame, size_t group)
  966. {
  967. CDefFile * file = getFile();
  968. loadFrame(file, frame, group);
  969. delete file;
  970. }
  971. void CAnimation::unload(size_t frame, size_t group)
  972. {
  973. unloadFrame(frame, group);
  974. }
  975. size_t CAnimation::size(size_t group) const
  976. {
  977. source_map::const_iterator iter = source.find(group);
  978. if (iter != source.end())
  979. return iter->second.size();
  980. return 0;
  981. }
  982. std::set<CAnimation*> CAnimation::loadedAnims;
  983. void CAnimation::getAnimInfo()
  984. {
  985. tlog1<<"Animation stats: Loaded "<<loadedAnims.size()<<" total\n";
  986. for (std::set<CAnimation*>::iterator it = loadedAnims.begin(); it != loadedAnims.end(); it++)
  987. {
  988. CAnimation * anim = *it;
  989. tlog1<<"Name: "<<anim->name<<" Groups: "<<anim->images.size();
  990. if (!anim->images.empty())
  991. tlog1<<", "<<anim->images.begin()->second.size()<<" image loaded in group "<< anim->images.begin()->first;
  992. tlog1<<"\n";
  993. }
  994. }
  995. CAnimImage::CAnimImage(std::string name, size_t Frame, size_t Group, int x, int y, unsigned char Flags):
  996. frame(Frame),
  997. group(Group),
  998. player(-1),
  999. flags(Flags)
  1000. {
  1001. pos.x += x;
  1002. pos.y += y;
  1003. anim = new CAnimation(name);
  1004. init();
  1005. }
  1006. CAnimImage::CAnimImage(CAnimation *Anim, size_t Frame, size_t Group, int x, int y, unsigned char Flags):
  1007. anim(Anim),
  1008. frame(Frame),
  1009. group(Group),
  1010. player(-1),
  1011. flags(Flags)
  1012. {
  1013. pos.x += x;
  1014. pos.y += y;
  1015. init();
  1016. }
  1017. size_t CAnimImage::size()
  1018. {
  1019. return anim->size(group);
  1020. }
  1021. void CAnimImage::init()
  1022. {
  1023. anim->load(frame, group);
  1024. if (flags & CShowableAnim::BASE)
  1025. anim->load(0,group);
  1026. IImage *img = anim->getImage(frame, group);
  1027. if (img)
  1028. {
  1029. pos.w = img->width();
  1030. pos.h = img->height();
  1031. }
  1032. }
  1033. CAnimImage::~CAnimImage()
  1034. {
  1035. anim->unload(frame, group);
  1036. if (flags & CShowableAnim::BASE)
  1037. anim->unload(0,group);
  1038. delete anim;
  1039. }
  1040. void CAnimImage::showAll(SDL_Surface *to)
  1041. {
  1042. IImage *img = anim->getImage(frame, group);
  1043. if (img)
  1044. img->draw(to, pos.x, pos.y);
  1045. }
  1046. void CAnimImage::setFrame(size_t Frame, size_t Group)
  1047. {
  1048. if (frame == Frame && group==Group)
  1049. return;
  1050. if (anim->size(Group) > Frame)
  1051. {
  1052. anim->load(Frame, Group);
  1053. anim->unload(frame, group);
  1054. frame = Frame;
  1055. group = Group;
  1056. IImage *img = anim->getImage(frame, group);
  1057. if (img)
  1058. {
  1059. if (flags & CShowableAnim::PLAYER_COLORED)
  1060. img->playerColored(player);
  1061. pos.w = img->width();
  1062. pos.h = img->height();
  1063. }
  1064. }
  1065. }
  1066. void CAnimImage::playerColored(int currPlayer)
  1067. {
  1068. player = currPlayer;
  1069. flags |= CShowableAnim::PLAYER_COLORED;
  1070. anim->getImage(frame, group)->playerColored(player);
  1071. if (flags & CShowableAnim::BASE)
  1072. anim->getImage(0, group)->playerColored(player);
  1073. }
  1074. CShowableAnim::CShowableAnim(int x, int y, std::string name, unsigned char Flags, unsigned int Delay, size_t Group):
  1075. anim(name, Flags & USE_RLE),
  1076. group(Group),
  1077. frame(0),
  1078. first(0),
  1079. frameDelay(Delay),
  1080. value(0),
  1081. flags(Flags),
  1082. xOffset(0),
  1083. yOffset(0),
  1084. alpha(255)
  1085. {
  1086. anim.loadGroup(group);
  1087. last = anim.size(group);
  1088. pos.w = anim.getImage(0, group)->width();
  1089. pos.h = anim.getImage(0, group)->height();
  1090. pos.x+= x;
  1091. pos.y+= y;
  1092. }
  1093. CShowableAnim::~CShowableAnim()
  1094. {
  1095. anim.unloadGroup(group);
  1096. }
  1097. void CShowableAnim::setAlpha(unsigned int alphaValue)
  1098. {
  1099. alpha = std::min<unsigned int>(alphaValue, 255);
  1100. }
  1101. bool CShowableAnim::set(size_t Group, size_t from, size_t to)
  1102. {
  1103. size_t max = anim.size(Group);
  1104. if (max>to)
  1105. max = to;
  1106. if (max < from || max == 0)
  1107. return false;
  1108. anim.load(Group);
  1109. anim.unload(group);
  1110. group = Group;
  1111. frame = first = from;
  1112. last = max;
  1113. value = 0;
  1114. return true;
  1115. }
  1116. bool CShowableAnim::set(size_t Group)
  1117. {
  1118. if (anim.size(Group)== 0)
  1119. return false;
  1120. if (group != Group)
  1121. {
  1122. anim.loadGroup(Group);
  1123. anim.unloadGroup(group);
  1124. first = 0;
  1125. group = Group;
  1126. last = anim.size(Group);
  1127. }
  1128. frame = value = 0;
  1129. return true;
  1130. }
  1131. void CShowableAnim::reset()
  1132. {
  1133. value = 0;
  1134. frame = first;
  1135. if (callback)
  1136. callback();
  1137. }
  1138. void CShowableAnim::clipRect(int posX, int posY, int width, int height)
  1139. {
  1140. xOffset = posX;
  1141. yOffset = posY;
  1142. pos.w = width;
  1143. pos.h = height;
  1144. }
  1145. void CShowableAnim::show(SDL_Surface *to)
  1146. {
  1147. if ( flags & BASE && frame != first)
  1148. blitImage(first, group, to);
  1149. blitImage(frame, group, to);
  1150. if ( ++value == frameDelay )
  1151. {
  1152. value = 0;
  1153. if ( ++frame == last)
  1154. reset();
  1155. }
  1156. }
  1157. void CShowableAnim::showAll(SDL_Surface *to)
  1158. {
  1159. if ( flags & BASE && frame != first)
  1160. blitImage(first, group, to);
  1161. blitImage(frame, group, to);
  1162. }
  1163. void CShowableAnim::blitImage(size_t frame, size_t group, SDL_Surface *to)
  1164. {
  1165. assert(to);
  1166. Rect src( xOffset, yOffset, pos.w, pos.h);
  1167. IImage * img = anim.getImage(frame, group);
  1168. if (img)
  1169. img->draw(to, pos.x-xOffset, pos.y-yOffset, &src, alpha);
  1170. }
  1171. void CShowableAnim::rotate(bool on, bool vertical)
  1172. {
  1173. unsigned char flag = vertical? VERTICAL_FLIP:HORIZONTAL_FLIP;
  1174. if (on)
  1175. flags |= flag;
  1176. else
  1177. flags &= ~flag;
  1178. }
  1179. CCreatureAnim::CCreatureAnim(int x, int y, std::string name, Rect picPos, unsigned char flags, EAnimType type):
  1180. CShowableAnim(x,y,name,flags,3,type)
  1181. {
  1182. xOffset = picPos.x;
  1183. yOffset = picPos.y;
  1184. if (picPos.w)
  1185. pos.w = picPos.w;
  1186. if (picPos.h)
  1187. pos.h = picPos.h;
  1188. };
  1189. void CCreatureAnim::loopPreview()
  1190. {
  1191. std::vector<EAnimType> available;
  1192. static const EAnimType previewList[] = {HOLDING, HITTED, DEFENCE, ATTACK_FRONT, CAST_FRONT};
  1193. for (size_t i=0; i<5; i++)
  1194. if (anim.size(previewList[i]))
  1195. available.push_back(previewList[i]);
  1196. size_t rnd = rand()%(available.size()*2);
  1197. if (rnd >= available.size())
  1198. {
  1199. if ( anim.size(MOVING) == 0 )//no moving animation present
  1200. addLast( HOLDING );
  1201. else
  1202. addLast( MOVING ) ;
  1203. }
  1204. else
  1205. addLast(available[rnd]);
  1206. }
  1207. void CCreatureAnim::addLast(EAnimType newType)
  1208. {
  1209. if (type != MOVING && newType == MOVING)//starting moving - play init sequence
  1210. {
  1211. queue.push( MOVE_START );
  1212. }
  1213. else if (type == MOVING && newType != MOVING )//previous anim was moving - finish it
  1214. {
  1215. queue.push( MOVE_END );
  1216. }
  1217. if (newType == TURN_L || newType == TURN_R)
  1218. queue.push(newType);
  1219. queue.push(newType);
  1220. }
  1221. void CCreatureAnim::reset()
  1222. {
  1223. //if we are in the middle of rotation - set flag
  1224. if (type == TURN_L && !queue.empty() && queue.front() == TURN_L)
  1225. rotate(true);
  1226. if (type == TURN_R && !queue.empty() && queue.front() == TURN_R)
  1227. rotate(false);
  1228. while (!queue.empty())
  1229. {
  1230. EAnimType at = queue.front();
  1231. queue.pop();
  1232. if (set(at))
  1233. return;
  1234. }
  1235. if (callback)
  1236. callback();
  1237. while (!queue.empty())
  1238. {
  1239. EAnimType at = queue.front();
  1240. queue.pop();
  1241. if (set(at))
  1242. return;
  1243. }
  1244. set(HOLDING);
  1245. }
  1246. void CCreatureAnim::startPreview()
  1247. {
  1248. callback = boost::bind(&CCreatureAnim::loopPreview,this);
  1249. }
  1250. void CCreatureAnim::clearAndSet(EAnimType type)
  1251. {
  1252. while (!queue.empty())
  1253. queue.pop();
  1254. set(type);
  1255. }