BattleActionsController.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. /*
  2. * BattleActionsController.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 "BattleActionsController.h"
  12. #include "BattleFieldController.h"
  13. #include "BattleHero.h"
  14. #include "BattleInterface.h"
  15. #include "BattleSiegeController.h"
  16. #include "BattleStacksController.h"
  17. #include "BattleWindow.h"
  18. #include "../CPlayerInterface.h"
  19. #include "../GameEngine.h"
  20. #include "../GameInstance.h"
  21. #include "../gui/CIntObject.h"
  22. #include "../gui/CursorHandler.h"
  23. #include "../gui/WindowHandler.h"
  24. #include "../windows/CCreatureWindow.h"
  25. #include "../windows/InfoWindows.h"
  26. #include "../../lib/CConfigHandler.h"
  27. #include "../../lib/CRandomGenerator.h"
  28. #include "../../lib/CStack.h"
  29. #include "../../lib/GameLibrary.h"
  30. #include "../../lib/battle/BattleAction.h"
  31. #include "../../lib/battle/CPlayerBattleCallback.h"
  32. #include "../../lib/callback/CCallback.h"
  33. #include "../../lib/spells/CSpellHandler.h"
  34. #include "../../lib/spells/ISpellMechanics.h"
  35. #include "../../lib/spells/Problem.h"
  36. #include "../../lib/texts/CGeneralTextHandler.h"
  37. struct TextReplacement
  38. {
  39. std::string placeholder;
  40. std::string replacement;
  41. };
  42. using TextReplacementList = std::vector<TextReplacement>;
  43. static std::string replacePlaceholders(std::string input, const TextReplacementList & format )
  44. {
  45. for(const auto & entry : format)
  46. boost::replace_all(input, entry.placeholder, entry.replacement);
  47. return input;
  48. }
  49. static std::string translatePlural(int amount, const std::string& baseTextID)
  50. {
  51. if(amount == 1)
  52. return LIBRARY->generaltexth->translate(baseTextID + ".1");
  53. return LIBRARY->generaltexth->translate(baseTextID);
  54. }
  55. static std::string formatPluralImpl(int amount, const std::string & amountString, const std::string & baseTextID)
  56. {
  57. std::string baseString = translatePlural(amount, baseTextID);
  58. TextReplacementList replacements {
  59. { "%d", amountString }
  60. };
  61. return replacePlaceholders(baseString, replacements);
  62. }
  63. static std::string formatPlural(int amount, const std::string & baseTextID)
  64. {
  65. return formatPluralImpl(amount, std::to_string(amount), baseTextID);
  66. }
  67. static std::string formatPlural(DamageRange range, const std::string & baseTextID)
  68. {
  69. if (range.min == range.max)
  70. return formatPlural(range.min, baseTextID);
  71. std::string rangeString = std::to_string(range.min) + " - " + std::to_string(range.max);
  72. return formatPluralImpl(range.max, rangeString, baseTextID);
  73. }
  74. static std::string formatAttack(const DamageEstimation & estimation, const std::string & creatureName, const std::string & baseTextID, int shotsLeft)
  75. {
  76. TextReplacementList replacements = {
  77. { "%CREATURE", creatureName },
  78. { "%DAMAGE", formatPlural(estimation.damage, "vcmi.battleWindow.damageEstimation.damage") },
  79. { "%SHOTS", formatPlural(shotsLeft, "vcmi.battleWindow.damageEstimation.shots") },
  80. { "%KILLS", formatPlural(estimation.kills, "vcmi.battleWindow.damageEstimation.kills") },
  81. };
  82. return replacePlaceholders(LIBRARY->generaltexth->translate(baseTextID), replacements);
  83. }
  84. static std::string formatMeleeAttack(const DamageEstimation & estimation, const std::string & creatureName)
  85. {
  86. std::string baseTextID = estimation.kills.max == 0 ?
  87. "vcmi.battleWindow.damageEstimation.melee" :
  88. "vcmi.battleWindow.damageEstimation.meleeKills";
  89. return formatAttack(estimation, creatureName, baseTextID, 0);
  90. }
  91. static std::string formatRangedAttack(const DamageEstimation & estimation, const std::string & creatureName, int shotsLeft)
  92. {
  93. std::string baseTextID = estimation.kills.max == 0 ?
  94. "vcmi.battleWindow.damageEstimation.ranged" :
  95. "vcmi.battleWindow.damageEstimation.rangedKills";
  96. return formatAttack(estimation, creatureName, baseTextID, shotsLeft);
  97. }
  98. static std::string formatRetaliation(const DamageEstimation & estimation, bool mayBeKilled)
  99. {
  100. if (estimation.damage.max == 0)
  101. return LIBRARY->generaltexth->translate("vcmi.battleWindow.damageRetaliation.never");
  102. std::string baseTextID = estimation.kills.max == 0 ?
  103. "vcmi.battleWindow.damageRetaliation.damage" :
  104. "vcmi.battleWindow.damageRetaliation.damageKills";
  105. std::string prefixTextID = mayBeKilled ?
  106. "vcmi.battleWindow.damageRetaliation.may" :
  107. "vcmi.battleWindow.damageRetaliation.will";
  108. return LIBRARY->generaltexth->translate(prefixTextID) + formatAttack(estimation, "", baseTextID, 0);
  109. }
  110. BattleActionsController::BattleActionsController(BattleInterface & owner):
  111. owner(owner),
  112. selectedStack(nullptr),
  113. heroSpellToCast(nullptr)
  114. {
  115. }
  116. void BattleActionsController::endCastingSpell()
  117. {
  118. if(heroSpellToCast)
  119. {
  120. heroSpellToCast.reset();
  121. owner.windowObject->blockUI(false);
  122. }
  123. if(owner.stacksController->getActiveStack())
  124. {
  125. possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack()); //restore actions after they were cleared
  126. owner.windowObject->setPossibleActions(possibleActions);
  127. }
  128. selectedStack = nullptr;
  129. ENGINE->fakeMouseMove();
  130. }
  131. bool BattleActionsController::isActiveStackSpellcaster() const
  132. {
  133. const CStack * casterStack = owner.stacksController->getActiveStack();
  134. if (!casterStack)
  135. return false;
  136. bool spellcaster = casterStack->hasBonusOfType(BonusType::SPELLCASTER);
  137. return (spellcaster && casterStack->canCast());
  138. }
  139. void BattleActionsController::enterCreatureCastingMode()
  140. {
  141. //silently check for possible errors
  142. if (owner.tacticsMode)
  143. return;
  144. //hero is casting a spell
  145. if (heroSpellToCast)
  146. return;
  147. if (!owner.stacksController->getActiveStack())
  148. return;
  149. if(owner.getBattle()->battleCanTargetEmptyHex(owner.stacksController->getActiveStack()))
  150. {
  151. auto actionFilterPredicate = [](const PossiblePlayerBattleAction x)
  152. {
  153. return x.get() != PossiblePlayerBattleAction::SHOOT;
  154. };
  155. vstd::erase_if(possibleActions, actionFilterPredicate);
  156. ENGINE->fakeMouseMove();
  157. return;
  158. }
  159. if (!isActiveStackSpellcaster())
  160. return;
  161. for(const auto & action : possibleActions)
  162. {
  163. if (action.get() != PossiblePlayerBattleAction::NO_LOCATION)
  164. continue;
  165. const spells::Caster * caster = owner.stacksController->getActiveStack();
  166. const CSpell * spell = action.spell().toSpell();
  167. spells::Target target;
  168. target.emplace_back();
  169. spells::BattleCast cast(owner.getBattle().get(), caster, spells::Mode::CREATURE_ACTIVE, spell);
  170. auto m = spell->battleMechanics(&cast);
  171. spells::detail::ProblemImpl ignored;
  172. const bool isCastingPossible = m->canBeCastAt(target, ignored);
  173. if (isCastingPossible)
  174. {
  175. owner.giveCommand(EActionType::MONSTER_SPELL, BattleHex::INVALID, spell->getId());
  176. selectedStack = nullptr;
  177. ENGINE->cursor().set(Cursor::Combat::POINTER);
  178. }
  179. return;
  180. }
  181. possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack());
  182. auto actionFilterPredicate = [](const PossiblePlayerBattleAction x)
  183. {
  184. return !x.spellcast();
  185. };
  186. vstd::erase_if(possibleActions, actionFilterPredicate);
  187. ENGINE->fakeMouseMove();
  188. }
  189. std::vector<PossiblePlayerBattleAction> BattleActionsController::getPossibleActionsForStack(const CStack *stack) const
  190. {
  191. BattleClientInterfaceData data; //hard to get rid of these things so for now they're required data to pass
  192. for(const auto & spell : creatureSpells)
  193. data.creatureSpellsToCast.push_back(spell->id);
  194. data.tacticsMode = owner.tacticsMode;
  195. auto allActions = owner.getBattle()->getClientActionsForStack(stack, data);
  196. allActions.push_back(PossiblePlayerBattleAction::HERO_INFO);
  197. allActions.push_back(PossiblePlayerBattleAction::CREATURE_INFO);
  198. return std::vector<PossiblePlayerBattleAction>(allActions);
  199. }
  200. void BattleActionsController::reorderPossibleActionsPriority(const CStack * stack, const CStack * targetStack)
  201. {
  202. if(owner.tacticsMode || possibleActions.empty()) return; //this function is not supposed to be called in tactics mode or before getPossibleActionsForStack
  203. auto assignPriority = [&](const PossiblePlayerBattleAction & item
  204. ) -> uint8_t //large lambda assigning priority which would have to be part of possibleActions without it
  205. {
  206. switch(item.get())
  207. {
  208. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  209. case PossiblePlayerBattleAction::ANY_LOCATION:
  210. case PossiblePlayerBattleAction::NO_LOCATION:
  211. case PossiblePlayerBattleAction::FREE_LOCATION:
  212. case PossiblePlayerBattleAction::OBSTACLE:
  213. case PossiblePlayerBattleAction::SACRIFICE:
  214. if(!stack->hasBonusOfType(BonusType::NO_SPELLCAST_BY_DEFAULT) && targetStack != nullptr)
  215. {
  216. PlayerColor stackOwner = owner.getBattle()->battleGetOwner(targetStack);
  217. bool enemyTargetingPositiveSpellcast = item.spell().toSpell()->isPositive() && stackOwner != owner.curInt->playerID;
  218. bool friendTargetingNegativeSpellcast = item.spell().toSpell()->isNegative() && stackOwner == owner.curInt->playerID;
  219. if(!enemyTargetingPositiveSpellcast && !friendTargetingNegativeSpellcast)
  220. return 1;
  221. }
  222. return 100; //bottom priority
  223. break;
  224. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  225. return 2;
  226. break;
  227. case PossiblePlayerBattleAction::SHOOT:
  228. if(targetStack == nullptr || targetStack->unitSide() == stack->unitSide() || !targetStack->alive())
  229. return 100; //bottom priority
  230. return 4;
  231. break;
  232. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  233. return 5;
  234. break;
  235. case PossiblePlayerBattleAction::ATTACK:
  236. return 6;
  237. break;
  238. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  239. return 7;
  240. break;
  241. case PossiblePlayerBattleAction::MOVE_STACK:
  242. return 8;
  243. break;
  244. case PossiblePlayerBattleAction::CATAPULT:
  245. return 9;
  246. break;
  247. case PossiblePlayerBattleAction::HEAL:
  248. return 10;
  249. break;
  250. case PossiblePlayerBattleAction::CREATURE_INFO:
  251. return 11;
  252. break;
  253. case PossiblePlayerBattleAction::HERO_INFO:
  254. return 12;
  255. break;
  256. case PossiblePlayerBattleAction::TELEPORT:
  257. return 13;
  258. break;
  259. default:
  260. assert(0);
  261. return 200;
  262. break;
  263. }
  264. };
  265. auto comparer = [&](const PossiblePlayerBattleAction & lhs, const PossiblePlayerBattleAction & rhs)
  266. {
  267. return assignPriority(lhs) < assignPriority(rhs);
  268. };
  269. std::sort(possibleActions.begin(), possibleActions.end(), comparer);
  270. }
  271. void BattleActionsController::castThisSpell(SpellID spellID)
  272. {
  273. heroSpellToCast = std::make_shared<BattleAction>();
  274. heroSpellToCast->actionType = EActionType::HERO_SPELL;
  275. heroSpellToCast->spell = spellID;
  276. heroSpellToCast->stackNumber = -1;
  277. heroSpellToCast->side = owner.curInt->cb->getBattle(owner.getBattleID())->battleGetMySide();
  278. //choosing possible targets
  279. const CGHeroInstance *castingHero = (owner.attackingHeroInstance->tempOwner == owner.curInt->playerID) ? owner.attackingHeroInstance : owner.defendingHeroInstance;
  280. assert(castingHero); // code below assumes non-null hero
  281. PossiblePlayerBattleAction spellSelMode = owner.getBattle()->getCasterAction(spellID.toSpell(), castingHero, spells::Mode::HERO);
  282. if (spellSelMode.get() == PossiblePlayerBattleAction::NO_LOCATION) //user does not have to select location
  283. {
  284. heroSpellToCast->aimToHex(BattleHex::INVALID);
  285. owner.curInt->cb->battleMakeSpellAction(owner.getBattleID(), *heroSpellToCast);
  286. endCastingSpell();
  287. }
  288. else
  289. {
  290. possibleActions.clear();
  291. possibleActions.push_back (spellSelMode); //only this one action can be performed at the moment
  292. ENGINE->fakeMouseMove();//update cursor
  293. }
  294. owner.windowObject->blockUI(true);
  295. }
  296. const CSpell * BattleActionsController::getHeroSpellToCast( ) const
  297. {
  298. if (heroSpellToCast)
  299. return heroSpellToCast->spell.toSpell();
  300. return nullptr;
  301. }
  302. const CSpell * BattleActionsController::getStackSpellToCast(const BattleHex & hoveredHex)
  303. {
  304. if (heroSpellToCast)
  305. return nullptr;
  306. if (!owner.stacksController->getActiveStack())
  307. return nullptr;
  308. if (!hoveredHex.isValid())
  309. return nullptr;
  310. auto action = selectAction(hoveredHex);
  311. if(owner.stacksController->getActiveStack()->hasBonusOfType(BonusType::SPELL_LIKE_ATTACK))
  312. {
  313. auto bonus = owner.stacksController->getActiveStack()->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  314. return bonus->subtype.as<SpellID>().toSpell();
  315. }
  316. if (action.spell() == SpellID::NONE)
  317. return nullptr;
  318. return action.spell().toSpell();
  319. }
  320. const CSpell * BattleActionsController::getCurrentSpell(const BattleHex & hoveredHex)
  321. {
  322. if (getHeroSpellToCast())
  323. return getHeroSpellToCast();
  324. return getStackSpellToCast(hoveredHex);
  325. }
  326. const CStack * BattleActionsController::getStackForHex(const BattleHex & hoveredHex)
  327. {
  328. const CStack * shere = owner.getBattle()->battleGetStackByPos(hoveredHex, true);
  329. if(shere)
  330. return shere;
  331. return owner.getBattle()->battleGetStackByPos(hoveredHex, false);
  332. }
  333. void BattleActionsController::actionSetCursor(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  334. {
  335. switch (action.get())
  336. {
  337. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  338. ENGINE->cursor().set(Cursor::Combat::POINTER);
  339. return;
  340. case PossiblePlayerBattleAction::MOVE_TACTICS:
  341. case PossiblePlayerBattleAction::MOVE_STACK:
  342. if (owner.stacksController->getActiveStack()->hasBonusOfType(BonusType::FLYING))
  343. ENGINE->cursor().set(Cursor::Combat::FLY);
  344. else
  345. ENGINE->cursor().set(Cursor::Combat::MOVE);
  346. return;
  347. case PossiblePlayerBattleAction::ATTACK:
  348. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  349. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  350. {
  351. static const std::map<BattleHex::EDir, Cursor::Combat> sectorCursor = {
  352. {BattleHex::TOP_LEFT, Cursor::Combat::HIT_SOUTHEAST},
  353. {BattleHex::TOP_RIGHT, Cursor::Combat::HIT_SOUTHWEST},
  354. {BattleHex::RIGHT, Cursor::Combat::HIT_WEST },
  355. {BattleHex::BOTTOM_RIGHT, Cursor::Combat::HIT_NORTHWEST},
  356. {BattleHex::BOTTOM_LEFT, Cursor::Combat::HIT_NORTHEAST},
  357. {BattleHex::LEFT, Cursor::Combat::HIT_EAST },
  358. {BattleHex::TOP, Cursor::Combat::HIT_SOUTH },
  359. {BattleHex::BOTTOM, Cursor::Combat::HIT_NORTH }
  360. };
  361. auto direction = owner.fieldController->selectAttackDirection(targetHex);
  362. assert(sectorCursor.count(direction) > 0);
  363. if (sectorCursor.count(direction))
  364. ENGINE->cursor().set(sectorCursor.at(direction));
  365. return;
  366. }
  367. case PossiblePlayerBattleAction::SHOOT:
  368. if (owner.getBattle()->battleHasShootingPenalty(owner.stacksController->getActiveStack(), targetHex))
  369. ENGINE->cursor().set(Cursor::Combat::SHOOT_PENALTY);
  370. else
  371. ENGINE->cursor().set(Cursor::Combat::SHOOT);
  372. return;
  373. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  374. case PossiblePlayerBattleAction::ANY_LOCATION:
  375. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  376. case PossiblePlayerBattleAction::FREE_LOCATION:
  377. case PossiblePlayerBattleAction::OBSTACLE:
  378. ENGINE->cursor().set(Cursor::Spellcast::SPELL);
  379. return;
  380. case PossiblePlayerBattleAction::TELEPORT:
  381. ENGINE->cursor().set(Cursor::Combat::TELEPORT);
  382. return;
  383. case PossiblePlayerBattleAction::SACRIFICE:
  384. ENGINE->cursor().set(Cursor::Combat::SACRIFICE);
  385. return;
  386. case PossiblePlayerBattleAction::HEAL:
  387. ENGINE->cursor().set(Cursor::Combat::HEAL);
  388. return;
  389. case PossiblePlayerBattleAction::CATAPULT:
  390. ENGINE->cursor().set(Cursor::Combat::SHOOT_CATAPULT);
  391. return;
  392. case PossiblePlayerBattleAction::CREATURE_INFO:
  393. ENGINE->cursor().set(Cursor::Combat::QUERY);
  394. return;
  395. case PossiblePlayerBattleAction::HERO_INFO:
  396. ENGINE->cursor().set(Cursor::Combat::HERO);
  397. return;
  398. }
  399. assert(0);
  400. }
  401. void BattleActionsController::actionSetCursorBlocked(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  402. {
  403. switch (action.get())
  404. {
  405. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  406. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  407. case PossiblePlayerBattleAction::TELEPORT:
  408. case PossiblePlayerBattleAction::SACRIFICE:
  409. case PossiblePlayerBattleAction::FREE_LOCATION:
  410. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  411. return;
  412. default:
  413. if (targetHex == -1)
  414. ENGINE->cursor().set(Cursor::Combat::POINTER);
  415. else
  416. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  417. return;
  418. }
  419. assert(0);
  420. }
  421. std::string BattleActionsController::actionGetStatusMessage(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  422. {
  423. const CStack * targetStack = getStackForHex(targetHex);
  424. switch (action.get()) //display console message, realize selected action
  425. {
  426. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  427. return (boost::format(LIBRARY->generaltexth->allTexts[481]) % targetStack->getName()).str(); //Select %s
  428. case PossiblePlayerBattleAction::MOVE_TACTICS:
  429. case PossiblePlayerBattleAction::MOVE_STACK:
  430. if (owner.stacksController->getActiveStack()->hasBonusOfType(BonusType::FLYING))
  431. return (boost::format(LIBRARY->generaltexth->allTexts[295]) % owner.stacksController->getActiveStack()->getName()).str(); //Fly %s here
  432. else
  433. return (boost::format(LIBRARY->generaltexth->allTexts[294]) % owner.stacksController->getActiveStack()->getName()).str(); //Move %s here
  434. case PossiblePlayerBattleAction::ATTACK:
  435. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  436. case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
  437. {
  438. const auto * attacker = owner.stacksController->getActiveStack();
  439. BattleHex attackFromHex = owner.getBattle()->fromWhichHexAttack(attacker, targetHex, owner.fieldController->selectAttackDirection(targetHex));
  440. assert(attackFromHex.isValid());
  441. int distance = attacker->position.isValid() ? owner.getBattle()->battleGetDistances(attacker, attacker->getPosition())[attackFromHex.toInt()] : 0;
  442. DamageEstimation retaliation;
  443. BattleAttackInfo attackInfo(attacker, targetStack, distance, false );
  444. attackInfo.attackerPos = attackFromHex;
  445. DamageEstimation estimation = owner.getBattle()->battleEstimateDamage(attackInfo, &retaliation);
  446. estimation.kills.max = std::min<int64_t>(estimation.kills.max, targetStack->getCount());
  447. estimation.kills.min = std::min<int64_t>(estimation.kills.min, targetStack->getCount());
  448. bool enemyMayBeKilled = estimation.kills.max == targetStack->getCount();
  449. return formatMeleeAttack(estimation, targetStack->getName()) + "\n" + formatRetaliation(retaliation, enemyMayBeKilled);
  450. }
  451. case PossiblePlayerBattleAction::SHOOT:
  452. {
  453. if(targetStack == nullptr) //should be true only for spell-like attack
  454. {
  455. auto spellLikeAttackBonus = owner.stacksController->getActiveStack()->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  456. assert(spellLikeAttackBonus != nullptr);
  457. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % spellLikeAttackBonus->subtype.as<SpellID>().toSpell()->getNameTranslated());
  458. }
  459. const auto * shooter = owner.stacksController->getActiveStack();
  460. DamageEstimation retaliation;
  461. BattleAttackInfo attackInfo(shooter, targetStack, 0, true );
  462. DamageEstimation estimation = owner.getBattle()->battleEstimateDamage(attackInfo, &retaliation);
  463. estimation.kills.max = std::min<int64_t>(estimation.kills.max, targetStack->getCount());
  464. estimation.kills.min = std::min<int64_t>(estimation.kills.min, targetStack->getCount());
  465. return formatRangedAttack(estimation, targetStack->getName(), shooter->shots.available());
  466. }
  467. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  468. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[27]) % action.spell().toSpell()->getNameTranslated() % targetStack->getName()); //Cast %s on %s
  469. case PossiblePlayerBattleAction::ANY_LOCATION:
  470. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % action.spell().toSpell()->getNameTranslated()); //Cast %s
  471. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
  472. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[301]) % targetStack->getName()); //Cast a spell on %
  473. case PossiblePlayerBattleAction::TELEPORT:
  474. return LIBRARY->generaltexth->allTexts[25]; //Teleport Here
  475. case PossiblePlayerBattleAction::OBSTACLE:
  476. return LIBRARY->generaltexth->allTexts[550];
  477. case PossiblePlayerBattleAction::SACRIFICE:
  478. return (boost::format(LIBRARY->generaltexth->allTexts[549]) % targetStack->getName()).str(); //sacrifice the %s
  479. case PossiblePlayerBattleAction::FREE_LOCATION:
  480. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[26]) % action.spell().toSpell()->getNameTranslated()); //Cast %s
  481. case PossiblePlayerBattleAction::HEAL:
  482. return (boost::format(LIBRARY->generaltexth->allTexts[419]) % targetStack->getName()).str(); //Apply first aid to the %s
  483. case PossiblePlayerBattleAction::CATAPULT:
  484. return ""; // TODO
  485. case PossiblePlayerBattleAction::CREATURE_INFO:
  486. return (boost::format(LIBRARY->generaltexth->allTexts[297]) % targetStack->getName()).str();
  487. case PossiblePlayerBattleAction::HERO_INFO:
  488. return LIBRARY->generaltexth->translate("core.genrltxt.417"); // "View Hero Stats"
  489. }
  490. assert(0);
  491. return "";
  492. }
  493. std::string BattleActionsController::actionGetStatusMessageBlocked(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  494. {
  495. switch (action.get())
  496. {
  497. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  498. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  499. return LIBRARY->generaltexth->allTexts[23];
  500. break;
  501. case PossiblePlayerBattleAction::TELEPORT:
  502. return LIBRARY->generaltexth->allTexts[24]; //Invalid Teleport Destination
  503. break;
  504. case PossiblePlayerBattleAction::SACRIFICE:
  505. return LIBRARY->generaltexth->allTexts[543]; //choose army to sacrifice
  506. break;
  507. case PossiblePlayerBattleAction::FREE_LOCATION:
  508. return boost::str(boost::format(LIBRARY->generaltexth->allTexts[181]) % action.spell().toSpell()->getNameTranslated()); //No room to place %s here
  509. break;
  510. default:
  511. return "";
  512. }
  513. }
  514. bool BattleActionsController::actionIsLegal(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  515. {
  516. const CStack * targetStack = getStackForHex(targetHex);
  517. bool targetStackOwned = targetStack && targetStack->unitOwner() == owner.curInt->playerID;
  518. switch (action.get())
  519. {
  520. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  521. return (targetStack && targetStackOwned && targetStack->getMovementRange() > 0);
  522. case PossiblePlayerBattleAction::CREATURE_INFO:
  523. return (targetStack && targetStack->alive());
  524. case PossiblePlayerBattleAction::HERO_INFO:
  525. if (targetHex == BattleHex::HERO_ATTACKER)
  526. return owner.attackingHero != nullptr;
  527. if (targetHex == BattleHex::HERO_DEFENDER)
  528. return owner.defendingHero != nullptr;
  529. return false;
  530. case PossiblePlayerBattleAction::MOVE_TACTICS:
  531. case PossiblePlayerBattleAction::MOVE_STACK:
  532. if (!(targetStack && targetStack->alive())) //we can walk on dead stacks
  533. {
  534. const CStack * currentStack = owner.stacksController->getActiveStack();
  535. return currentStack && owner.getBattle()->toWhichHexMove(currentStack, targetHex).isValid();
  536. }
  537. return false;
  538. case PossiblePlayerBattleAction::ATTACK:
  539. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  540. case PossiblePlayerBattleAction::ATTACK_AND_RETURN:
  541. {
  542. const CStack * currentStack = owner.stacksController->getActiveStack();
  543. return currentStack &&
  544. owner.getBattle()->battleCanAttackUnit(currentStack, targetStack) &&
  545. owner.getBattle()->battleCanAttackHex(currentStack, targetHex);
  546. }
  547. case PossiblePlayerBattleAction::SHOOT:
  548. {
  549. auto currentStack = owner.stacksController->getActiveStack();
  550. if(!owner.getBattle()->battleCanShoot(currentStack, targetHex))
  551. return false;
  552. if(targetStack == nullptr && owner.getBattle()->battleCanTargetEmptyHex(currentStack))
  553. {
  554. auto spellLikeAttackBonus = currentStack->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  555. const CSpell * spellDataToCheck = spellLikeAttackBonus->subtype.as<SpellID>().toSpell();
  556. return isCastingPossibleHere(spellDataToCheck, nullptr, targetHex);
  557. }
  558. return true;
  559. }
  560. case PossiblePlayerBattleAction::NO_LOCATION:
  561. return false;
  562. case PossiblePlayerBattleAction::ANY_LOCATION:
  563. return isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  564. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  565. return !selectedStack && targetStack && isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  566. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL:
  567. if(targetStack && targetStackOwned && targetStack != owner.stacksController->getActiveStack() && targetStack->alive()) //only positive spells for other allied creatures
  568. {
  569. SpellID spellID = owner.getBattle()->getRandomBeneficialSpell(CRandomGenerator::getDefault(), owner.stacksController->getActiveStack(), targetStack);
  570. return spellID != SpellID::NONE;
  571. }
  572. return false;
  573. case PossiblePlayerBattleAction::TELEPORT:
  574. return selectedStack && isCastingPossibleHere(action.spell().toSpell(), selectedStack, targetHex);
  575. case PossiblePlayerBattleAction::SACRIFICE: //choose our living stack to sacrifice
  576. {
  577. if(!targetStack)
  578. return false;
  579. auto unit = targetStack->acquire();
  580. return targetStack != selectedStack && targetStackOwned && targetStack->alive()
  581. && unit->isLiving() && !unit->hasBonusOfType(BonusType::MECHANICAL);
  582. }
  583. case PossiblePlayerBattleAction::OBSTACLE:
  584. case PossiblePlayerBattleAction::FREE_LOCATION:
  585. return isCastingPossibleHere(action.spell().toSpell(), nullptr, targetHex);
  586. case PossiblePlayerBattleAction::CATAPULT:
  587. return owner.siegeController && owner.siegeController->isAttackableByCatapult(targetHex);
  588. case PossiblePlayerBattleAction::HEAL:
  589. return targetStack && targetStackOwned && targetStack->canBeHealed();
  590. }
  591. assert(0);
  592. return false;
  593. }
  594. void BattleActionsController::actionRealize(PossiblePlayerBattleAction action, const BattleHex & targetHex)
  595. {
  596. const CStack * targetStack = getStackForHex(targetHex);
  597. switch (action.get()) //display console message, realize selected action
  598. {
  599. case PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK:
  600. {
  601. owner.stackActivated(targetStack);
  602. return;
  603. }
  604. case PossiblePlayerBattleAction::MOVE_TACTICS:
  605. case PossiblePlayerBattleAction::MOVE_STACK:
  606. {
  607. const auto * activeStack = owner.stacksController->getActiveStack();
  608. auto toHex = owner.getBattle()->toWhichHexMove(activeStack, targetHex);
  609. assert(toHex.isValid());
  610. owner.giveCommand(EActionType::WALK, toHex);
  611. return;
  612. }
  613. case PossiblePlayerBattleAction::ATTACK:
  614. case PossiblePlayerBattleAction::WALK_AND_ATTACK:
  615. case PossiblePlayerBattleAction::ATTACK_AND_RETURN: //TODO: allow to disable return
  616. {
  617. bool returnAfterAttack = action.get() == PossiblePlayerBattleAction::ATTACK_AND_RETURN;
  618. auto attacker = owner.stacksController->getActiveStack();
  619. BattleHex attackFromHex = owner.getBattle()->fromWhichHexAttack(attacker, targetHex, owner.fieldController->selectAttackDirection(targetHex));
  620. assert(attackFromHex.isValid());
  621. BattleAction command = BattleAction::makeMeleeAttack(attacker, targetHex, attackFromHex, returnAfterAttack);
  622. owner.sendCommand(command, attacker);
  623. return;
  624. }
  625. case PossiblePlayerBattleAction::SHOOT:
  626. {
  627. owner.giveCommand(EActionType::SHOOT, targetHex);
  628. return;
  629. }
  630. case PossiblePlayerBattleAction::HEAL:
  631. {
  632. owner.giveCommand(EActionType::STACK_HEAL, targetHex);
  633. return;
  634. };
  635. case PossiblePlayerBattleAction::CATAPULT:
  636. {
  637. owner.giveCommand(EActionType::CATAPULT, targetHex);
  638. return;
  639. }
  640. case PossiblePlayerBattleAction::CREATURE_INFO:
  641. {
  642. ENGINE->windows().createAndPushWindow<CStackWindow>(targetStack, false);
  643. return;
  644. }
  645. case PossiblePlayerBattleAction::HERO_INFO:
  646. {
  647. if (targetHex == BattleHex::HERO_ATTACKER)
  648. owner.attackingHero->heroLeftClicked();
  649. if (targetHex == BattleHex::HERO_DEFENDER)
  650. owner.defendingHero->heroLeftClicked();
  651. return;
  652. }
  653. case PossiblePlayerBattleAction::AIMED_SPELL_CREATURE:
  654. case PossiblePlayerBattleAction::ANY_LOCATION:
  655. case PossiblePlayerBattleAction::RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be available as random spell
  656. case PossiblePlayerBattleAction::TELEPORT:
  657. case PossiblePlayerBattleAction::OBSTACLE:
  658. case PossiblePlayerBattleAction::SACRIFICE:
  659. case PossiblePlayerBattleAction::FREE_LOCATION:
  660. {
  661. if (action.get() == PossiblePlayerBattleAction::AIMED_SPELL_CREATURE )
  662. {
  663. if (action.spell() == SpellID::SACRIFICE)
  664. {
  665. heroSpellToCast->aimToHex(targetHex);
  666. possibleActions.push_back({PossiblePlayerBattleAction::SACRIFICE, action.spell()});
  667. selectedStack = targetStack;
  668. return;
  669. }
  670. if (action.spell() == SpellID::TELEPORT)
  671. {
  672. heroSpellToCast->aimToUnit(targetStack);
  673. possibleActions.push_back({PossiblePlayerBattleAction::TELEPORT, action.spell()});
  674. selectedStack = targetStack;
  675. return;
  676. }
  677. }
  678. if (!heroSpellcastingModeActive())
  679. {
  680. if (action.spell().hasValue())
  681. {
  682. owner.giveCommand(EActionType::MONSTER_SPELL, targetHex, action.spell());
  683. }
  684. else //unknown random spell
  685. {
  686. owner.giveCommand(EActionType::MONSTER_SPELL, targetHex);
  687. }
  688. }
  689. else
  690. {
  691. assert(getHeroSpellToCast());
  692. switch (getHeroSpellToCast()->id.toEnum())
  693. {
  694. case SpellID::SACRIFICE:
  695. heroSpellToCast->aimToUnit(targetStack);//victim
  696. break;
  697. default:
  698. heroSpellToCast->aimToHex(targetHex);
  699. break;
  700. }
  701. owner.curInt->cb->battleMakeSpellAction(owner.getBattleID(), *heroSpellToCast);
  702. endCastingSpell();
  703. }
  704. selectedStack = nullptr;
  705. return;
  706. }
  707. }
  708. assert(0);
  709. return;
  710. }
  711. PossiblePlayerBattleAction BattleActionsController::selectAction(const BattleHex & targetHex)
  712. {
  713. assert(owner.stacksController->getActiveStack() != nullptr);
  714. assert(!possibleActions.empty());
  715. assert(targetHex.isValid());
  716. if (owner.stacksController->getActiveStack() == nullptr)
  717. return PossiblePlayerBattleAction::INVALID;
  718. if (possibleActions.empty())
  719. return PossiblePlayerBattleAction::INVALID;
  720. const CStack * targetStack = getStackForHex(targetHex);
  721. reorderPossibleActionsPriority(owner.stacksController->getActiveStack(), targetStack);
  722. for (PossiblePlayerBattleAction action : possibleActions)
  723. {
  724. if (actionIsLegal(action, targetHex))
  725. return action;
  726. }
  727. return possibleActions.front();
  728. }
  729. void BattleActionsController::onHexHovered(const BattleHex & hoveredHex)
  730. {
  731. if (owner.openingPlaying())
  732. {
  733. currentConsoleMsg = LIBRARY->generaltexth->translate("vcmi.battleWindow.pressKeyToSkipIntro");
  734. ENGINE->statusbar()->write(currentConsoleMsg);
  735. return;
  736. }
  737. if (owner.stacksController->getActiveStack() == nullptr)
  738. return;
  739. if (hoveredHex == BattleHex::INVALID)
  740. {
  741. if (!currentConsoleMsg.empty())
  742. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  743. currentConsoleMsg.clear();
  744. ENGINE->cursor().set(Cursor::Combat::BLOCKED);
  745. return;
  746. }
  747. auto action = selectAction(hoveredHex);
  748. std::string newConsoleMsg;
  749. if (actionIsLegal(action, hoveredHex))
  750. {
  751. actionSetCursor(action, hoveredHex);
  752. newConsoleMsg = actionGetStatusMessage(action, hoveredHex);
  753. }
  754. else
  755. {
  756. actionSetCursorBlocked(action, hoveredHex);
  757. newConsoleMsg = actionGetStatusMessageBlocked(action, hoveredHex);
  758. }
  759. if (!currentConsoleMsg.empty())
  760. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  761. if (!newConsoleMsg.empty())
  762. ENGINE->statusbar()->write(newConsoleMsg);
  763. currentConsoleMsg = newConsoleMsg;
  764. }
  765. void BattleActionsController::onHoverEnded()
  766. {
  767. ENGINE->cursor().set(Cursor::Combat::POINTER);
  768. if (!currentConsoleMsg.empty())
  769. ENGINE->statusbar()->clearIfMatching(currentConsoleMsg);
  770. currentConsoleMsg.clear();
  771. }
  772. void BattleActionsController::onHexLeftClicked(const BattleHex & clickedHex)
  773. {
  774. if (owner.stacksController->getActiveStack() == nullptr)
  775. return;
  776. auto action = selectAction(clickedHex);
  777. std::string newConsoleMsg;
  778. if (!actionIsLegal(action, clickedHex))
  779. return;
  780. actionRealize(action, clickedHex);
  781. ENGINE->statusbar()->clear();
  782. }
  783. void BattleActionsController::tryActivateStackSpellcasting(const CStack *casterStack)
  784. {
  785. creatureSpells.clear();
  786. bool spellcaster = casterStack->hasBonusOfType(BonusType::SPELLCASTER);
  787. if(casterStack->canCast() && spellcaster)
  788. {
  789. // faerie dragon can cast only one, randomly selected spell until their next move
  790. //TODO: faerie dragon type spell should be selected by server
  791. const auto spellToCast = owner.getBattle()->getRandomCastedSpell(CRandomGenerator::getDefault(), casterStack);
  792. if (spellToCast.hasValue())
  793. creatureSpells.push_back(spellToCast.toSpell());
  794. }
  795. TConstBonusListPtr bl = casterStack->getBonusesOfType(BonusType::SPELLCASTER);
  796. for(const auto & bonus : *bl)
  797. {
  798. if (bonus->additionalInfo[0] <= 0 && bonus->subtype.as<SpellID>().hasValue())
  799. creatureSpells.push_back(bonus->subtype.as<SpellID>().toSpell());
  800. }
  801. }
  802. const spells::Caster * BattleActionsController::getCurrentSpellcaster() const
  803. {
  804. if (heroSpellToCast)
  805. return owner.currentHero();
  806. else
  807. return owner.stacksController->getActiveStack();
  808. }
  809. spells::Mode BattleActionsController::getCurrentCastMode() const
  810. {
  811. if (heroSpellToCast)
  812. return spells::Mode::HERO;
  813. else
  814. return spells::Mode::CREATURE_ACTIVE;
  815. }
  816. bool BattleActionsController::isCastingPossibleHere(const CSpell * currentSpell, const CStack *targetStack, const BattleHex & targetHex)
  817. {
  818. assert(currentSpell);
  819. if (!currentSpell)
  820. return false;
  821. auto caster = getCurrentSpellcaster();
  822. const spells::Mode mode = heroSpellToCast ? spells::Mode::HERO : spells::Mode::CREATURE_ACTIVE;
  823. spells::Target target;
  824. if(targetStack)
  825. target.emplace_back(targetStack);
  826. target.emplace_back(targetHex);
  827. spells::BattleCast cast(owner.getBattle().get(), caster, mode, currentSpell);
  828. auto m = currentSpell->battleMechanics(&cast);
  829. spells::detail::ProblemImpl problem; //todo: display problem in status bar
  830. return m->canBeCastAt(target, problem);
  831. }
  832. void BattleActionsController::activateStack()
  833. {
  834. const CStack * s = owner.stacksController->getActiveStack();
  835. if(s)
  836. {
  837. tryActivateStackSpellcasting(s);
  838. possibleActions = getPossibleActionsForStack(s);
  839. owner.windowObject->setPossibleActions(possibleActions);
  840. }
  841. }
  842. void BattleActionsController::onHexRightClicked(const BattleHex & clickedHex)
  843. {
  844. bool isCurrentStackInSpellcastMode = creatureSpellcastingModeActive();
  845. if (heroSpellcastingModeActive() || isCurrentStackInSpellcastMode)
  846. {
  847. endCastingSpell();
  848. CRClickPopup::createAndPush(LIBRARY->generaltexth->translate("core.genrltxt.731")); // spell cancelled
  849. return;
  850. }
  851. auto selectedStack = owner.getBattle()->battleGetStackByPos(clickedHex, true);
  852. if (selectedStack != nullptr)
  853. ENGINE->windows().createAndPushWindow<CStackWindow>(selectedStack, true);
  854. if (clickedHex == BattleHex::HERO_ATTACKER && owner.attackingHero)
  855. owner.attackingHero->heroRightClicked();
  856. if (clickedHex == BattleHex::HERO_DEFENDER && owner.defendingHero)
  857. owner.defendingHero->heroRightClicked();
  858. }
  859. bool BattleActionsController::heroSpellcastingModeActive() const
  860. {
  861. return heroSpellToCast != nullptr;
  862. }
  863. bool BattleActionsController::creatureSpellcastingModeActive() const
  864. {
  865. auto spellcastModePredicate = [](const PossiblePlayerBattleAction & action)
  866. {
  867. return action.spellcast() || action.get() == PossiblePlayerBattleAction::SHOOT; //for hotkey-eligible SPELL_LIKE_ATTACK creature should have only SHOOT action
  868. };
  869. return !possibleActions.empty() && std::all_of(possibleActions.begin(), possibleActions.end(), spellcastModePredicate);
  870. }
  871. bool BattleActionsController::currentActionSpellcasting(const BattleHex & hoveredHex)
  872. {
  873. if (heroSpellToCast)
  874. return true;
  875. if (!owner.stacksController->getActiveStack())
  876. return false;
  877. auto action = selectAction(hoveredHex);
  878. return action.spellcast();
  879. }
  880. const std::vector<PossiblePlayerBattleAction> & BattleActionsController::getPossibleActions() const
  881. {
  882. return possibleActions;
  883. }
  884. void BattleActionsController::setPriorityActions(const std::vector<PossiblePlayerBattleAction> & actions)
  885. {
  886. possibleActions = actions;
  887. }
  888. void BattleActionsController::resetCurrentStackPossibleActions()
  889. {
  890. possibleActions = getPossibleActionsForStack(owner.stacksController->getActiveStack());
  891. }