CAnimation.cpp 32 KB

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