CAnimation.cpp 32 KB

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