CCreatureAnimation.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. #include "StdInc.h"
  2. #include "CCreatureAnimation.h"
  3. #include "../../lib/vcmi_endian.h"
  4. #include "../../lib/CConfigHandler.h"
  5. #include "../../lib/CCreatureHandler.h"
  6. #include "../../lib/filesystem/Filesystem.h"
  7. #include "../../lib/filesystem/CBinaryReader.h"
  8. #include "../../lib/filesystem/CMemoryStream.h"
  9. #include "../gui/SDL_Pixels.h"
  10. /*
  11. * CCreatureAnimation.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. static const SDL_Color creatureBlueBorder = { 0, 255, 255, 255 };
  20. static const SDL_Color creatureGoldBorder = { 255, 255, 0, 255 };
  21. static const SDL_Color creatureNoBorder = { 0, 0, 0, 0 };
  22. SDL_Color AnimationControls::getBlueBorder()
  23. {
  24. return creatureBlueBorder;
  25. }
  26. SDL_Color AnimationControls::getGoldBorder()
  27. {
  28. return creatureGoldBorder;
  29. }
  30. SDL_Color AnimationControls::getNoBorder()
  31. {
  32. return creatureNoBorder;
  33. }
  34. CCreatureAnimation * AnimationControls::getAnimation(const CCreature * creature)
  35. {
  36. auto func = std::bind(&AnimationControls::getCreatureAnimationSpeed, creature, _1, _2);
  37. return new CCreatureAnimation(creature->animDefName, func);
  38. }
  39. float AnimationControls::getCreatureAnimationSpeed(const CCreature * creature, const CCreatureAnimation * anim, size_t group)
  40. {
  41. CCreatureAnim::EAnimType type = CCreatureAnim::EAnimType(group);
  42. assert(creature->animation.walkAnimationTime != 0);
  43. assert(creature->animation.attackAnimationTime != 0);
  44. assert(anim->framesInGroup(type) != 0);
  45. // possible new fields for creature format:
  46. //split "Attack time" into "Shoot Time" and "Cast Time"
  47. // a lot of arbitrary multipliers, mostly to make animation speed closer to H3
  48. const float baseSpeed = 0.1;
  49. const float speedMult = settings["battle"]["animationSpeed"].Float();
  50. const float speed = baseSpeed / speedMult;
  51. switch (type)
  52. {
  53. case CCreatureAnim::MOVING:
  54. return speed * 2 * creature->animation.walkAnimationTime / anim->framesInGroup(type);
  55. case CCreatureAnim::MOUSEON:
  56. return baseSpeed;
  57. case CCreatureAnim::HOLDING:
  58. return baseSpeed * creature->animation.idleAnimationTime / anim->framesInGroup(type);
  59. case CCreatureAnim::SHOOT_UP:
  60. case CCreatureAnim::SHOOT_FRONT:
  61. case CCreatureAnim::SHOOT_DOWN:
  62. case CCreatureAnim::CAST_UP:
  63. case CCreatureAnim::CAST_FRONT:
  64. case CCreatureAnim::CAST_DOWN:
  65. return speed * 4 * creature->animation.attackAnimationTime / anim->framesInGroup(type);
  66. // as strange as it looks like "attackAnimationTime" does not affects melee attacks
  67. // necessary because length of these animations must be same for all creatures for synchronization
  68. case CCreatureAnim::ATTACK_UP:
  69. case CCreatureAnim::ATTACK_FRONT:
  70. case CCreatureAnim::ATTACK_DOWN:
  71. case CCreatureAnim::HITTED:
  72. case CCreatureAnim::DEFENCE:
  73. case CCreatureAnim::DEATH:
  74. return speed * 3 / anim->framesInGroup(type);
  75. case CCreatureAnim::TURN_L:
  76. case CCreatureAnim::TURN_R:
  77. return speed / 3;
  78. case CCreatureAnim::MOVE_START:
  79. case CCreatureAnim::MOVE_END:
  80. return speed / 3;
  81. case CCreatureAnim::DEAD:
  82. return speed;
  83. default:
  84. assert(0);
  85. return 1;
  86. }
  87. }
  88. float AnimationControls::getProjectileSpeed()
  89. {
  90. return settings["battle"]["animationSpeed"].Float() * 100;
  91. }
  92. float AnimationControls::getSpellEffectSpeed()
  93. {
  94. return settings["battle"]["animationSpeed"].Float() * 60;
  95. }
  96. float AnimationControls::getMovementDuration(const CCreature * creature)
  97. {
  98. return settings["battle"]["animationSpeed"].Float() * 4 / creature->animation.walkAnimationTime;
  99. }
  100. float AnimationControls::getFlightDistance(const CCreature * creature)
  101. {
  102. return creature->animation.flightAnimationDistance * 200;
  103. }
  104. CCreatureAnim::EAnimType CCreatureAnimation::getType() const
  105. {
  106. return type;
  107. }
  108. void CCreatureAnimation::setType(CCreatureAnim::EAnimType type)
  109. {
  110. assert(type >= 0);
  111. assert(framesInGroup(type) != 0);
  112. this->type = type;
  113. currentFrame = 0;
  114. once = false;
  115. play();
  116. }
  117. CCreatureAnimation::CCreatureAnimation(std::string name, TSpeedController controller)
  118. : defName(name),
  119. speed(0.1),
  120. currentFrame(0),
  121. elapsedTime(0),
  122. type(CCreatureAnim::HOLDING),
  123. border(CSDL_Ext::makeColor(0, 0, 0, 0)),
  124. speedController(controller),
  125. once(false)
  126. {
  127. // separate block to avoid accidental use of "data" after it was moved into "pixelData"
  128. {
  129. ResourceID resID(std::string("SPRITES/") + name, EResType::ANIMATION);
  130. auto data = CResourceHandler::get()->load(resID)->readAll();
  131. pixelData = std::move(data.first);
  132. pixelDataSize = data.second;
  133. }
  134. CMemoryStream stm(pixelData.get(), pixelDataSize);
  135. CBinaryReader reader(&stm);
  136. reader.readInt32(); // def type, unused
  137. fullWidth = reader.readInt32();
  138. fullHeight = reader.readInt32();
  139. int totalBlocks = reader.readInt32();
  140. for (auto & elem : palette)
  141. {
  142. elem.r = reader.readUInt8();
  143. elem.g = reader.readUInt8();
  144. elem.b = reader.readUInt8();
  145. elem.a = SDL_ALPHA_OPAQUE;
  146. }
  147. for (int i=0; i<totalBlocks; i++)
  148. {
  149. int groupID = reader.readInt32();
  150. int totalInBlock = reader.readInt32();
  151. reader.skip(4 + 4 + 13 * totalInBlock); // some unused data
  152. for (int j=0; j<totalInBlock; j++)
  153. dataOffsets[groupID].push_back(reader.readUInt32());
  154. }
  155. // if necessary, add one frame into vcmi-only group DEAD
  156. if (dataOffsets.count(CCreatureAnim::DEAD) == 0)
  157. dataOffsets[CCreatureAnim::DEAD].push_back(dataOffsets[CCreatureAnim::DEATH].back());
  158. play();
  159. }
  160. void CCreatureAnimation::endAnimation()
  161. {
  162. once = false;
  163. auto copy = onAnimationReset;
  164. onAnimationReset.clear();
  165. copy();
  166. }
  167. bool CCreatureAnimation::incrementFrame(float timePassed)
  168. {
  169. elapsedTime += timePassed;
  170. currentFrame += timePassed * speed;
  171. if (currentFrame >= float(framesInGroup(type)))
  172. {
  173. // just in case of extremely low fps (or insanely high speed)
  174. while (currentFrame >= float(framesInGroup(type)))
  175. currentFrame -= framesInGroup(type);
  176. if (once)
  177. setType(CCreatureAnim::HOLDING);
  178. endAnimation();
  179. return true;
  180. }
  181. return false;
  182. }
  183. void CCreatureAnimation::setBorderColor(SDL_Color palette)
  184. {
  185. border = palette;
  186. }
  187. int CCreatureAnimation::getWidth() const
  188. {
  189. return fullWidth;
  190. }
  191. int CCreatureAnimation::getHeight() const
  192. {
  193. return fullHeight;
  194. }
  195. float CCreatureAnimation::getCurrentFrame() const
  196. {
  197. return currentFrame;
  198. }
  199. void CCreatureAnimation::playOnce( CCreatureAnim::EAnimType type )
  200. {
  201. setType(type);
  202. once = true;
  203. }
  204. inline int getBorderStrength(float time)
  205. {
  206. float borderStrength = fabs(vstd::round(time) - time) * 2; // generate value in range 0-1
  207. return borderStrength * 155 + 100; // scale to 0-255
  208. }
  209. static SDL_Color genShadow(ui8 alpha)
  210. {
  211. return CSDL_Ext::makeColor(0, 0, 0, alpha);
  212. }
  213. static SDL_Color genBorderColor(ui8 alpha, const SDL_Color & base)
  214. {
  215. return CSDL_Ext::makeColor(base.r, base.g, base.b, ui8(base.a * alpha / 256));
  216. }
  217. static ui8 mixChannels(ui8 c1, ui8 c2, ui8 a1, ui8 a2)
  218. {
  219. return c1*a1 / 256 + c2*a2*(255 - a1) / 256 / 256;
  220. }
  221. static SDL_Color addColors(const SDL_Color & base, const SDL_Color & over)
  222. {
  223. return CSDL_Ext::makeColor(
  224. mixChannels(over.r, base.r, over.a, base.a),
  225. mixChannels(over.g, base.g, over.a, base.a),
  226. mixChannels(over.b, base.b, over.a, base.a),
  227. ui8(over.a + base.a * (255 - over.a) / 256)
  228. );
  229. }
  230. std::array<SDL_Color, 8> CCreatureAnimation::genSpecialPalette()
  231. {
  232. std::array<SDL_Color, 8> ret;
  233. ret[0] = genShadow(0);
  234. ret[1] = genShadow(64);
  235. ret[2] = genShadow(128);
  236. ret[3] = genShadow(128);
  237. ret[4] = genShadow(128);
  238. ret[5] = genBorderColor(getBorderStrength(elapsedTime), border);
  239. ret[6] = addColors(genShadow(128), genBorderColor(getBorderStrength(elapsedTime), border));
  240. ret[7] = addColors(genShadow(64), genBorderColor(getBorderStrength(elapsedTime), border));
  241. return ret;
  242. }
  243. template<int bpp>
  244. void CCreatureAnimation::nextFrameT(SDL_Surface * dest, bool rotate)
  245. {
  246. assert(dataOffsets.count(type) && dataOffsets.at(type).size() > size_t(currentFrame));
  247. ui32 offset = dataOffsets.at(type).at(floor(currentFrame));
  248. CMemoryStream stm(pixelData.get(), pixelDataSize);
  249. CBinaryReader reader(&stm);
  250. reader.getStream()->seek(offset);
  251. reader.readUInt32(); // unused, size of pixel data for this frame
  252. const ui32 defType2 = reader.readUInt32();
  253. const ui32 fullWidth = reader.readUInt32();
  254. /*const ui32 fullHeight =*/ reader.readUInt32();
  255. const ui32 spriteWidth = reader.readUInt32();
  256. const ui32 spriteHeight = reader.readUInt32();
  257. const int leftMargin = reader.readInt32();
  258. const int topMargin = reader.readInt32();
  259. const int rightMargin = fullWidth - spriteWidth - leftMargin;
  260. //const int bottomMargin = fullHeight - spriteHeight - topMargin;
  261. const size_t baseOffset = reader.getStream()->tell();
  262. assert(defType2 == 1);
  263. UNUSED(defType2);
  264. auto specialPalette = genSpecialPalette();
  265. for (ui32 i=0; i<spriteHeight; i++)
  266. {
  267. //NOTE: if this loop will be optimized to skip empty lines - recheck this read access
  268. ui8 * lineData = pixelData.get() + baseOffset + reader.readUInt32();
  269. size_t destX = pos.x;
  270. if (rotate)
  271. destX += rightMargin + spriteWidth - 1;
  272. else
  273. destX += leftMargin;
  274. size_t destY = pos.y + topMargin + i;
  275. size_t currentOffset = 0;
  276. size_t totalRowLength = 0;
  277. while (totalRowLength < spriteWidth)
  278. {
  279. ui8 type = lineData[currentOffset++];
  280. ui32 length = lineData[currentOffset++] + 1;
  281. if (type==0xFF)//Raw data
  282. {
  283. for (size_t j=0; j<length; j++)
  284. putPixelAt<bpp>(dest, destX + (rotate?(-j):(j)), destY, lineData[currentOffset + j], specialPalette);
  285. currentOffset += length;
  286. }
  287. else// RLE
  288. {
  289. if (type != 0) // transparency row, handle it here for speed
  290. {
  291. for (size_t j=0; j<length; j++)
  292. putPixelAt<bpp>(dest, destX + (rotate?(-j):(j)), destY, type, specialPalette);
  293. }
  294. }
  295. destX += rotate ? (-length) : (length);
  296. totalRowLength += length;
  297. }
  298. }
  299. }
  300. void CCreatureAnimation::nextFrame(SDL_Surface *dest, bool attacker)
  301. {
  302. // Note: please notice that attacker value is inversed when passed further.
  303. // This is intended behavior because "attacker" actually does not needs rotation
  304. switch(dest->format->BytesPerPixel)
  305. {
  306. case 2: return nextFrameT<2>(dest, !attacker);
  307. case 3: return nextFrameT<3>(dest, !attacker);
  308. case 4: return nextFrameT<4>(dest, !attacker);
  309. default:
  310. logGlobal->errorStream() << (int)dest->format->BitsPerPixel << " bpp is not supported!!!";
  311. }
  312. }
  313. int CCreatureAnimation::framesInGroup(CCreatureAnim::EAnimType group) const
  314. {
  315. if(dataOffsets.count(group) == 0)
  316. return 0;
  317. return dataOffsets.at(group).size();
  318. }
  319. ui8 * CCreatureAnimation::getPixelAddr(SDL_Surface * dest, int X, int Y) const
  320. {
  321. return (ui8*)dest->pixels + X * dest->format->BytesPerPixel + Y * dest->pitch;
  322. }
  323. template<int bpp>
  324. inline void CCreatureAnimation::putPixelAt(SDL_Surface * dest, int X, int Y, size_t index, const std::array<SDL_Color, 8> & special) const
  325. {
  326. if ( X < pos.x + pos.w && Y < pos.y + pos.h && X >= 0 && Y >= 0)
  327. putPixel<bpp>(getPixelAddr(dest, X, Y), palette[index], index, special);
  328. }
  329. template<int bpp>
  330. inline void CCreatureAnimation::putPixel(ui8 * dest, const SDL_Color & color, size_t index, const std::array<SDL_Color, 8> & special) const
  331. {
  332. if (index < 8)
  333. {
  334. const SDL_Color & pal = special[index];
  335. ColorPutter<bpp, 0>::PutColor(dest, pal.r, pal.g, pal.b, pal.a);
  336. }
  337. else
  338. {
  339. ColorPutter<bpp, 0>::PutColor(dest, color.r, color.g, color.b);
  340. }
  341. }
  342. bool CCreatureAnimation::isDead() const
  343. {
  344. return getType() == CCreatureAnim::DEAD
  345. || getType() == CCreatureAnim::DEATH;
  346. }
  347. bool CCreatureAnimation::isIdle() const
  348. {
  349. return getType() == CCreatureAnim::HOLDING
  350. || getType() == CCreatureAnim::MOUSEON;
  351. }
  352. bool CCreatureAnimation::isMoving() const
  353. {
  354. return getType() == CCreatureAnim::MOVE_START
  355. || getType() == CCreatureAnim::MOVING
  356. || getType() == CCreatureAnim::MOVE_END;
  357. }
  358. bool CCreatureAnimation::isShooting() const
  359. {
  360. return getType() == CCreatureAnim::SHOOT_UP
  361. || getType() == CCreatureAnim::SHOOT_FRONT
  362. || getType() == CCreatureAnim::SHOOT_DOWN;
  363. }
  364. void CCreatureAnimation::pause()
  365. {
  366. speed = 0;
  367. }
  368. void CCreatureAnimation::play()
  369. {
  370. speed = 0;
  371. if (speedController(this, type) != 0)
  372. speed = 1 / speedController(this, type);
  373. }