BattleActionsController.cpp 35 KB

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