CBattleStacksController.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /*
  2. * CBattleStacksController.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CBattleStacksController.h"
  12. #include "CBattleSiegeController.h"
  13. #include "CBattleInterfaceClasses.h"
  14. #include "CBattleInterface.h"
  15. #include "CBattleAnimations.h"
  16. #include "CBattleFieldController.h"
  17. #include "CBattleEffectsController.h"
  18. #include "CBattleProjectileController.h"
  19. #include "CBattleControlPanel.h"
  20. #include "../gui/CAnimation.h"
  21. #include "../gui/SDL_Extensions.h"
  22. #include "../gui/CGuiHandler.h"
  23. #include "../../lib/battle/BattleHex.h"
  24. #include "../CPlayerInterface.h"
  25. #include "CCreatureAnimation.h"
  26. #include "../../lib/CGameState.h"
  27. #include "../../CCallback.h"
  28. #include "../../lib/CStack.h"
  29. #include "../../lib/CondSh.h"
  30. #include "../CMusicHandler.h"
  31. #include "../CGameInfo.h"
  32. static void onAnimationFinished(const CStack *stack, std::weak_ptr<CCreatureAnimation> anim)
  33. {
  34. std::shared_ptr<CCreatureAnimation> animation = anim.lock();
  35. if(!animation)
  36. return;
  37. if (animation->isIdle())
  38. {
  39. const CCreature *creature = stack->getCreature();
  40. if (animation->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  41. {
  42. if (CRandomGenerator::getDefault().nextDouble(99.0) < creature->animation.timeBetweenFidgets *10)
  43. animation->playOnce(CCreatureAnim::MOUSEON);
  44. else
  45. animation->setType(CCreatureAnim::HOLDING);
  46. }
  47. else
  48. {
  49. animation->setType(CCreatureAnim::HOLDING);
  50. }
  51. }
  52. // always reset callback
  53. animation->onAnimationReset += std::bind(&onAnimationFinished, stack, anim);
  54. }
  55. CBattleStacksController::CBattleStacksController(CBattleInterface * owner):
  56. owner(owner)
  57. {
  58. //preparing graphics for displaying amounts of creatures
  59. amountNormal = IImage::createFromFile("CMNUMWIN.BMP");
  60. amountPositive = IImage::createFromFile("CMNUMWIN.BMP");
  61. amountNegative = IImage::createFromFile("CMNUMWIN.BMP");
  62. amountEffNeutral = IImage::createFromFile("CMNUMWIN.BMP");
  63. ColorShifterAddMulExcept shifterNormal ({0,0,0,0}, {150, 48, 237, 255}, {132, 231, 255, 255});
  64. ColorShifterAddMulExcept shifterPositive({0,0,0,0}, { 45, 255, 45, 255}, {132, 231, 255, 255});
  65. ColorShifterAddMulExcept shifterNegative({0,0,0,0}, {255, 45, 45, 255}, {132, 231, 255, 255});
  66. ColorShifterAddMulExcept shifterNeutral ({0,0,0,0}, {255, 255, 45, 255}, {132, 231, 255, 255});
  67. amountNormal->adjustPalette(&shifterNormal);
  68. amountPositive->adjustPalette(&shifterPositive);
  69. amountNegative->adjustPalette(&shifterNegative);
  70. amountEffNeutral->adjustPalette(&shifterNeutral);
  71. std::vector<const CStack*> stacks = owner->curInt->cb->battleGetAllStacks(true);
  72. for(const CStack * s : stacks)
  73. {
  74. stackAdded(s);
  75. }
  76. }
  77. void CBattleStacksController::showBattlefieldObjects(SDL_Surface *to, const BattleHex & location )
  78. {
  79. auto getCurrentPosition = [&](const CStack *stack) -> BattleHex
  80. {
  81. for (auto & anim : pendingAnims)
  82. {
  83. // certainly ugly workaround but fixes quite annoying bug
  84. // stack position will be updated only *after* movement is finished
  85. // before this - stack is always at its initial position. Thus we need to find
  86. // its current position. Which can be found only in this class
  87. if (CMovementAnimation *move = dynamic_cast<CMovementAnimation*>(anim.first))
  88. {
  89. if (move->stack == stack)
  90. return move->nextHex;
  91. }
  92. }
  93. return stack->getPosition();
  94. };
  95. auto stacks = owner->curInt->cb->battleGetAllStacks(true);
  96. for (auto & stack : stacks)
  97. {
  98. if (creAnims.find(stack->ID) == creAnims.end()) //e.g. for summoned but not yet handled stacks
  99. continue;
  100. //if (stack->initialPosition < 0) // turret shooters are handled separately
  101. // continue;
  102. //FIXME: hack to ignore ghost stacks
  103. if ((creAnims[stack->ID]->getType() == CCreatureAnim::DEAD || creAnims[stack->ID]->getType() == CCreatureAnim::HOLDING) && stack->isGhost())
  104. continue;//ignore
  105. if (creAnims[stack->ID]->isDead())
  106. {
  107. //if ( location == stack->getPosition() )
  108. if ( location == BattleHex::HEX_BEFORE_ALL ) //FIXME: any cases when this won't work?
  109. {};
  110. continue;
  111. }
  112. // standing - blit at current position
  113. if (!creAnims[stack->ID]->isMoving())
  114. {
  115. if ( location == stack->getPosition() )
  116. {};
  117. continue;
  118. }
  119. // flying creature - just blit them over everyone else
  120. if (stack->hasBonusOfType(Bonus::FLYING))
  121. {
  122. if ( location == BattleHex::HEX_AFTER_ALL)
  123. {};
  124. continue;
  125. }
  126. // else - unit moving on ground
  127. {
  128. if ( location == getCurrentPosition(stack) )
  129. {};
  130. continue;
  131. }
  132. }
  133. }
  134. void CBattleStacksController::stackReset(const CStack * stack)
  135. {
  136. auto iter = creAnims.find(stack->ID);
  137. if(iter == creAnims.end())
  138. {
  139. logGlobal->error("Unit %d have no animation", stack->ID);
  140. return;
  141. }
  142. auto animation = iter->second;
  143. if(stack->alive() && animation->isDead())
  144. animation->setType(CCreatureAnim::HOLDING);
  145. if (stack->isClone())
  146. {
  147. auto shifter = ColorShifterAddMul::deepBlue();
  148. animation->shiftColor(&shifter);
  149. }
  150. //TODO: handle more cases
  151. }
  152. void CBattleStacksController::stackAdded(const CStack * stack)
  153. {
  154. creDir[stack->ID] = stack->side == BattleSide::ATTACKER; // must be set before getting stack position
  155. Point coords = CClickableHex::getXYUnitAnim(stack->getPosition(), stack, owner);
  156. if(stack->initialPosition < 0) //turret
  157. {
  158. assert(owner->siegeController);
  159. const CCreature *turretCreature = owner->siegeController->getTurretCreature();
  160. creAnims[stack->ID] = AnimationControls::getAnimation(turretCreature);
  161. creAnims[stack->ID]->pos.h = 225;
  162. coords = owner->siegeController->getTurretCreaturePosition(stack->initialPosition);
  163. }
  164. else
  165. {
  166. creAnims[stack->ID] = AnimationControls::getAnimation(stack->getCreature());
  167. creAnims[stack->ID]->onAnimationReset += std::bind(&onAnimationFinished, stack, creAnims[stack->ID]);
  168. creAnims[stack->ID]->pos.h = creAnims[stack->ID]->getHeight();
  169. }
  170. creAnims[stack->ID]->pos.x = coords.x;
  171. creAnims[stack->ID]->pos.y = coords.y;
  172. creAnims[stack->ID]->pos.w = creAnims[stack->ID]->getWidth();
  173. creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  174. }
  175. void CBattleStacksController::setActiveStack(const CStack *stack)
  176. {
  177. if (activeStack) // update UI
  178. creAnims[activeStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  179. activeStack = stack;
  180. if (activeStack) // update UI
  181. creAnims[activeStack->ID]->setBorderColor(AnimationControls::getGoldBorder());
  182. owner->controlPanel->blockUI(activeStack == nullptr);
  183. }
  184. void CBattleStacksController::setHoveredStack(const CStack *stack)
  185. {
  186. if ( stack == mouseHoveredStack )
  187. return;
  188. if (mouseHoveredStack)
  189. creAnims[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getNoBorder());
  190. // stack must be alive and not active (which uses gold border instead)
  191. if (stack && stack->alive() && stack != activeStack)
  192. {
  193. mouseHoveredStack = stack;
  194. if (mouseHoveredStack)
  195. {
  196. creAnims[mouseHoveredStack->ID]->setBorderColor(AnimationControls::getBlueBorder());
  197. if (creAnims[mouseHoveredStack->ID]->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  198. creAnims[mouseHoveredStack->ID]->playOnce(CCreatureAnim::MOUSEON);
  199. }
  200. }
  201. else
  202. mouseHoveredStack = nullptr;
  203. }
  204. bool CBattleStacksController::stackNeedsAmountBox(const CStack * stack)
  205. {
  206. BattleHex currentActionTarget;
  207. if(owner->curInt->curAction)
  208. {
  209. auto target = owner->curInt->curAction->getTarget(owner->curInt->cb.get());
  210. if(!target.empty())
  211. currentActionTarget = target.at(0).hexValue;
  212. }
  213. if(!stack->alive())
  214. return false;
  215. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON) && stack->getCount() == 1) //do not show box for singular war machines, stacked war machines with box shown are supported as extension feature
  216. return false;
  217. if(stack->getCount() == 0) //hide box when target is going to die anyway - do not display "0 creatures"
  218. return false;
  219. for(auto anim : pendingAnims) //no matter what other conditions below are, hide box when creature is playing hit animation
  220. {
  221. auto hitAnimation = dynamic_cast<CDefenceAnimation*>(anim.first);
  222. if(hitAnimation && (hitAnimation->stack->ID == stack->ID)) //we process only "current creature" as other creatures will be processed reliably on their own iteration
  223. return false;
  224. }
  225. if(owner->curInt->curAction)
  226. {
  227. if(owner->curInt->curAction->stackNumber == stack->ID) //stack is currently taking action (is not a target of another creature's action etc)
  228. {
  229. if(owner->curInt->curAction->actionType == EActionType::WALK || owner->curInt->curAction->actionType == EActionType::SHOOT) //hide when stack walks or shoots
  230. return false;
  231. else if(owner->curInt->curAction->actionType == EActionType::WALK_AND_ATTACK && currentActionTarget != stack->getPosition()) //when attacking, hide until walk phase finished
  232. return false;
  233. }
  234. if(owner->curInt->curAction->actionType == EActionType::SHOOT && currentActionTarget == stack->getPosition()) //hide if we are ranged attack target
  235. return false;
  236. }
  237. return true;
  238. }
  239. void CBattleStacksController::showStackAmountBox(SDL_Surface *to, const CStack * stack)
  240. {
  241. auto getEffectsPositivness = [&](const std::vector<si32> & activeSpells) -> int
  242. {
  243. int pos = 0;
  244. for (const auto & spellId : activeSpells)
  245. {
  246. pos += CGI->spellh->objects.at(spellId)->positiveness;
  247. }
  248. return pos;
  249. };
  250. auto getAmountBoxBackground = [&](int positivness) -> auto
  251. {
  252. if (positivness > 0)
  253. return amountPositive;
  254. if (positivness < 0)
  255. return amountNegative;
  256. return amountEffNeutral;
  257. };
  258. const int sideShift = stack->side == BattleSide::ATTACKER ? 1 : -1;
  259. const int reverseSideShift = stack->side == BattleSide::ATTACKER ? -1 : 1;
  260. const BattleHex nextPos = stack->getPosition() + sideShift;
  261. const bool edge = stack->getPosition() % GameConstants::BFIELD_WIDTH == (stack->side == BattleSide::ATTACKER ? GameConstants::BFIELD_WIDTH - 2 : 1);
  262. const bool moveInside = !edge && !owner->fieldController->stackCountOutsideHex(nextPos);
  263. int xAdd = (stack->side == BattleSide::ATTACKER ? 220 : 202) +
  264. (stack->doubleWide() ? 44 : 0) * sideShift +
  265. (moveInside ? amountNormal->width() + 10 : 0) * reverseSideShift;
  266. int yAdd = 260 + ((stack->side == BattleSide::ATTACKER || moveInside) ? 0 : -15);
  267. //blitting amount background box
  268. std::vector<si32> activeSpells = stack->activeSpells();
  269. auto amountBG = activeSpells.empty() ? amountNormal : getAmountBoxBackground(getEffectsPositivness(activeSpells));
  270. amountBG->draw(to, creAnims[stack->ID]->pos.x + xAdd, creAnims[stack->ID]->pos.y + yAdd);
  271. //blitting amount
  272. Point textPos(creAnims[stack->ID]->pos.x + xAdd + amountNormal->width()/2,
  273. creAnims[stack->ID]->pos.y + yAdd + amountNormal->height()/2);
  274. graphics->fonts[FONT_TINY]->renderTextCenter(to, makeNumberShort(stack->getCount()), Colors::WHITE, textPos);
  275. }
  276. void CBattleStacksController::showStack(SDL_Surface *to, const CStack * stack)
  277. {
  278. creAnims[stack->ID]->nextFrame(to, facingRight(stack)); // do actual blit
  279. creAnims[stack->ID]->incrementFrame(float(GH.mainFPSmng->getElapsedMilliseconds()) / 1000);
  280. if (stackNeedsAmountBox(stack))
  281. showStackAmountBox(to, stack);
  282. }
  283. void CBattleStacksController::updateBattleAnimations()
  284. {
  285. //handle animations
  286. for (auto & elem : pendingAnims)
  287. {
  288. if (!elem.first) //this animation should be deleted
  289. continue;
  290. if (!elem.second)
  291. {
  292. elem.second = elem.first->init();
  293. }
  294. if (elem.second && elem.first)
  295. elem.first->nextFrame();
  296. }
  297. //delete anims
  298. int preSize = static_cast<int>(pendingAnims.size());
  299. for (auto it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
  300. {
  301. if (it->first == nullptr)
  302. {
  303. pendingAnims.erase(it);
  304. it = pendingAnims.begin();
  305. break;
  306. }
  307. }
  308. if (preSize > 0 && pendingAnims.empty())
  309. {
  310. //anims ended
  311. owner->controlPanel->blockUI(activeStack == nullptr);
  312. owner->animsAreDisplayed.setn(false);
  313. }
  314. }
  315. void CBattleStacksController::addNewAnim(CBattleAnimation *anim)
  316. {
  317. pendingAnims.push_back( std::make_pair(anim, false) );
  318. owner->animsAreDisplayed.setn(true);
  319. }
  320. void CBattleStacksController::stackActivated(const CStack *stack) //TODO: check it all before game state is changed due to abilities
  321. {
  322. stackToActivate = stack;
  323. owner->waitForAnims();
  324. if (stackToActivate) //during waiting stack may have gotten activated through show
  325. activateStack();
  326. }
  327. void CBattleStacksController::stackRemoved(uint32_t stackID)
  328. {
  329. if (getActiveStack() != nullptr)
  330. {
  331. if (getActiveStack()->ID == stackID)
  332. {
  333. BattleAction *action = new BattleAction();
  334. action->side = owner->defendingHeroInstance ? (owner->curInt->playerID == owner->defendingHeroInstance->tempOwner) : false;
  335. action->actionType = EActionType::CANCEL;
  336. action->stackNumber = owner->stacksController->getActiveStack()->ID;
  337. owner->givenCommand.setn(action);
  338. setActiveStack(nullptr);
  339. }
  340. }
  341. //todo: ensure that ghost stack animation has fadeout effect
  342. }
  343. void CBattleStacksController::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  344. {
  345. for(auto & attackedInfo : attackedInfos)
  346. {
  347. //if (!attackedInfo.cloneKilled) //FIXME: play dead animation for cloned creature before it vanishes
  348. addNewAnim(new CDefenceAnimation(attackedInfo, owner));
  349. if(attackedInfo.rebirth)
  350. {
  351. owner->effectsController->displayEffect(EBattleEffect::RESURRECT, soundBase::RESURECT, attackedInfo.defender->getPosition()); //TODO: play reverse death animation
  352. }
  353. }
  354. owner->waitForAnims();
  355. for (auto & attackedInfo : attackedInfos)
  356. {
  357. if (attackedInfo.rebirth)
  358. creAnims[attackedInfo.defender->ID]->setType(CCreatureAnim::HOLDING);
  359. if (attackedInfo.cloneKilled)
  360. stackRemoved(attackedInfo.defender->ID);
  361. }
  362. }
  363. void CBattleStacksController::stackMoved(const CStack *stack, std::vector<BattleHex> destHex, int distance)
  364. {
  365. addNewAnim(new CMovementAnimation(owner, stack, destHex, distance));
  366. owner->waitForAnims();
  367. }
  368. void CBattleStacksController::stackAttacking( const CStack *attacker, BattleHex dest, const CStack *attacked, bool shooting )
  369. {
  370. if (shooting)
  371. {
  372. addNewAnim(new CShootingAnimation(owner, attacker, dest, attacked));
  373. }
  374. else
  375. {
  376. addNewAnim(new CMeleeAttackAnimation(owner, attacker, dest, attacked));
  377. }
  378. //waitForAnims();
  379. }
  380. bool CBattleStacksController::shouldRotate(const CStack * stack, const BattleHex & oldPos, const BattleHex & nextHex)
  381. {
  382. Point begPosition = CClickableHex::getXYUnitAnim(oldPos,stack, owner);
  383. Point endPosition = CClickableHex::getXYUnitAnim(nextHex, stack, owner);
  384. if((begPosition.x > endPosition.x) && facingRight(stack))
  385. return true;
  386. else if((begPosition.x < endPosition.x) && !facingRight(stack))
  387. return true;
  388. return false;
  389. }
  390. void CBattleStacksController::endAction(const BattleAction* action)
  391. {
  392. //check if we should reverse stacks
  393. //for some strange reason, it's not enough
  394. TStacks stacks = owner->curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  395. for (const CStack *s : stacks)
  396. {
  397. bool shouldFaceRight = s && s->side == BattleSide::ATTACKER;
  398. if (s && facingRight(s) != shouldFaceRight && s->alive() && creAnims[s->ID]->isIdle())
  399. {
  400. addNewAnim(new CReverseAnimation(owner, s, s->getPosition(), false));
  401. }
  402. }
  403. }
  404. void CBattleStacksController::startAction(const BattleAction* action)
  405. {
  406. const CStack *stack = owner->curInt->cb->battleGetStackByID(action->stackNumber);
  407. setHoveredStack(nullptr);
  408. auto actionTarget = action->getTarget(owner->curInt->cb.get());
  409. if(action->actionType == EActionType::WALK
  410. || (action->actionType == EActionType::WALK_AND_ATTACK && actionTarget.at(0).hexValue != stack->getPosition()))
  411. {
  412. assert(stack);
  413. owner->moveStarted = true;
  414. if (creAnims[action->stackNumber]->framesInGroup(CCreatureAnim::MOVE_START))
  415. {
  416. pendingAnims.push_back(std::make_pair(new CMovementStartAnimation(owner, stack), false));
  417. }
  418. if(shouldRotate(stack, stack->getPosition(), actionTarget.at(0).hexValue))
  419. pendingAnims.push_back(std::make_pair(new CReverseAnimation(owner, stack, stack->getPosition(), true), false));
  420. }
  421. }
  422. void CBattleStacksController::activateStack()
  423. {
  424. if ( !pendingAnims.empty())
  425. return;
  426. if ( !stackToActivate)
  427. return;
  428. owner->trySetActivePlayer(stackToActivate->owner);
  429. setActiveStack(stackToActivate);
  430. stackToActivate = nullptr;
  431. const CStack * s = owner->stacksController->getActiveStack();
  432. if(!s)
  433. return;
  434. //set casting flag to true if creature can use it to not check it every time
  435. const auto spellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::SPELLCASTER));
  436. const auto randomSpellcaster = s->getBonusLocalFirst(Selector::type()(Bonus::RANDOM_SPELLCASTER));
  437. if(s->canCast() && (spellcaster || randomSpellcaster))
  438. {
  439. stackCanCastSpell = true;
  440. if(randomSpellcaster)
  441. creatureSpellToCast = -1; //spell will be set later on cast
  442. else
  443. creatureSpellToCast = owner->curInt->cb->battleGetRandomStackSpell(CRandomGenerator::getDefault(), s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  444. //TODO: what if creature can cast BOTH random genie spell and aimed spell?
  445. //TODO: faerie dragon type spell should be selected by server
  446. }
  447. else
  448. {
  449. stackCanCastSpell = false;
  450. creatureSpellToCast = -1;
  451. }
  452. }
  453. void CBattleStacksController::setSelectedStack(const CStack *stack)
  454. {
  455. selectedStack = stack;
  456. }
  457. const CStack* CBattleStacksController::getSelectedStack()
  458. {
  459. return selectedStack;
  460. }
  461. const CStack* CBattleStacksController::getActiveStack()
  462. {
  463. return activeStack;
  464. }
  465. bool CBattleStacksController::facingRight(const CStack * stack)
  466. {
  467. return creDir[stack->ID];
  468. }
  469. bool CBattleStacksController::activeStackSpellcaster()
  470. {
  471. return stackCanCastSpell;
  472. }
  473. SpellID CBattleStacksController::activeStackSpellToCast()
  474. {
  475. if (!stackCanCastSpell)
  476. return SpellID::NONE;
  477. return SpellID(creatureSpellToCast);
  478. }