BattleProcessor.cpp 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753
  1. /*
  2. * BattleProcessor.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 "BattleProcessor.h"
  12. #include "../CGameHandler.h"
  13. #include "../CVCMIServer.h"
  14. #include "../processors/HeroPoolProcessor.h"
  15. #include "../queries/CQuery.h"
  16. #include "../../lib/ArtifactUtils.h"
  17. #include "../../lib/CGeneralTextHandler.h"
  18. #include "../../lib/CModHandler.h"
  19. #include "../../lib/CStack.h"
  20. #include "../../lib/CondSh.h"
  21. #include "../../lib/GameSettings.h"
  22. #include "../../lib/ScopeGuard.h"
  23. #include "../../lib/TerrainHandler.h"
  24. #include "../../lib/battle/BattleInfo.h"
  25. #include "../../lib/battle/CUnitState.h"
  26. #include "../../lib/gameState/CGameState.h"
  27. #include "../../lib/mapObjects/CGTownInstance.h"
  28. #include "../../lib/mapping/CMap.h"
  29. #include "../../lib/serializer/Cast.h"
  30. #include "../../lib/spells/AbilityCaster.h"
  31. #include "../../lib/spells/BonusCaster.h"
  32. #include "../../lib/spells/CSpellHandler.h"
  33. #include "../../lib/spells/ISpellMechanics.h"
  34. #include "../../lib/spells/ObstacleCasterProxy.h"
  35. #include "../../lib/spells/Problem.h"
  36. #define COMPLAIN_RET_IF(cond, txt) do {if (cond){gameHandler->complain(txt); return;}} while(0)
  37. #define COMPLAIN_RET_FALSE_IF(cond, txt) do {if (cond){gameHandler->complain(txt); return false;}} while(0)
  38. #define COMPLAIN_RET(txt) {gameHandler->complain(txt); return false;}
  39. #define COMPLAIN_RETF(txt, FORMAT) {gameHandler->complain(boost::str(boost::format(txt) % FORMAT)); return false;}
  40. CondSh<bool> battleMadeAction(false);
  41. CondSh<BattleResult *> battleResult(nullptr);
  42. boost::recursive_mutex battleActionMutex;
  43. static EndAction end_action;
  44. static void giveExp(BattleResult &r)
  45. {
  46. if (r.winner > 1)
  47. {
  48. // draw
  49. return;
  50. }
  51. r.exp[0] = 0;
  52. r.exp[1] = 0;
  53. for (auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  54. {
  55. r.exp[r.winner] += VLC->creh->objects.at(i->first)->valOfBonuses(BonusType::STACK_HEALTH) * i->second;
  56. }
  57. }
  58. static void summonGuardiansHelper(std::vector<BattleHex> & output, const BattleHex & targetPosition, ui8 side, bool targetIsTwoHex) //return hexes for summoning two hex monsters in output, target = unit to guard
  59. {
  60. int x = targetPosition.getX();
  61. int y = targetPosition.getY();
  62. const bool targetIsAttacker = side == BattleSide::ATTACKER;
  63. if (targetIsAttacker) //handle front guardians, TODO: should we handle situation when units start battle near opposite side of the battlefield? Cannot happen in normal H3...
  64. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  65. else
  66. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  67. //guardian spawn locations for four default position cases for attacker and defender, non-default starting location for att and def is handled in first two if's
  68. if (targetIsAttacker && ((y % 2 == 0) || (x > 1)))
  69. {
  70. if (targetIsTwoHex && (y % 2 == 1) && (x == 2)) //handle exceptional case
  71. {
  72. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  73. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  74. }
  75. else
  76. { //add back-side guardians for two-hex target, side guardians for one-hex
  77. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_LEFT : BattleHex::EDir::TOP_RIGHT, false), output);
  78. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_LEFT : BattleHex::EDir::BOTTOM_RIGHT, false), output);
  79. if (!targetIsTwoHex && x > 2) //back guard for one-hex
  80. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false), output);
  81. else if (targetIsTwoHex)//front-side guardians for two-hex target
  82. {
  83. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  84. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  85. if (x > 3) //back guard for two-hex
  86. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  87. }
  88. }
  89. }
  90. else if (!targetIsAttacker && ((y % 2 == 1) || (x < GameConstants::BFIELD_WIDTH - 2)))
  91. {
  92. if (targetIsTwoHex && (y % 2 == 0) && (x == GameConstants::BFIELD_WIDTH - 3)) //handle exceptional case... equivalent for above for defender side
  93. {
  94. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  95. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  96. }
  97. else
  98. {
  99. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_RIGHT : BattleHex::EDir::TOP_LEFT, false), output);
  100. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_RIGHT : BattleHex::EDir::BOTTOM_LEFT, false), output);
  101. if (!targetIsTwoHex && x < GameConstants::BFIELD_WIDTH - 3)
  102. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  103. else if (targetIsTwoHex)
  104. {
  105. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  106. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  107. if (x < GameConstants::BFIELD_WIDTH - 4)
  108. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  109. }
  110. }
  111. }
  112. else if (!targetIsAttacker && y % 2 == 0)
  113. {
  114. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  115. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  116. }
  117. else if (targetIsAttacker && y % 2 == 1)
  118. {
  119. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  120. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  121. }
  122. }
  123. CasualtiesAfterBattle::CasualtiesAfterBattle(const SideInBattle & battleSide, const BattleInfo * bat):
  124. army(battleSide.armyObject)
  125. {
  126. heroWithDeadCommander = ObjectInstanceID();
  127. PlayerColor color = battleSide.color;
  128. for(CStack * st : bat->stacks)
  129. {
  130. if(st->summoned) //don't take into account temporary summoned stacks
  131. continue;
  132. if(st->unitOwner() != color) //remove only our stacks
  133. continue;
  134. logGlobal->debug("Calculating casualties for %s", st->nodeName());
  135. st->health.takeResurrected();
  136. if(st->unitSlot() == SlotID::ARROW_TOWERS_SLOT)
  137. {
  138. logGlobal->debug("Ignored arrow towers stack.");
  139. }
  140. else if(st->unitSlot() == SlotID::WAR_MACHINES_SLOT)
  141. {
  142. auto warMachine = st->unitType()->warMachine;
  143. if(warMachine == ArtifactID::NONE)
  144. {
  145. logGlobal->error("Invalid creature in war machine virtual slot. Stack: %s", st->nodeName());
  146. }
  147. //catapult artifact remain even if "creature" killed in siege
  148. else if(warMachine != ArtifactID::CATAPULT && st->getCount() <= 0)
  149. {
  150. logGlobal->debug("War machine has been destroyed");
  151. auto hero = dynamic_ptr_cast<CGHeroInstance> (army);
  152. if (hero)
  153. removedWarMachines.push_back (ArtifactLocation(hero, hero->getArtPos(warMachine, true)));
  154. else
  155. logGlobal->error("War machine in army without hero");
  156. }
  157. }
  158. else if(st->unitSlot() == SlotID::SUMMONED_SLOT_PLACEHOLDER)
  159. {
  160. if(st->alive() && st->getCount() > 0)
  161. {
  162. logGlobal->debug("Permanently summoned %d units.", st->getCount());
  163. const CreatureID summonedType = st->creatureId();
  164. summoned[summonedType] += st->getCount();
  165. }
  166. }
  167. else if(st->unitSlot() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  168. {
  169. if (nullptr == st->base)
  170. {
  171. logGlobal->error("Stack with no base in commander slot. Stack: %s", st->nodeName());
  172. }
  173. else
  174. {
  175. auto c = dynamic_cast <const CCommanderInstance *>(st->base);
  176. if(c)
  177. {
  178. auto h = dynamic_cast <const CGHeroInstance *>(army);
  179. if(h && h->commander == c && (st->getCount() == 0 || !st->alive()))
  180. {
  181. logGlobal->debug("Commander is dead.");
  182. heroWithDeadCommander = army->id; //TODO: unify commander handling
  183. }
  184. }
  185. else
  186. logGlobal->error("Stack with invalid instance in commander slot. Stack: %s", st->nodeName());
  187. }
  188. }
  189. else if(st->base && !army->slotEmpty(st->unitSlot()))
  190. {
  191. logGlobal->debug("Count: %d; base count: %d", st->getCount(), army->getStackCount(st->unitSlot()));
  192. if(st->getCount() == 0 || !st->alive())
  193. {
  194. logGlobal->debug("Stack has been destroyed.");
  195. StackLocation sl(army, st->unitSlot());
  196. newStackCounts.push_back(TStackAndItsNewCount(sl, 0));
  197. }
  198. else if(st->getCount() < army->getStackCount(st->unitSlot()))
  199. {
  200. logGlobal->debug("Stack lost %d units.", army->getStackCount(st->unitSlot()) - st->getCount());
  201. StackLocation sl(army, st->unitSlot());
  202. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  203. }
  204. else if(st->getCount() > army->getStackCount(st->unitSlot()))
  205. {
  206. logGlobal->debug("Stack gained %d units.", st->getCount() - army->getStackCount(st->unitSlot()));
  207. StackLocation sl(army, st->unitSlot());
  208. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  209. }
  210. }
  211. else
  212. {
  213. logGlobal->warn("Unable to process stack: %s", st->nodeName());
  214. }
  215. }
  216. }
  217. void CasualtiesAfterBattle::updateArmy(CGameHandler *gh)
  218. {
  219. for (TStackAndItsNewCount &ncount : newStackCounts)
  220. {
  221. if (ncount.second > 0)
  222. gh->changeStackCount(ncount.first, ncount.second, true);
  223. else
  224. gh->eraseStack(ncount.first, true);
  225. }
  226. for (auto summoned_iter : summoned)
  227. {
  228. SlotID slot = army->getSlotFor(summoned_iter.first);
  229. if (slot.validSlot())
  230. {
  231. StackLocation location(army, slot);
  232. gh->addToSlot(location, summoned_iter.first.toCreature(), summoned_iter.second);
  233. }
  234. else
  235. {
  236. //even if it will be possible to summon anything permanently it should be checked for free slot
  237. //necromancy is handled separately
  238. gh->complain("No free slot to put summoned creature");
  239. }
  240. }
  241. for (auto al : removedWarMachines)
  242. {
  243. gh->removeArtifact(al);
  244. }
  245. if (heroWithDeadCommander != ObjectInstanceID())
  246. {
  247. SetCommanderProperty scp;
  248. scp.heroid = heroWithDeadCommander;
  249. scp.which = SetCommanderProperty::ALIVE;
  250. scp.amount = 0;
  251. gh->sendAndApply(&scp);
  252. }
  253. }
  254. BattleProcessor::BattleProcessor(CGameHandler * gameHandler):
  255. visitObjectAfterVictory(false),
  256. gameHandler(gameHandler)
  257. {
  258. }
  259. BattleProcessor::BattleProcessor():
  260. visitObjectAfterVictory(false),
  261. gameHandler(nullptr)
  262. {
  263. }
  264. BattleProcessor::~BattleProcessor()
  265. {
  266. if (battleThread)
  267. {
  268. //Setting battleMadeAction is needed because battleThread waits for the action to continue the main loop
  269. battleMadeAction.setn(true);
  270. battleThread->join();
  271. }
  272. }
  273. FinishingBattleHelper::FinishingBattleHelper(std::shared_ptr<const CBattleQuery> Query, int remainingBattleQueriesCount)
  274. {
  275. assert(Query->result);
  276. assert(Query->bi);
  277. auto &result = *Query->result;
  278. auto &info = *Query->bi;
  279. winnerHero = result.winner != 0 ? info.sides[1].hero : info.sides[0].hero;
  280. loserHero = result.winner != 0 ? info.sides[0].hero : info.sides[1].hero;
  281. victor = info.sides[result.winner].color;
  282. loser = info.sides[!result.winner].color;
  283. winnerSide = result.winner;
  284. this->remainingBattleQueriesCount = remainingBattleQueriesCount;
  285. }
  286. FinishingBattleHelper::FinishingBattleHelper()
  287. {
  288. winnerHero = loserHero = nullptr;
  289. winnerSide = 0;
  290. remainingBattleQueriesCount = 0;
  291. }
  292. void BattleProcessor::engageIntoBattle(PlayerColor player)
  293. {
  294. //notify interfaces
  295. PlayerBlocked pb;
  296. pb.player = player;
  297. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  298. pb.startOrEnd = PlayerBlocked::BLOCKADE_STARTED;
  299. gameHandler->sendAndApply(&pb);
  300. }
  301. void BattleProcessor::startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile,
  302. const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank,
  303. const CGTownInstance *town) //use hero=nullptr for no hero
  304. {
  305. if(gameHandler->gameState()->curB)
  306. gameHandler->gameState()->curB.dellNull();
  307. engageIntoBattle(army1->tempOwner);
  308. engageIntoBattle(army2->tempOwner);
  309. static const CArmedInstance *armies[2];
  310. armies[0] = army1;
  311. armies[1] = army2;
  312. static const CGHeroInstance*heroes[2];
  313. heroes[0] = hero1;
  314. heroes[1] = hero2;
  315. setupBattle(tile, armies, heroes, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  316. auto lastBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries.topQuery(gameHandler->gameState()->curB->sides[0].color));
  317. //existing battle query for retying auto-combat
  318. if(lastBattleQuery)
  319. {
  320. for(int i : {0, 1})
  321. {
  322. if(heroes[i])
  323. {
  324. SetMana restoreInitialMana;
  325. restoreInitialMana.val = lastBattleQuery->initialHeroMana[i];
  326. restoreInitialMana.hid = heroes[i]->id;
  327. gameHandler->sendAndApply(&restoreInitialMana);
  328. }
  329. }
  330. lastBattleQuery->bi = gameHandler->gameState()->curB;
  331. lastBattleQuery->result = std::nullopt;
  332. lastBattleQuery->belligerents[0] = gameHandler->gameState()->curB->sides[0].armyObject;
  333. lastBattleQuery->belligerents[1] = gameHandler->gameState()->curB->sides[1].armyObject;
  334. }
  335. auto nextBattleQuery = std::make_shared<CBattleQuery>(gameHandler, gameHandler->gameState()->curB);
  336. for(int i : {0, 1})
  337. {
  338. if(heroes[i])
  339. {
  340. nextBattleQuery->initialHeroMana[i] = heroes[i]->mana;
  341. }
  342. }
  343. gameHandler->queries->addQuery(nextBattleQuery);
  344. this->battleThread = std::make_unique<boost::thread>(boost::thread(&BattleProcessor::runBattle, this));
  345. }
  346. void BattleProcessor::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank)
  347. {
  348. startBattlePrimary(army1, army2, tile,
  349. army1->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army1) : nullptr,
  350. army2->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army2) : nullptr,
  351. creatureBank);
  352. }
  353. void BattleProcessor::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank)
  354. {
  355. startBattleI(army1, army2, army2->visitablePos(), creatureBank);
  356. }
  357. void BattleProcessor::runBattle()
  358. {
  359. boost::unique_lock lock(battleActionMutex);
  360. gameHandler->setBattle(gameHandler->gameState()->curB);
  361. assert(gameHandler->gameState()->curB);
  362. //TODO: pre-tactic stuff, call scripts etc.
  363. //Moat should be initialized here, because only here we can use spellcasting
  364. if (gameHandler->gameState()->curB->town && gameHandler->gameState()->curB->town->fortLevel() >= CGTownInstance::CITADEL)
  365. {
  366. const auto * h = gameHandler->gameState()->curB->battleGetFightingHero(BattleSide::DEFENDER);
  367. const auto * actualCaster = h ? static_cast<const spells::Caster*>(h) : nullptr;
  368. auto moatCaster = spells::SilentCaster(gameHandler->gameState()->curB->getSidePlayer(BattleSide::DEFENDER), actualCaster);
  369. auto cast = spells::BattleCast(gameHandler->gameState()->curB, &moatCaster, spells::Mode::PASSIVE, gameHandler->gameState()->curB->town->town->moatAbility.toSpell());
  370. auto target = spells::Target();
  371. cast.cast(gameHandler->spellEnv, target);
  372. }
  373. //tactic round
  374. {
  375. while ((gameHandler->gameLobby()->state != EServerState::SHUTDOWN) && gameHandler->gameState()->curB->tacticDistance && !battleResult.get())
  376. {
  377. auto unlockGuard = vstd::makeUnlockGuard(battleActionMutex);
  378. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  379. }
  380. }
  381. //initial stacks appearance triggers, e.g. built-in bonus spells
  382. auto initialStacks = gameHandler->gameState()->curB->stacks; //use temporary variable to outclude summoned stacks added to gameHandler->gameState()->curB->stacks from processing
  383. for (CStack * stack : initialStacks)
  384. {
  385. if (stack->hasBonusOfType(BonusType::SUMMON_GUARDIANS))
  386. {
  387. std::shared_ptr<const Bonus> summonInfo = stack->getBonus(Selector::type()(BonusType::SUMMON_GUARDIANS));
  388. auto accessibility = gameHandler->getAccesibility();
  389. CreatureID creatureData = CreatureID(summonInfo->subtype);
  390. std::vector<BattleHex> targetHexes;
  391. const bool targetIsBig = stack->unitType()->isDoubleWide(); //target = creature to guard
  392. const bool guardianIsBig = creatureData.toCreature()->isDoubleWide();
  393. /*Chosen idea for two hex units was to cover all possible surrounding hexes of target unit with as small number of stacks as possible.
  394. For one-hex targets there are four guardians - front, back and one per side (up + down).
  395. Two-hex targets are wider and the difference is there are two guardians per side to cover 3 hexes + extra hex in the front
  396. Additionally, there are special cases for starting positions etc., where guardians would be outside of battlefield if spawned normally*/
  397. if (!guardianIsBig)
  398. targetHexes = stack->getSurroundingHexes();
  399. else
  400. summonGuardiansHelper(targetHexes, stack->getPosition(), stack->unitSide(), targetIsBig);
  401. for(auto hex : targetHexes)
  402. {
  403. if(accessibility.accessible(hex, guardianIsBig, stack->unitSide())) //without this multiple creatures can occupy one hex
  404. {
  405. battle::UnitInfo info;
  406. info.id = gameHandler->gameState()->curB->battleNextUnitId();
  407. info.count = std::max(1, (int)(stack->getCount() * 0.01 * summonInfo->val));
  408. info.type = creatureData;
  409. info.side = stack->unitSide();
  410. info.position = hex;
  411. info.summoned = true;
  412. BattleUnitsChanged pack;
  413. pack.changedStacks.emplace_back(info.id, UnitChanges::EOperation::ADD);
  414. info.save(pack.changedStacks.back().data);
  415. gameHandler->sendAndApply(&pack);
  416. }
  417. }
  418. }
  419. stackEnchantedTrigger(stack);
  420. }
  421. //spells opening battle
  422. for (int i = 0; i < 2; ++i)
  423. {
  424. auto h = gameHandler->gameState()->curB->battleGetFightingHero(i);
  425. if (h)
  426. {
  427. TConstBonusListPtr bl = h->getBonuses(Selector::type()(BonusType::OPENING_BATTLE_SPELL));
  428. for (auto b : *bl)
  429. {
  430. spells::BonusCaster caster(h, b);
  431. const CSpell * spell = SpellID(b->subtype).toSpell();
  432. spells::BattleCast parameters(gameHandler->gameState()->curB, &caster, spells::Mode::PASSIVE, spell);
  433. parameters.setSpellLevel(3);
  434. parameters.setEffectDuration(b->val);
  435. parameters.massive = true;
  436. parameters.castIfPossible(gameHandler->spellEnv, spells::Target());
  437. }
  438. }
  439. }
  440. // it is possible that due to opening spells one side was eliminated -> check for end of battle
  441. checkBattleStateChanges();
  442. bool firstRound = true;//FIXME: why first round is -1?
  443. //main loop
  444. while ((gameHandler->gameLobby()->state != EServerState::SHUTDOWN) && !battleResult.get()) //till the end of the battle ;]
  445. {
  446. BattleNextRound bnr;
  447. bnr.round = gameHandler->gameState()->curB->round + 1;
  448. logGlobal->debug("Round %d", bnr.round);
  449. gameHandler->sendAndApply(&bnr);
  450. auto obstacles = gameHandler->gameState()->curB->obstacles; //we copy container, because we're going to modify it
  451. for (auto &obstPtr : obstacles)
  452. {
  453. if (const SpellCreatedObstacle *sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get()))
  454. if (sco->turnsRemaining == 0)
  455. removeObstacle(*obstPtr);
  456. }
  457. const BattleInfo & curB = *gameHandler->gameState()->curB;
  458. for(auto stack : curB.stacks)
  459. {
  460. if(stack->alive() && !firstRound)
  461. stackEnchantedTrigger(stack);
  462. }
  463. //stack loop
  464. auto getNextStack = [this]() -> const CStack *
  465. {
  466. if(battleResult.get())
  467. return nullptr;
  468. std::vector<battle::Units> q;
  469. gameHandler->gameState()->curB->battleGetTurnOrder(q, 1, 0, -1); //todo: get rid of "turn -1"
  470. if(!q.empty())
  471. {
  472. if(!q.front().empty())
  473. {
  474. auto next = q.front().front();
  475. const auto stack = dynamic_cast<const CStack *>(next);
  476. // regeneration takes place before everything else but only during first turn attempt in each round
  477. // also works under blind and similar effects
  478. if(stack && stack->alive() && !stack->waiting)
  479. {
  480. BattleTriggerEffect bte;
  481. bte.stackID = stack->unitId();
  482. bte.effect = vstd::to_underlying(BonusType::HP_REGENERATION);
  483. const int32_t lostHealth = stack->getMaxHealth() - stack->getFirstHPleft();
  484. if(stack->hasBonusOfType(BonusType::HP_REGENERATION))
  485. bte.val = std::min(lostHealth, stack->valOfBonuses(BonusType::HP_REGENERATION));
  486. if(bte.val) // anything to heal
  487. gameHandler->sendAndApply(&bte);
  488. }
  489. if(next->willMove())
  490. return stack;
  491. }
  492. }
  493. return nullptr;
  494. };
  495. const CStack * next = nullptr;
  496. while((gameHandler->gameLobby()->state != EServerState::SHUTDOWN) && (next = getNextStack()))
  497. {
  498. BattleUnitsChanged removeGhosts;
  499. for(auto stack : curB.stacks)
  500. {
  501. if(stack->ghostPending)
  502. removeGhosts.changedStacks.emplace_back(stack->unitId(), UnitChanges::EOperation::REMOVE);
  503. }
  504. if(!removeGhosts.changedStacks.empty())
  505. gameHandler->sendAndApply(&removeGhosts);
  506. // check for bad morale => freeze
  507. int nextStackMorale = next->moraleVal();
  508. if(!next->hadMorale && !next->waited() && nextStackMorale < 0)
  509. {
  510. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_MORALE_DICE);
  511. size_t diceIndex = std::min<size_t>(diceSize.size()-1, -nextStackMorale);
  512. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  513. {
  514. //unit loses its turn - empty freeze action
  515. BattleAction ba;
  516. ba.actionType = EActionType::BAD_MORALE;
  517. ba.side = next->unitSide();
  518. ba.stackNumber = next->unitId();
  519. makeAutomaticAction(next, ba);
  520. continue;
  521. }
  522. }
  523. if (next->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE)) //while in berserk
  524. {
  525. logGlobal->trace("Handle Berserk effect");
  526. std::pair<const battle::Unit *, BattleHex> attackInfo = curB.getNearestStack(next);
  527. if (attackInfo.first != nullptr)
  528. {
  529. BattleAction attack;
  530. attack.actionType = EActionType::WALK_AND_ATTACK;
  531. attack.side = next->unitSide();
  532. attack.stackNumber = next->unitId();
  533. attack.aimToHex(attackInfo.second);
  534. attack.aimToUnit(attackInfo.first);
  535. makeAutomaticAction(next, attack);
  536. logGlobal->trace("Attacked nearest target %s", attackInfo.first->getDescription());
  537. }
  538. else
  539. {
  540. makeStackDoNothing(next);
  541. logGlobal->trace("No target found");
  542. }
  543. continue;
  544. }
  545. const CGHeroInstance * curOwner = gameHandler->battleGetOwnerHero(next);
  546. const int stackCreatureId = next->unitType()->getId();
  547. if ((stackCreatureId == CreatureID::ARROW_TOWERS || stackCreatureId == CreatureID::BALLISTA)
  548. && (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, stackCreatureId)))
  549. {
  550. BattleAction attack;
  551. attack.actionType = EActionType::SHOOT;
  552. attack.side = next->unitSide();
  553. attack.stackNumber = next->unitId();
  554. //TODO: select target by priority
  555. const battle::Unit * target = nullptr;
  556. for(auto & elem : gameHandler->gameState()->curB->stacks)
  557. {
  558. if(elem->unitType()->getId() != CreatureID::CATAPULT
  559. && elem->unitOwner() != next->unitOwner()
  560. && elem->isValidTarget()
  561. && gameHandler->gameState()->curB->battleCanShoot(next, elem->getPosition()))
  562. {
  563. target = elem;
  564. break;
  565. }
  566. }
  567. if(target == nullptr)
  568. {
  569. makeStackDoNothing(next);
  570. }
  571. else
  572. {
  573. attack.aimToUnit(target);
  574. makeAutomaticAction(next, attack);
  575. }
  576. continue;
  577. }
  578. if (next->unitType()->getId() == CreatureID::CATAPULT)
  579. {
  580. const auto & attackableBattleHexes = curB.getAttackableBattleHexes();
  581. if (attackableBattleHexes.empty())
  582. {
  583. makeStackDoNothing(next);
  584. continue;
  585. }
  586. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::CATAPULT))
  587. {
  588. BattleAction attack;
  589. attack.actionType = EActionType::CATAPULT;
  590. attack.side = next->unitSide();
  591. attack.stackNumber = next->unitId();
  592. makeAutomaticAction(next, attack);
  593. continue;
  594. }
  595. }
  596. if (next->unitType()->getId() == CreatureID::FIRST_AID_TENT)
  597. {
  598. TStacks possibleStacks = gameHandler->battleGetStacksIf([=](const CStack * s)
  599. {
  600. return s->unitOwner() == next->unitOwner() && s->canBeHealed();
  601. });
  602. if (!possibleStacks.size())
  603. {
  604. makeStackDoNothing(next);
  605. continue;
  606. }
  607. if (!curOwner || gameHandler->getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::FIRST_AID_TENT))
  608. {
  609. RandomGeneratorUtil::randomShuffle(possibleStacks, gameHandler->getRandomGenerator());
  610. const CStack * toBeHealed = possibleStacks.front();
  611. BattleAction heal;
  612. heal.actionType = EActionType::STACK_HEAL;
  613. heal.aimToUnit(toBeHealed);
  614. heal.side = next->unitSide();
  615. heal.stackNumber = next->unitId();
  616. makeAutomaticAction(next, heal);
  617. continue;
  618. }
  619. }
  620. int numberOfAsks = 1;
  621. bool breakOuter = false;
  622. do
  623. {//ask interface and wait for answer
  624. if (!battleResult.get())
  625. {
  626. stackTurnTrigger(next); //various effects
  627. if(next->fear)
  628. {
  629. makeStackDoNothing(next); //end immediately if stack was affected by fear
  630. }
  631. else
  632. {
  633. logGlobal->trace("Activating %s", next->nodeName());
  634. auto nextId = next->unitId();
  635. BattleSetActiveStack sas;
  636. sas.stack = nextId;
  637. gameHandler->sendAndApply(&sas);
  638. auto actionWasMade = [&]() -> bool
  639. {
  640. if (battleMadeAction.data)//active stack has made its action
  641. return true;
  642. if (battleResult.get())// battle is finished
  643. return true;
  644. if (next == nullptr)//active stack was been removed
  645. return true;
  646. return !next->alive();//active stack is dead
  647. };
  648. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  649. battleMadeAction.data = false;
  650. while ((gameHandler->gameLobby()->state != EServerState::SHUTDOWN) && !actionWasMade())
  651. {
  652. {
  653. boost::unique_lock actionLock(battleActionMutex);
  654. battleMadeAction.cond.wait(lock);
  655. }
  656. if (gameHandler->battleGetStackByID(nextId, false) != next)
  657. next = nullptr; //it may be removed, while we wait
  658. }
  659. }
  660. }
  661. if (battleResult.get()) //don't touch it, battle could be finished while waiting got action
  662. {
  663. breakOuter = true;
  664. break;
  665. }
  666. //we're after action, all results applied
  667. checkBattleStateChanges(); //check if this action ended the battle
  668. if(next != nullptr)
  669. {
  670. //check for good morale
  671. nextStackMorale = next->moraleVal();
  672. if( !battleResult.get()
  673. && !next->hadMorale
  674. && !next->defending
  675. && !next->waited()
  676. && !next->fear
  677. && next->alive()
  678. && nextStackMorale > 0)
  679. {
  680. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_MORALE_DICE);
  681. size_t diceIndex = std::min<size_t>(diceSize.size()-1, nextStackMorale);
  682. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  683. {
  684. BattleTriggerEffect bte;
  685. bte.stackID = next->unitId();
  686. bte.effect = vstd::to_underlying(BonusType::MORALE);
  687. bte.val = 1;
  688. bte.additionalInfo = 0;
  689. gameHandler->sendAndApply(&bte); //play animation
  690. ++numberOfAsks; //move this stack once more
  691. }
  692. }
  693. }
  694. --numberOfAsks;
  695. } while (numberOfAsks > 0);
  696. if (breakOuter)
  697. {
  698. break;
  699. }
  700. }
  701. firstRound = false;
  702. }
  703. if (gameHandler->gameLobby()->state != EServerState::SHUTDOWN)
  704. endBattle(gameHandler->gameState()->curB->tile, gameHandler->gameState()->curB->battleGetFightingHero(0), gameHandler->gameState()->curB->battleGetFightingHero(1));
  705. }
  706. bool BattleProcessor::makeAutomaticAction(const CStack *stack, BattleAction &ba)
  707. {
  708. boost::unique_lock lock(battleActionMutex);
  709. BattleSetActiveStack bsa;
  710. bsa.stack = stack->unitId();
  711. bsa.askPlayerInterface = false;
  712. gameHandler->sendAndApply(&bsa);
  713. bool ret = makeBattleAction(ba);
  714. checkBattleStateChanges();
  715. return ret;
  716. }
  717. void BattleProcessor::attackCasting(bool ranged, BonusType attackMode, const battle::Unit * attacker, const battle::Unit * defender)
  718. {
  719. if(attacker->hasBonusOfType(attackMode))
  720. {
  721. std::set<SpellID> spellsToCast;
  722. TConstBonusListPtr spells = attacker->getBonuses(Selector::type()(attackMode));
  723. for(const auto & sf : *spells)
  724. {
  725. spellsToCast.insert(SpellID(sf->subtype));
  726. }
  727. for(SpellID spellID : spellsToCast)
  728. {
  729. bool castMe = false;
  730. if(!defender->alive())
  731. {
  732. logGlobal->debug("attackCasting: all attacked creatures have been killed");
  733. return;
  734. }
  735. int32_t spellLevel = 0;
  736. TConstBonusListPtr spellsByType = attacker->getBonuses(Selector::typeSubtype(attackMode, spellID));
  737. for(const auto & sf : *spellsByType)
  738. {
  739. int meleeRanged;
  740. if(sf->additionalInfo.size() < 2)
  741. {
  742. // legacy format
  743. vstd::amax(spellLevel, sf->additionalInfo[0] % 1000);
  744. meleeRanged = sf->additionalInfo[0] / 1000;
  745. }
  746. else
  747. {
  748. vstd::amax(spellLevel, sf->additionalInfo[0]);
  749. meleeRanged = sf->additionalInfo[1];
  750. }
  751. if (meleeRanged == 0 || (meleeRanged == 1 && ranged) || (meleeRanged == 2 && !ranged))
  752. castMe = true;
  753. }
  754. int chance = attacker->valOfBonuses((Selector::typeSubtype(attackMode, spellID)));
  755. vstd::amin(chance, 100);
  756. const CSpell * spell = SpellID(spellID).toSpell();
  757. spells::AbilityCaster caster(attacker, spellLevel);
  758. spells::Target target;
  759. target.emplace_back(defender);
  760. spells::BattleCast parameters(gameHandler->gameState()->curB, &caster, spells::Mode::PASSIVE, spell);
  761. auto m = spell->battleMechanics(&parameters);
  762. spells::detail::ProblemImpl ignored;
  763. if(!m->canBeCastAt(target, ignored))
  764. continue;
  765. //check if spell should be cast (probability handling)
  766. if(gameHandler->getRandomGenerator().nextInt(99) >= chance)
  767. continue;
  768. //casting
  769. if(castMe)
  770. {
  771. parameters.cast(gameHandler->spellEnv, target);
  772. }
  773. }
  774. }
  775. }
  776. void BattleProcessor::handleAttackBeforeCasting(bool ranged, const CStack * attacker, const CStack * defender)
  777. {
  778. attackCasting(ranged, BonusType::SPELL_BEFORE_ATTACK, attacker, defender); //no death stare / acid breath needed?
  779. }
  780. void BattleProcessor::handleAfterAttackCasting(bool ranged, const CStack * attacker, const CStack * defender)
  781. {
  782. if(!attacker->alive() || !defender->alive()) // can be already dead
  783. return;
  784. attackCasting(ranged, BonusType::SPELL_AFTER_ATTACK, attacker, defender);
  785. if(!defender->alive())
  786. {
  787. //don't try death stare or acid breath on dead stack (crash!)
  788. return;
  789. }
  790. if(attacker->hasBonusOfType(BonusType::DEATH_STARE))
  791. {
  792. // mechanics of Death Stare as in H3:
  793. // each gorgon have 10% chance to kill (counted separately in H3) -> binomial distribution
  794. //original formula x = min(x, (gorgons_count + 9)/10);
  795. double chanceToKill = attacker->valOfBonuses(BonusType::DEATH_STARE, 0) / 100.0f;
  796. vstd::amin(chanceToKill, 1); //cap at 100%
  797. std::binomial_distribution<> distribution(attacker->getCount(), chanceToKill);
  798. int staredCreatures = distribution(gameHandler->getRandomGenerator().getStdGenerator());
  799. double cap = 1 / std::max(chanceToKill, (double)(0.01));//don't divide by 0
  800. int maxToKill = static_cast<int>((attacker->getCount() + cap - 1) / cap); //not much more than chance * count
  801. vstd::amin(staredCreatures, maxToKill);
  802. staredCreatures += (attacker->level() * attacker->valOfBonuses(BonusType::DEATH_STARE, 1)) / defender->level();
  803. if(staredCreatures)
  804. {
  805. //TODO: death stare was not originally available for multiple-hex attacks, but...
  806. const CSpell * spell = SpellID(SpellID::DEATH_STARE).toSpell();
  807. spells::AbilityCaster caster(attacker, 0);
  808. spells::BattleCast parameters(gameHandler->gameState()->curB, &caster, spells::Mode::PASSIVE, spell);
  809. spells::Target target;
  810. target.emplace_back(defender);
  811. parameters.setEffectValue(staredCreatures);
  812. parameters.cast(gameHandler->spellEnv, target);
  813. }
  814. }
  815. if(!defender->alive())
  816. return;
  817. int64_t acidDamage = 0;
  818. TConstBonusListPtr acidBreath = attacker->getBonuses(Selector::type()(BonusType::ACID_BREATH));
  819. for(const auto & b : *acidBreath)
  820. {
  821. if(b->additionalInfo[0] > gameHandler->getRandomGenerator().nextInt(99))
  822. acidDamage += b->val;
  823. }
  824. if(acidDamage > 0)
  825. {
  826. const CSpell * spell = SpellID(SpellID::ACID_BREATH_DAMAGE).toSpell();
  827. spells::AbilityCaster caster(attacker, 0);
  828. spells::BattleCast parameters(gameHandler->gameState()->curB, &caster, spells::Mode::PASSIVE, spell);
  829. spells::Target target;
  830. target.emplace_back(defender);
  831. parameters.setEffectValue(acidDamage * attacker->getCount());
  832. parameters.cast(gameHandler->spellEnv, target);
  833. }
  834. if(!defender->alive())
  835. return;
  836. if(attacker->hasBonusOfType(BonusType::TRANSMUTATION) && defender->isLiving()) //transmutation mechanics, similar to WoG werewolf ability
  837. {
  838. double chanceToTrigger = attacker->valOfBonuses(BonusType::TRANSMUTATION) / 100.0f;
  839. vstd::amin(chanceToTrigger, 1); //cap at 100%
  840. if(gameHandler->getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  841. return;
  842. int bonusAdditionalInfo = attacker->getBonus(Selector::type()(BonusType::TRANSMUTATION))->additionalInfo[0];
  843. if(defender->unitType()->getId() == bonusAdditionalInfo ||
  844. (bonusAdditionalInfo == CAddInfo::NONE && defender->unitType()->getId() == attacker->unitType()->getId()))
  845. return;
  846. battle::UnitInfo resurrectInfo;
  847. resurrectInfo.id = gameHandler->gameState()->curB->battleNextUnitId();
  848. resurrectInfo.summoned = false;
  849. resurrectInfo.position = defender->getPosition();
  850. resurrectInfo.side = defender->unitSide();
  851. if(bonusAdditionalInfo != CAddInfo::NONE)
  852. resurrectInfo.type = CreatureID(bonusAdditionalInfo);
  853. else
  854. resurrectInfo.type = attacker->creatureId();
  855. if(attacker->hasBonusOfType((BonusType::TRANSMUTATION), 0))
  856. resurrectInfo.count = std::max((defender->getCount() * defender->getMaxHealth()) / resurrectInfo.type.toCreature()->getMaxHealth(), 1u);
  857. else if (attacker->hasBonusOfType((BonusType::TRANSMUTATION), 1))
  858. resurrectInfo.count = defender->getCount();
  859. else
  860. return; //wrong subtype
  861. BattleUnitsChanged addUnits;
  862. addUnits.changedStacks.emplace_back(resurrectInfo.id, UnitChanges::EOperation::ADD);
  863. resurrectInfo.save(addUnits.changedStacks.back().data);
  864. BattleUnitsChanged removeUnits;
  865. removeUnits.changedStacks.emplace_back(defender->unitId(), UnitChanges::EOperation::REMOVE);
  866. gameHandler->sendAndApply(&removeUnits);
  867. gameHandler->sendAndApply(&addUnits);
  868. }
  869. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0) || attacker->hasBonusOfType(BonusType::DESTRUCTION, 1))
  870. {
  871. double chanceToTrigger = 0;
  872. int amountToDie = 0;
  873. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0)) //killing by percentage
  874. {
  875. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 0) / 100.0f;
  876. int percentageToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(0)))->additionalInfo[0];
  877. amountToDie = static_cast<int>(defender->getCount() * percentageToDie * 0.01f);
  878. }
  879. else if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 1)) //killing by count
  880. {
  881. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 1) / 100.0f;
  882. amountToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(1)))->additionalInfo[0];
  883. }
  884. vstd::amin(chanceToTrigger, 1); //cap trigger chance at 100%
  885. if(gameHandler->getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  886. return;
  887. BattleStackAttacked bsa;
  888. bsa.attackerID = -1;
  889. bsa.stackAttacked = defender->unitId();
  890. bsa.damageAmount = amountToDie * defender->getMaxHealth();
  891. bsa.flags = BattleStackAttacked::SPELL_EFFECT;
  892. bsa.spellID = SpellID::SLAYER;
  893. defender->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  894. StacksInjured si;
  895. si.stacks.push_back(bsa);
  896. gameHandler->sendAndApply(&si);
  897. sendGenericKilledLog(defender, bsa.killedAmount, false);
  898. }
  899. }
  900. void BattleProcessor::makeAttack(const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter)
  901. {
  902. if(first && !counter)
  903. handleAttackBeforeCasting(ranged, attacker, defender);
  904. FireShieldInfo fireShield;
  905. BattleAttack bat;
  906. BattleLogMessage blm;
  907. bat.stackAttacking = attacker->unitId();
  908. bat.tile = targetHex;
  909. std::shared_ptr<battle::CUnitState> attackerState = attacker->acquireState();
  910. if(ranged)
  911. bat.flags |= BattleAttack::SHOT;
  912. if(counter)
  913. bat.flags |= BattleAttack::COUNTER;
  914. const int attackerLuck = attacker->luckVal();
  915. if(attackerLuck > 0)
  916. {
  917. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_LUCK_DICE);
  918. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, attackerLuck);
  919. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  920. bat.flags |= BattleAttack::LUCKY;
  921. }
  922. if(attackerLuck < 0)
  923. {
  924. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_LUCK_DICE);
  925. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, -attackerLuck);
  926. if(diceSize.size() > 0 && gameHandler->getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  927. bat.flags |= BattleAttack::UNLUCKY;
  928. }
  929. if (gameHandler->getRandomGenerator().nextInt(99) < attacker->valOfBonuses(BonusType::DOUBLE_DAMAGE_CHANCE))
  930. {
  931. bat.flags |= BattleAttack::DEATH_BLOW;
  932. }
  933. const auto * owner = gameHandler->gameState()->curB->getHero(attacker->unitOwner());
  934. if(owner)
  935. {
  936. int chance = owner->valOfBonuses(BonusType::BONUS_DAMAGE_CHANCE, attacker->creatureIndex());
  937. if (chance > gameHandler->getRandomGenerator().nextInt(99))
  938. bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
  939. }
  940. int64_t drainedLife = 0;
  941. // only primary target
  942. if(defender->alive())
  943. drainedLife += applyBattleEffects(bat, attackerState, fireShield, defender, distance, false);
  944. //multiple-hex normal attack
  945. std::set<const CStack*> attackedCreatures = gameHandler->gameState()->curB->getAttackedCreatures(attacker, targetHex, bat.shot()); //creatures other than primary target
  946. for(const CStack * stack : attackedCreatures)
  947. {
  948. if(stack != defender && stack->alive()) //do not hit same stack twice
  949. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  950. }
  951. std::shared_ptr<const Bonus> bonus = attacker->getBonusLocalFirst(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  952. if(bonus && ranged) //TODO: make it work in melee?
  953. {
  954. //this is need for displaying hit animation
  955. bat.flags |= BattleAttack::SPELL_LIKE;
  956. bat.spellID = SpellID(bonus->subtype);
  957. //TODO: should spell override creature`s projectile?
  958. auto spell = bat.spellID.toSpell();
  959. battle::Target target;
  960. target.emplace_back(defender, targetHex);
  961. spells::BattleCast event(gameHandler->gameState()->curB, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  962. event.setSpellLevel(bonus->val);
  963. auto attackedCreatures = spell->battleMechanics(&event)->getAffectedStacks(target);
  964. //TODO: get exact attacked hex for defender
  965. for(const CStack * stack : attackedCreatures)
  966. {
  967. if(stack != defender && stack->alive()) //do not hit same stack twice
  968. {
  969. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  970. }
  971. }
  972. //now add effect info for all attacked stacks
  973. for (BattleStackAttacked & bsa : bat.bsa)
  974. {
  975. if (bsa.attackerID == attacker->unitId()) //this is our attack and not f.e. fire shield
  976. {
  977. //this is need for displaying affect animation
  978. bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
  979. bsa.spellID = SpellID(bonus->subtype);
  980. }
  981. }
  982. }
  983. attackerState->afterAttack(ranged, counter);
  984. {
  985. UnitChanges info(attackerState->unitId(), UnitChanges::EOperation::RESET_STATE);
  986. attackerState->save(info.data);
  987. bat.attackerChanges.changedStacks.push_back(info);
  988. }
  989. if (drainedLife > 0)
  990. bat.flags |= BattleAttack::LIFE_DRAIN;
  991. gameHandler->sendAndApply(&bat);
  992. {
  993. const bool multipleTargets = bat.bsa.size() > 1;
  994. int64_t totalDamage = 0;
  995. int32_t totalKills = 0;
  996. for(const BattleStackAttacked & bsa : bat.bsa)
  997. {
  998. totalDamage += bsa.damageAmount;
  999. totalKills += bsa.killedAmount;
  1000. }
  1001. {
  1002. MetaString text;
  1003. attacker->addText(text, EMetaText::GENERAL_TXT, 376);
  1004. attacker->addNameReplacement(text);
  1005. text.replaceNumber(totalDamage);
  1006. blm.lines.push_back(text);
  1007. }
  1008. addGenericKilledLog(blm, defender, totalKills, multipleTargets);
  1009. }
  1010. // drain life effect (as well as log entry) must be applied after the attack
  1011. if(drainedLife > 0)
  1012. {
  1013. MetaString text;
  1014. attackerState->addText(text, EMetaText::GENERAL_TXT, 361);
  1015. attackerState->addNameReplacement(text, false);
  1016. text.replaceNumber(drainedLife);
  1017. defender->addNameReplacement(text, true);
  1018. blm.lines.push_back(std::move(text));
  1019. }
  1020. if(!fireShield.empty())
  1021. {
  1022. //todo: this should be "virtual" spell instead, we only need fire spell school bonus here
  1023. const CSpell * fireShieldSpell = SpellID(SpellID::FIRE_SHIELD).toSpell();
  1024. int64_t totalDamage = 0;
  1025. for(const auto & item : fireShield)
  1026. {
  1027. const CStack * actor = item.first;
  1028. int64_t rawDamage = item.second;
  1029. const CGHeroInstance * actorOwner = gameHandler->gameState()->curB->getHero(actor->unitOwner());
  1030. if(actorOwner)
  1031. {
  1032. rawDamage = fireShieldSpell->adjustRawDamage(actorOwner, attacker, rawDamage);
  1033. }
  1034. else
  1035. {
  1036. rawDamage = fireShieldSpell->adjustRawDamage(actor, attacker, rawDamage);
  1037. }
  1038. totalDamage+=rawDamage;
  1039. //FIXME: add custom effect on actor
  1040. }
  1041. if (totalDamage > 0)
  1042. {
  1043. BattleStackAttacked bsa;
  1044. bsa.flags |= BattleStackAttacked::FIRE_SHIELD;
  1045. bsa.stackAttacked = attacker->unitId(); //invert
  1046. bsa.attackerID = defender->unitId();
  1047. bsa.damageAmount = totalDamage;
  1048. attacker->prepareAttacked(bsa, gameHandler->getRandomGenerator());
  1049. StacksInjured pack;
  1050. pack.stacks.push_back(bsa);
  1051. gameHandler->sendAndApply(&pack);
  1052. // TODO: this is already implemented in Damage::describeEffect()
  1053. {
  1054. MetaString text;
  1055. text.appendLocalString(EMetaText::GENERAL_TXT, 376);
  1056. text.replaceLocalString(EMetaText::SPELL_NAME, SpellID::FIRE_SHIELD);
  1057. text.replaceNumber(totalDamage);
  1058. blm.lines.push_back(std::move(text));
  1059. }
  1060. addGenericKilledLog(blm, attacker, bsa.killedAmount, false);
  1061. }
  1062. }
  1063. gameHandler->sendAndApply(&blm);
  1064. handleAfterAttackCasting(ranged, attacker, defender);
  1065. }
  1066. int64_t BattleProcessor::applyBattleEffects(BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, int distance, bool secondary)
  1067. {
  1068. BattleStackAttacked bsa;
  1069. if(secondary)
  1070. bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
  1071. bsa.attackerID = attackerState->unitId();
  1072. bsa.stackAttacked = def->unitId();
  1073. {
  1074. BattleAttackInfo bai(attackerState.get(), def, distance, bat.shot());
  1075. bai.deathBlow = bat.deathBlow();
  1076. bai.doubleDamage = bat.ballistaDoubleDmg();
  1077. bai.luckyStrike = bat.lucky();
  1078. bai.unluckyStrike = bat.unlucky();
  1079. auto range = gameHandler->gameState()->curB->calculateDmgRange(bai);
  1080. bsa.damageAmount = gameHandler->gameState()->curB->getActualDamage(range.damage, attackerState->getCount(), gameHandler->getRandomGenerator());
  1081. CStack::prepareAttacked(bsa, gameHandler->getRandomGenerator(), bai.defender->acquireState()); //calculate casualties
  1082. }
  1083. int64_t drainedLife = 0;
  1084. //life drain handling
  1085. if(attackerState->hasBonusOfType(BonusType::LIFE_DRAIN) && def->isLiving())
  1086. {
  1087. int64_t toHeal = bsa.damageAmount * attackerState->valOfBonuses(BonusType::LIFE_DRAIN) / 100;
  1088. attackerState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  1089. drainedLife += toHeal;
  1090. }
  1091. //soul steal handling
  1092. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL) && def->isLiving())
  1093. {
  1094. //we can have two bonuses - one with subtype 0 and another with subtype 1
  1095. //try to use permanent first, use only one of two
  1096. for(si32 subtype = 1; subtype >= 0; subtype--)
  1097. {
  1098. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL, subtype))
  1099. {
  1100. int64_t toHeal = bsa.killedAmount * attackerState->valOfBonuses(BonusType::SOUL_STEAL, subtype) * attackerState->getMaxHealth();
  1101. attackerState->heal(toHeal, EHealLevel::OVERHEAL, ((subtype == 0) ? EHealPower::ONE_BATTLE : EHealPower::PERMANENT));
  1102. drainedLife += toHeal;
  1103. break;
  1104. }
  1105. }
  1106. }
  1107. bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
  1108. //fire shield handling
  1109. if(!bat.shot() &&
  1110. !def->isClone() &&
  1111. def->hasBonusOfType(BonusType::FIRE_SHIELD) &&
  1112. !attackerState->hasBonusOfType(BonusType::FIRE_IMMUNITY) &&
  1113. CStack::isMeleeAttackPossible(attackerState.get(), def) // attacked needs to be adjacent to defender for fire shield to trigger (e.g. Dragon Breath attack)
  1114. )
  1115. {
  1116. //TODO: use damage with bonus but without penalties
  1117. auto fireShieldDamage = (std::min<int64_t>(def->getAvailableHealth(), bsa.damageAmount) * def->valOfBonuses(BonusType::FIRE_SHIELD)) / 100;
  1118. fireShield.push_back(std::make_pair(def, fireShieldDamage));
  1119. }
  1120. return drainedLife;
  1121. }
  1122. void BattleProcessor::sendGenericKilledLog(const CStack * defender, int32_t killed, bool multiple)
  1123. {
  1124. if(killed > 0)
  1125. {
  1126. BattleLogMessage blm;
  1127. addGenericKilledLog(blm, defender, killed, multiple);
  1128. gameHandler->sendAndApply(&blm);
  1129. }
  1130. }
  1131. void BattleProcessor::addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple)
  1132. {
  1133. if(killed > 0)
  1134. {
  1135. const int32_t txtIndex = (killed > 1) ? 379 : 378;
  1136. std::string formatString = VLC->generaltexth->allTexts[txtIndex];
  1137. // these default h3 texts have unnecessary new lines, so get rid of them before displaying (and trim just in case, trimming newlines does not works for some reason)
  1138. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\n'), formatString.end());
  1139. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\r'), formatString.end());
  1140. boost::algorithm::trim(formatString);
  1141. boost::format txt(formatString);
  1142. if(killed > 1)
  1143. {
  1144. txt % killed % (multiple ? VLC->generaltexth->allTexts[43] : defender->unitType()->getNamePluralTranslated()); // creatures perish
  1145. }
  1146. else //killed == 1
  1147. {
  1148. txt % (multiple ? VLC->generaltexth->allTexts[42] : defender->unitType()->getNameSingularTranslated()); // creature perishes
  1149. }
  1150. MetaString line;
  1151. line.appendRawString(txt.str());
  1152. blm.lines.push_back(std::move(line));
  1153. }
  1154. }
  1155. void BattleProcessor::endBattle(int3 tile, const CGHeroInstance * heroAttacker, const CGHeroInstance * heroDefender)
  1156. {
  1157. LOG_TRACE(logGlobal);
  1158. //Fill BattleResult structure with exp info
  1159. giveExp(*battleResult.data);
  1160. if (battleResult.get()->result == BattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  1161. {
  1162. if(heroAttacker)
  1163. battleResult.data->exp[1] += 500;
  1164. if(heroDefender)
  1165. battleResult.data->exp[0] += 500;
  1166. }
  1167. if(heroAttacker)
  1168. battleResult.data->exp[0] = heroAttacker->calculateXp(battleResult.data->exp[0]);//scholar skill
  1169. if(heroDefender)
  1170. battleResult.data->exp[1] = heroDefender->calculateXp(battleResult.data->exp[1]);
  1171. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(gameHandler->gameState()->curB->sides[0].color));
  1172. if (!battleQuery)
  1173. {
  1174. logGlobal->error("Cannot find battle query!");
  1175. gameHandler->complain("Player " + boost::lexical_cast<std::string>(gameHandler->gameState()->curB->sides[0].color) + " has no battle query at the top!");
  1176. return;
  1177. }
  1178. battleQuery->result = std::make_optional(*battleResult.data);
  1179. //Check how many battle gameHandler->queries were created (number of players blocked by battle)
  1180. const int queriedPlayers = battleQuery ? (int)boost::count(gameHandler->queries->allQueries(), battleQuery) : 0;
  1181. finishingBattle = std::make_unique<FinishingBattleHelper>(battleQuery, queriedPlayers);
  1182. // in battles against neutrals, 1st player can ask to replay battle manually
  1183. if (!gameHandler->gameState()->curB->sides[1].color.isValidPlayer())
  1184. {
  1185. auto battleDialogQuery = std::make_shared<CBattleDialogQuery>(gameHandler, gameHandler->gameState()->curB);
  1186. battleResult.data->queryID = battleDialogQuery->queryID;
  1187. gameHandler->queries->addQuery(battleDialogQuery);
  1188. }
  1189. else
  1190. battleResult.data->queryID = -1;
  1191. //set same battle result for all gameHandler->queries
  1192. for(auto q : gameHandler->queries->allQueries())
  1193. {
  1194. auto otherBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(q);
  1195. if(otherBattleQuery)
  1196. otherBattleQuery->result = battleQuery->result;
  1197. }
  1198. gameHandler->sendAndApply(battleResult.data); //after this point casualties objects are destroyed
  1199. if (battleResult.data->queryID == -1)
  1200. endBattleConfirm(gameHandler->gameState()->curB);
  1201. }
  1202. void BattleProcessor::endBattleConfirm(const BattleInfo * battleInfo)
  1203. {
  1204. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries->topQuery(battleInfo->sides.at(0).color));
  1205. if(!battleQuery)
  1206. {
  1207. logGlobal->trace("No battle query, battle end was confirmed by another player");
  1208. return;
  1209. }
  1210. const BattleResult::EResult result = battleResult.get()->result;
  1211. CasualtiesAfterBattle cab1(battleInfo->sides.at(0), battleInfo), cab2(battleInfo->sides.at(1), battleInfo); //calculate casualties before deleting battle
  1212. ChangeSpells cs; //for Eagle Eye
  1213. if(!finishingBattle->isDraw() && finishingBattle->winnerHero)
  1214. {
  1215. if (int eagleEyeLevel = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT, -1))
  1216. {
  1217. double eagleEyeChance = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE, 0);
  1218. for(auto & spellId : battleInfo->sides.at(!battleResult.data->winner).usedSpellsHistory)
  1219. {
  1220. auto spell = spellId.toSpell(VLC->spells());
  1221. if(spell && spell->getLevel() <= eagleEyeLevel && !finishingBattle->winnerHero->spellbookContainsSpell(spell->getId()) && gameHandler->getRandomGenerator().nextInt(99) < eagleEyeChance)
  1222. cs.spells.insert(spell->getId());
  1223. }
  1224. }
  1225. }
  1226. std::vector<const CArtifactInstance *> arts; //display them in window
  1227. if(result == BattleResult::NORMAL && !finishingBattle->isDraw() && finishingBattle->winnerHero)
  1228. {
  1229. auto sendMoveArtifact = [&](const CArtifactInstance *art, MoveArtifact *ma)
  1230. {
  1231. const auto slot = ArtifactUtils::getArtAnyPosition(finishingBattle->winnerHero, art->getTypeId());
  1232. if(slot != ArtifactPosition::PRE_FIRST)
  1233. {
  1234. arts.push_back(art);
  1235. ma->dst = ArtifactLocation(finishingBattle->winnerHero, slot);
  1236. if(ArtifactUtils::isSlotBackpack(slot))
  1237. ma->askAssemble = false;
  1238. gameHandler->sendAndApply(ma);
  1239. }
  1240. };
  1241. if (finishingBattle->loserHero)
  1242. {
  1243. //TODO: wrap it into a function, somehow (std::variant -_-)
  1244. auto artifactsWorn = finishingBattle->loserHero->artifactsWorn;
  1245. for (auto artSlot : artifactsWorn)
  1246. {
  1247. MoveArtifact ma;
  1248. ma.src = ArtifactLocation(finishingBattle->loserHero, artSlot.first);
  1249. const CArtifactInstance * art = ma.src.getArt();
  1250. if (art && !art->artType->isBig() &&
  1251. art->artType->getId() != ArtifactID::SPELLBOOK)
  1252. // don't move war machines or locked arts (spellbook)
  1253. {
  1254. sendMoveArtifact(art, &ma);
  1255. }
  1256. }
  1257. for(int slotNumber = finishingBattle->loserHero->artifactsInBackpack.size() - 1; slotNumber >= 0; slotNumber--)
  1258. {
  1259. //we assume that no big artifacts can be found
  1260. MoveArtifact ma;
  1261. ma.src = ArtifactLocation(finishingBattle->loserHero,
  1262. ArtifactPosition(GameConstants::BACKPACK_START + slotNumber)); //backpack automatically shifts arts to beginning
  1263. const CArtifactInstance * art = ma.src.getArt();
  1264. if (art->artType->getId() != ArtifactID::GRAIL) //grail may not be won
  1265. {
  1266. sendMoveArtifact(art, &ma);
  1267. }
  1268. }
  1269. if (finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero?
  1270. {
  1271. artifactsWorn = finishingBattle->loserHero->commander->artifactsWorn;
  1272. for (auto artSlot : artifactsWorn)
  1273. {
  1274. MoveArtifact ma;
  1275. ma.src = ArtifactLocation(finishingBattle->loserHero->commander.get(), artSlot.first);
  1276. const CArtifactInstance * art = ma.src.getArt();
  1277. if (art && !art->artType->isBig())
  1278. {
  1279. sendMoveArtifact(art, &ma);
  1280. }
  1281. }
  1282. }
  1283. }
  1284. for (auto armySlot : battleInfo->sides.at(!battleResult.data->winner).armyObject->stacks)
  1285. {
  1286. auto artifactsWorn = armySlot.second->artifactsWorn;
  1287. for (auto artSlot : artifactsWorn)
  1288. {
  1289. MoveArtifact ma;
  1290. ma.src = ArtifactLocation(armySlot.second, artSlot.first);
  1291. const CArtifactInstance * art = ma.src.getArt();
  1292. if (art && !art->artType->isBig())
  1293. {
  1294. sendMoveArtifact(art, &ma);
  1295. }
  1296. }
  1297. }
  1298. }
  1299. if (arts.size()) //display loot
  1300. {
  1301. InfoWindow iw;
  1302. iw.player = finishingBattle->winnerHero->tempOwner;
  1303. iw.text.appendLocalString (EMetaText::GENERAL_TXT, 30); //You have captured enemy artifact
  1304. for (auto art : arts) //TODO; separate function to display loot for various ojects?
  1305. {
  1306. iw.components.emplace_back(
  1307. Component::EComponentType::ARTIFACT, art->artType->getId(),
  1308. art->artType->getId() == ArtifactID::SPELL_SCROLL? art->getScrollSpellID() : 0, 0);
  1309. if (iw.components.size() >= 14)
  1310. {
  1311. gameHandler->sendAndApply(&iw);
  1312. iw.components.clear();
  1313. }
  1314. }
  1315. if (iw.components.size())
  1316. {
  1317. gameHandler->sendAndApply(&iw);
  1318. }
  1319. }
  1320. //Eagle Eye secondary skill handling
  1321. if (!cs.spells.empty())
  1322. {
  1323. cs.learn = 1;
  1324. cs.hid = finishingBattle->winnerHero->id;
  1325. InfoWindow iw;
  1326. iw.player = finishingBattle->winnerHero->tempOwner;
  1327. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
  1328. iw.text.replaceRawString(finishingBattle->winnerHero->getNameTranslated());
  1329. std::ostringstream names;
  1330. for (int i = 0; i < cs.spells.size(); i++)
  1331. {
  1332. names << "%s";
  1333. if (i < cs.spells.size() - 2)
  1334. names << ", ";
  1335. else if (i < cs.spells.size() - 1)
  1336. names << "%s";
  1337. }
  1338. names << ".";
  1339. iw.text.replaceRawString(names.str());
  1340. auto it = cs.spells.begin();
  1341. for (int i = 0; i < cs.spells.size(); i++, it++)
  1342. {
  1343. iw.text.replaceLocalString(EMetaText::SPELL_NAME, it->toEnum());
  1344. if (i == cs.spells.size() - 2) //we just added pre-last name
  1345. iw.text.replaceLocalString(EMetaText::GENERAL_TXT, 141); // " and "
  1346. iw.components.emplace_back(Component::EComponentType::SPELL, *it, 0, 0);
  1347. }
  1348. gameHandler->sendAndApply(&iw);
  1349. gameHandler->sendAndApply(&cs);
  1350. }
  1351. cab1.updateArmy(gameHandler);
  1352. cab2.updateArmy(gameHandler); //take casualties after battle is deleted
  1353. if(finishingBattle->loserHero) //remove beaten hero
  1354. {
  1355. RemoveObject ro(finishingBattle->loserHero->id);
  1356. gameHandler->sendAndApply(&ro);
  1357. }
  1358. if(finishingBattle->isDraw() && finishingBattle->winnerHero) //for draw case both heroes should be removed
  1359. {
  1360. RemoveObject ro(finishingBattle->winnerHero->id);
  1361. gameHandler->sendAndApply(&ro);
  1362. }
  1363. if(battleResult.data->winner == BattleSide::DEFENDER
  1364. && finishingBattle->winnerHero
  1365. && finishingBattle->winnerHero->visitedTown
  1366. && !finishingBattle->winnerHero->inTownGarrison
  1367. && finishingBattle->winnerHero->visitedTown->garrisonHero == finishingBattle->winnerHero)
  1368. {
  1369. gameHandler->swapGarrisonOnSiege(finishingBattle->winnerHero->visitedTown->id); //return defending visitor from garrison to its rightful place
  1370. }
  1371. //give exp
  1372. if(!finishingBattle->isDraw() && battleResult.data->exp[finishingBattle->winnerSide] && finishingBattle->winnerHero)
  1373. gameHandler->changePrimSkill(finishingBattle->winnerHero, PrimarySkill::EXPERIENCE, battleResult.data->exp[finishingBattle->winnerSide]);
  1374. BattleResultAccepted raccepted;
  1375. raccepted.heroResult[0].army = const_cast<CArmedInstance*>(battleInfo->sides.at(0).armyObject);
  1376. raccepted.heroResult[1].army = const_cast<CArmedInstance*>(battleInfo->sides.at(1).armyObject);
  1377. raccepted.heroResult[0].hero = const_cast<CGHeroInstance*>(battleInfo->sides.at(0).hero);
  1378. raccepted.heroResult[1].hero = const_cast<CGHeroInstance*>(battleInfo->sides.at(1).hero);
  1379. raccepted.heroResult[0].exp = battleResult.data->exp[0];
  1380. raccepted.heroResult[1].exp = battleResult.data->exp[1];
  1381. raccepted.winnerSide = finishingBattle->winnerSide;
  1382. gameHandler->sendAndApply(&raccepted);
  1383. gameHandler->queries->popIfTop(battleQuery);
  1384. //--> continuation (battleAfterLevelUp) occurs after level-up gameHandler->queries are handled or on removing query
  1385. }
  1386. void BattleProcessor::battleAfterLevelUp(const BattleResult &result)
  1387. {
  1388. LOG_TRACE(logGlobal);
  1389. if(!finishingBattle)
  1390. return;
  1391. finishingBattle->remainingBattleQueriesCount--;
  1392. logGlobal->trace("Decremented gameHandler->queries count to %d", finishingBattle->remainingBattleQueriesCount);
  1393. if (finishingBattle->remainingBattleQueriesCount > 0)
  1394. //Battle results will be handled when all battle gameHandler->queries are closed
  1395. return;
  1396. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  1397. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  1398. // Still, it looks like a hole.
  1399. // Necromancy if applicable.
  1400. const CStackBasicDescriptor raisedStack = finishingBattle->winnerHero ? finishingBattle->winnerHero->calculateNecromancy(*battleResult.data) : CStackBasicDescriptor();
  1401. // Give raised units to winner and show dialog, if any were raised,
  1402. // units will be given after casualties are taken
  1403. const SlotID necroSlot = raisedStack.type ? finishingBattle->winnerHero->getSlotFor(raisedStack.type) : SlotID();
  1404. if (necroSlot != SlotID())
  1405. {
  1406. finishingBattle->winnerHero->showNecromancyDialog(raisedStack, gameHandler->getRandomGenerator());
  1407. gameHandler->addToSlot(StackLocation(finishingBattle->winnerHero, necroSlot), raisedStack.type, raisedStack.count);
  1408. }
  1409. BattleResultsApplied resultsApplied;
  1410. resultsApplied.player1 = finishingBattle->victor;
  1411. resultsApplied.player2 = finishingBattle->loser;
  1412. gameHandler->sendAndApply(&resultsApplied);
  1413. gameHandler->setBattle(nullptr);
  1414. if (visitObjectAfterVictory && result.winner==0 && !finishingBattle->winnerHero->stacks.empty())
  1415. {
  1416. logGlobal->trace("post-victory visit");
  1417. gameHandler->visitObjectOnTile(*gameHandler->getTile(finishingBattle->winnerHero->visitablePos()), finishingBattle->winnerHero);
  1418. }
  1419. visitObjectAfterVictory = false;
  1420. //handle victory/loss of engaged players
  1421. std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
  1422. gameHandler->checkVictoryLossConditions(playerColors);
  1423. if (result.result == BattleResult::SURRENDER)
  1424. gameHandler->heroPool->onHeroSurrendered(finishingBattle->loser, finishingBattle->loserHero);
  1425. if (result.result == BattleResult::ESCAPE)
  1426. gameHandler->heroPool->onHeroEscaped(finishingBattle->loser, finishingBattle->loserHero);
  1427. if (result.winner != 2 && finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()
  1428. && (!finishingBattle->winnerHero->commander || !finishingBattle->winnerHero->commander->alive))
  1429. {
  1430. RemoveObject ro(finishingBattle->winnerHero->id);
  1431. gameHandler->sendAndApply(&ro);
  1432. if (VLC->settings()->getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  1433. gameHandler->heroPool->onHeroEscaped(finishingBattle->victor, finishingBattle->winnerHero);
  1434. }
  1435. finishingBattle.reset();
  1436. }
  1437. int BattleProcessor::moveStack(int stack, BattleHex dest)
  1438. {
  1439. int ret = 0;
  1440. const CStack *curStack = gameHandler->battleGetStackByID(stack),
  1441. *stackAtEnd = gameHandler->gameState()->curB->battleGetStackByPos(dest);
  1442. assert(curStack);
  1443. assert(dest < GameConstants::BFIELD_SIZE);
  1444. if (gameHandler->gameState()->curB->tacticDistance)
  1445. {
  1446. assert(gameHandler->gameState()->curB->isInTacticRange(dest));
  1447. }
  1448. auto start = curStack->getPosition();
  1449. if (start == dest)
  1450. return 0;
  1451. //initing necessary tables
  1452. auto accessibility = gameHandler->getAccesibility(curStack);
  1453. std::set<BattleHex> passed;
  1454. //Ignore obstacles on starting position
  1455. passed.insert(curStack->getPosition());
  1456. if(curStack->doubleWide())
  1457. passed.insert(curStack->occupiedHex());
  1458. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  1459. if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
  1460. {
  1461. BattleHex shifted = dest.cloneInDirection(curStack->destShiftDir(), false);
  1462. if(accessibility.accessible(shifted, curStack))
  1463. dest = shifted;
  1464. }
  1465. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
  1466. {
  1467. gameHandler->complain("Given destination is not accessible!");
  1468. return 0;
  1469. }
  1470. bool canUseGate = false;
  1471. auto dbState = gameHandler->gameState()->curB->si.gateState;
  1472. if(gameHandler->battleGetSiegeLevel() > 0 && curStack->unitSide() == BattleSide::DEFENDER &&
  1473. dbState != EGateState::DESTROYED &&
  1474. dbState != EGateState::BLOCKED)
  1475. {
  1476. canUseGate = true;
  1477. }
  1478. std::pair< std::vector<BattleHex>, int > path = gameHandler->gameState()->curB->getPath(start, dest, curStack);
  1479. ret = path.second;
  1480. int creSpeed = curStack->speed(0, true);
  1481. if (gameHandler->gameState()->curB->tacticDistance > 0 && creSpeed > 0)
  1482. creSpeed = GameConstants::BFIELD_SIZE;
  1483. bool hasWideMoat = vstd::contains_if(gameHandler->battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  1484. {
  1485. return obst->obstacleType == CObstacleInstance::MOAT;
  1486. });
  1487. auto isGateDrawbridgeHex = [&](BattleHex hex) -> bool
  1488. {
  1489. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  1490. return true;
  1491. if (hex == ESiegeHex::GATE_OUTER)
  1492. return true;
  1493. if (hex == ESiegeHex::GATE_INNER)
  1494. return true;
  1495. return false;
  1496. };
  1497. auto occupyGateDrawbridgeHex = [&](BattleHex hex) -> bool
  1498. {
  1499. if (isGateDrawbridgeHex(hex))
  1500. return true;
  1501. if (curStack->doubleWide())
  1502. {
  1503. BattleHex otherHex = curStack->occupiedHex(hex);
  1504. if (otherHex.isValid() && isGateDrawbridgeHex(otherHex))
  1505. return true;
  1506. }
  1507. return false;
  1508. };
  1509. if (curStack->hasBonusOfType(BonusType::FLYING))
  1510. {
  1511. if (path.second <= creSpeed && path.first.size() > 0)
  1512. {
  1513. if (canUseGate && dbState != EGateState::OPENED &&
  1514. occupyGateDrawbridgeHex(dest))
  1515. {
  1516. BattleUpdateGateState db;
  1517. db.state = EGateState::OPENED;
  1518. gameHandler->sendAndApply(&db);
  1519. }
  1520. //inform clients about move
  1521. BattleStackMoved sm;
  1522. sm.stack = curStack->unitId();
  1523. std::vector<BattleHex> tiles;
  1524. tiles.push_back(path.first[0]);
  1525. sm.tilesToMove = tiles;
  1526. sm.distance = path.second;
  1527. sm.teleporting = false;
  1528. gameHandler->sendAndApply(&sm);
  1529. }
  1530. }
  1531. else //for non-flying creatures
  1532. {
  1533. std::vector<BattleHex> tiles;
  1534. const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0);
  1535. int v = (int)path.first.size()-1;
  1536. path.first.push_back(start);
  1537. // check if gate need to be open or closed at some point
  1538. BattleHex openGateAtHex, gateMayCloseAtHex;
  1539. if (canUseGate)
  1540. {
  1541. for (int i = (int)path.first.size()-1; i >= 0; i--)
  1542. {
  1543. auto needOpenGates = [&](BattleHex hex) -> bool
  1544. {
  1545. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  1546. return true;
  1547. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] == ESiegeHex::GATE_OUTER)
  1548. return true;
  1549. else if (hex == ESiegeHex::GATE_OUTER || hex == ESiegeHex::GATE_INNER)
  1550. return true;
  1551. return false;
  1552. };
  1553. auto hex = path.first[i];
  1554. if (!openGateAtHex.isValid() && dbState != EGateState::OPENED)
  1555. {
  1556. if (needOpenGates(hex))
  1557. openGateAtHex = path.first[i+1];
  1558. //TODO we need find batter way to handle double-wide stacks
  1559. //currently if only second occupied stack part is standing on gate / bridge hex then stack will start to wait for bridge to lower before it's needed. Though this is just a visual bug.
  1560. if (curStack->doubleWide())
  1561. {
  1562. BattleHex otherHex = curStack->occupiedHex(hex);
  1563. if (otherHex.isValid() && needOpenGates(otherHex))
  1564. openGateAtHex = path.first[i+2];
  1565. }
  1566. //gate may be opened and then closed during stack movement, but not other way around
  1567. if (openGateAtHex.isValid())
  1568. dbState = EGateState::OPENED;
  1569. }
  1570. if (!gateMayCloseAtHex.isValid() && dbState != EGateState::CLOSED)
  1571. {
  1572. if (hex == ESiegeHex::GATE_INNER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  1573. {
  1574. gateMayCloseAtHex = path.first[i-1];
  1575. }
  1576. if (hasWideMoat)
  1577. {
  1578. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  1579. {
  1580. gateMayCloseAtHex = path.first[i-1];
  1581. }
  1582. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 &&
  1583. path.first[i-1] != ESiegeHex::GATE_INNER &&
  1584. path.first[i-1] != ESiegeHex::GATE_BRIDGE)
  1585. {
  1586. gateMayCloseAtHex = path.first[i-1];
  1587. }
  1588. }
  1589. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_INNER)
  1590. {
  1591. gateMayCloseAtHex = path.first[i-1];
  1592. }
  1593. }
  1594. }
  1595. }
  1596. bool stackIsMoving = true;
  1597. while(stackIsMoving)
  1598. {
  1599. if (v<tilesToMove)
  1600. {
  1601. logGlobal->error("Movement terminated abnormally");
  1602. break;
  1603. }
  1604. bool gateStateChanging = false;
  1605. //special handling for opening gate on from starting hex
  1606. if (openGateAtHex.isValid() && openGateAtHex == start)
  1607. gateStateChanging = true;
  1608. else
  1609. {
  1610. for (bool obstacleHit = false; (!obstacleHit) && (!gateStateChanging) && (v >= tilesToMove); --v)
  1611. {
  1612. BattleHex hex = path.first[v];
  1613. tiles.push_back(hex);
  1614. if ((openGateAtHex.isValid() && openGateAtHex == hex) ||
  1615. (gateMayCloseAtHex.isValid() && gateMayCloseAtHex == hex))
  1616. {
  1617. gateStateChanging = true;
  1618. }
  1619. //if we walked onto something, finalize this portion of stack movement check into obstacle
  1620. if(!gameHandler->battleGetAllObstaclesOnPos(hex, false).empty())
  1621. obstacleHit = true;
  1622. if (curStack->doubleWide())
  1623. {
  1624. BattleHex otherHex = curStack->occupiedHex(hex);
  1625. //two hex creature hit obstacle by backside
  1626. auto obstacle2 = gameHandler->battleGetAllObstaclesOnPos(otherHex, false);
  1627. if(otherHex.isValid() && !obstacle2.empty())
  1628. obstacleHit = true;
  1629. }
  1630. if(!obstacleHit)
  1631. passed.insert(hex);
  1632. }
  1633. }
  1634. if (!tiles.empty())
  1635. {
  1636. //commit movement
  1637. BattleStackMoved sm;
  1638. sm.stack = curStack->unitId();
  1639. sm.distance = path.second;
  1640. sm.teleporting = false;
  1641. sm.tilesToMove = tiles;
  1642. gameHandler->sendAndApply(&sm);
  1643. tiles.clear();
  1644. }
  1645. //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end
  1646. if (curStack->getPosition() != dest)
  1647. {
  1648. if(stackIsMoving && start != curStack->getPosition())
  1649. {
  1650. stackIsMoving = gameHandler->handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  1651. passed.insert(curStack->getPosition());
  1652. if(curStack->doubleWide())
  1653. passed.insert(curStack->occupiedHex());
  1654. }
  1655. if (gateStateChanging)
  1656. {
  1657. if (curStack->getPosition() == openGateAtHex)
  1658. {
  1659. openGateAtHex = BattleHex();
  1660. //only open gate if stack is still alive
  1661. if (curStack->alive())
  1662. {
  1663. BattleUpdateGateState db;
  1664. db.state = EGateState::OPENED;
  1665. gameHandler->sendAndApply(&db);
  1666. }
  1667. }
  1668. else if (curStack->getPosition() == gateMayCloseAtHex)
  1669. {
  1670. gateMayCloseAtHex = BattleHex();
  1671. updateGateState();
  1672. }
  1673. }
  1674. }
  1675. else
  1676. //movement finished normally: we reached destination
  1677. stackIsMoving = false;
  1678. }
  1679. }
  1680. //handle last hex separately for deviation
  1681. if (VLC->settings()->getBoolean(EGameSettings::COMBAT_ONE_HEX_TRIGGERS_OBSTACLES))
  1682. {
  1683. if (dest == battle::Unit::occupiedHex(start, curStack->doubleWide(), curStack->unitSide())
  1684. || start == battle::Unit::occupiedHex(dest, curStack->doubleWide(), curStack->unitSide()))
  1685. passed.clear(); //Just empty passed, obstacles will handled automatically
  1686. }
  1687. //handling obstacle on the final field (separate, because it affects both flying and walking stacks)
  1688. gameHandler->handleObstacleTriggersForUnit(*gameHandler->spellEnv, *curStack, passed);
  1689. return ret;
  1690. }
  1691. void BattleProcessor::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town)
  1692. {
  1693. battleResult.set(nullptr);
  1694. const auto & t = *gameHandler->getTile(tile);
  1695. TerrainId terrain = t.terType->getId();
  1696. if (gameHandler->gameState()->map->isCoastalTile(tile)) //coastal tile is always ground
  1697. terrain = ETerrainId::SAND;
  1698. BattleField terType = gameHandler->gameState()->battleGetBattlefieldType(tile, gameHandler->getRandomGenerator());
  1699. if (heroes[0] && heroes[0]->boat && heroes[1] && heroes[1]->boat)
  1700. terType = BattleField(*VLC->identifiers()->getIdentifier("core", "battlefield.ship_to_ship"));
  1701. //send info about battles
  1702. BattleStart bs;
  1703. bs.info = BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  1704. engageIntoBattle(bs.info->sides[0].color);
  1705. engageIntoBattle(bs.info->sides[1].color);
  1706. auto lastBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(gameHandler->queries.topQuery(bs.info->sides[0].color));
  1707. bs.info->replayAllowed = lastBattleQuery == nullptr && !bs.info->sides[1].color.isValidPlayer();
  1708. gameHandler->sendAndApply(&bs);
  1709. }
  1710. void BattleProcessor::checkBattleStateChanges()
  1711. {
  1712. //check if drawbridge state need to be changes
  1713. if (gameHandler->battleGetSiegeLevel() > 0)
  1714. updateGateState();
  1715. //check if battle ended
  1716. if (auto result = gameHandler->battleIsFinished())
  1717. {
  1718. setBattleResult(BattleResult::NORMAL, *result);
  1719. }
  1720. }
  1721. bool BattleProcessor::makeBattleAction(BattleAction &ba)
  1722. {
  1723. bool ok = true;
  1724. battle::Target target = ba.getTarget(gameHandler->gameState()->curB);
  1725. const CStack * stack = gameHandler->battleGetStackByID(ba.stackNumber); //may be nullptr if action is not about stack
  1726. const bool isAboutActiveStack = stack && (ba.stackNumber == gameHandler->gameState()->curB->getActiveStackID());
  1727. logGlobal->trace("Making action: %s", ba.toString());
  1728. switch(ba.actionType)
  1729. {
  1730. case EActionType::WALK: //walk
  1731. case EActionType::DEFEND: //defend
  1732. case EActionType::WAIT: //wait
  1733. case EActionType::WALK_AND_ATTACK: //walk or attack
  1734. case EActionType::SHOOT: //shoot
  1735. case EActionType::CATAPULT: //catapult
  1736. case EActionType::STACK_HEAL: //healing with First Aid Tent
  1737. case EActionType::MONSTER_SPELL:
  1738. if (!stack)
  1739. {
  1740. gameHandler->complain("No such stack!");
  1741. return false;
  1742. }
  1743. if (!stack->alive())
  1744. {
  1745. gameHandler->complain("This stack is dead: " + stack->nodeName());
  1746. return false;
  1747. }
  1748. if (gameHandler->battleTacticDist())
  1749. {
  1750. if (stack && stack->unitSide() != gameHandler->battleGetTacticsSide())
  1751. {
  1752. gameHandler->complain("This is not a stack of side that has tactics!");
  1753. return false;
  1754. }
  1755. }
  1756. else if (!isAboutActiveStack)
  1757. {
  1758. gameHandler->complain("Action has to be about active stack!");
  1759. return false;
  1760. }
  1761. }
  1762. auto wrapAction = [this](BattleAction &ba)
  1763. {
  1764. StartAction startAction(ba);
  1765. gameHandler->sendAndApply(&startAction);
  1766. return vstd::makeScopeGuard([&]()
  1767. {
  1768. gameHandler->sendAndApply(&end_action);
  1769. });
  1770. };
  1771. switch(ba.actionType)
  1772. {
  1773. case EActionType::END_TACTIC_PHASE: //wait
  1774. case EActionType::BAD_MORALE:
  1775. case EActionType::NO_ACTION:
  1776. {
  1777. auto wrapper = wrapAction(ba);
  1778. break;
  1779. }
  1780. case EActionType::WALK:
  1781. {
  1782. auto wrapper = wrapAction(ba);
  1783. if(target.size() < 1)
  1784. {
  1785. gameHandler->complain("Destination required for move action.");
  1786. ok = false;
  1787. break;
  1788. }
  1789. int walkedTiles = moveStack(ba.stackNumber, target.at(0).hexValue); //move
  1790. if (!walkedTiles)
  1791. gameHandler->complain("Stack failed movement!");
  1792. break;
  1793. }
  1794. case EActionType::DEFEND:
  1795. {
  1796. //defensive stance, TODO: filter out spell boosts from bonus (stone skin etc.)
  1797. SetStackEffect sse;
  1798. Bonus defenseBonusToAdd(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 20, -1, PrimarySkill::DEFENSE, BonusValueType::PERCENT_TO_ALL);
  1799. Bonus bonus2(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, stack->valOfBonuses(BonusType::DEFENSIVE_STANCE),
  1800. -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  1801. Bonus alternativeWeakCreatureBonus(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 1, -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  1802. BonusList defence = *stack->getBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, PrimarySkill::DEFENSE));
  1803. int oldDefenceValue = defence.totalValue();
  1804. defence.push_back(std::make_shared<Bonus>(defenseBonusToAdd));
  1805. defence.push_back(std::make_shared<Bonus>(bonus2));
  1806. int difference = defence.totalValue() - oldDefenceValue;
  1807. std::vector<Bonus> buffer;
  1808. if(difference == 0) //give replacement bonus for creatures not reaching 5 defense points (20% of def becomes 0)
  1809. {
  1810. difference = 1;
  1811. buffer.push_back(alternativeWeakCreatureBonus);
  1812. }
  1813. else
  1814. {
  1815. buffer.push_back(defenseBonusToAdd);
  1816. }
  1817. buffer.push_back(bonus2);
  1818. sse.toUpdate.push_back(std::make_pair(ba.stackNumber, buffer));
  1819. gameHandler->sendAndApply(&sse);
  1820. BattleLogMessage message;
  1821. MetaString text;
  1822. stack->addText(text, EMetaText::GENERAL_TXT, 120);
  1823. stack->addNameReplacement(text);
  1824. text.replaceNumber(difference);
  1825. message.lines.push_back(text);
  1826. gameHandler->sendAndApply(&message);
  1827. //don't break - we share code with next case
  1828. }
  1829. [[fallthrough]];
  1830. case EActionType::WAIT:
  1831. {
  1832. auto wrapper = wrapAction(ba);
  1833. break;
  1834. }
  1835. case EActionType::RETREAT: //retreat/flee
  1836. {
  1837. if (!gameHandler->gameState()->curB->battleCanFlee(gameHandler->gameState()->curB->sides.at(ba.side).color))
  1838. gameHandler->complain("Cannot retreat!");
  1839. else
  1840. setBattleResult(BattleResult::ESCAPE, !ba.side); //surrendering side loses
  1841. break;
  1842. }
  1843. case EActionType::SURRENDER:
  1844. {
  1845. PlayerColor player = gameHandler->gameState()->curB->sides.at(ba.side).color;
  1846. int cost = gameHandler->gameState()->curB->battleGetSurrenderCost(player);
  1847. if (cost < 0)
  1848. gameHandler->complain("Cannot surrender!");
  1849. else if (gameHandler->getResource(player, EGameResID::GOLD) < cost)
  1850. gameHandler->complain("Not enough gold to surrender!");
  1851. else
  1852. {
  1853. gameHandler->giveResource(player, EGameResID::GOLD, -cost);
  1854. setBattleResult(BattleResult::SURRENDER, !ba.side); //surrendering side loses
  1855. }
  1856. break;
  1857. }
  1858. case EActionType::WALK_AND_ATTACK: //walk or attack
  1859. {
  1860. auto wrapper = wrapAction(ba);
  1861. if(!stack)
  1862. {
  1863. gameHandler->complain("No attacker");
  1864. ok = false;
  1865. break;
  1866. }
  1867. if(target.size() < 2)
  1868. {
  1869. gameHandler->complain("Two destinations required for attack action.");
  1870. ok = false;
  1871. break;
  1872. }
  1873. BattleHex attackPos = target.at(0).hexValue;
  1874. BattleHex destinationTile = target.at(1).hexValue;
  1875. const CStack * destinationStack = gameHandler->gameState()->curB->battleGetStackByPos(destinationTile, true);
  1876. if(!destinationStack)
  1877. {
  1878. gameHandler->complain("Invalid target to attack");
  1879. ok = false;
  1880. break;
  1881. }
  1882. BattleHex startingPos = stack->getPosition();
  1883. int distance = moveStack(ba.stackNumber, attackPos);
  1884. logGlobal->trace("%s will attack %s", stack->nodeName(), destinationStack->nodeName());
  1885. if(stack->getPosition() != attackPos
  1886. && !(stack->doubleWide() && (stack->getPosition() == attackPos.cloneInDirection(stack->destShiftDir(), false)))
  1887. )
  1888. {
  1889. // we were not able to reach destination tile, nor occupy specified hex
  1890. // abort attack attempt, but treat this case as legal - we may have stepped onto a quicksands/mine
  1891. break;
  1892. }
  1893. if(destinationStack && stack->unitId() == destinationStack->unitId()) //we should just move, it will be handled by following check
  1894. {
  1895. destinationStack = nullptr;
  1896. }
  1897. if(!destinationStack)
  1898. {
  1899. gameHandler->complain("Unit can not attack itself");
  1900. ok = false;
  1901. break;
  1902. }
  1903. if(!CStack::isMeleeAttackPossible(stack, destinationStack))
  1904. {
  1905. gameHandler->complain("Attack cannot be performed!");
  1906. ok = false;
  1907. break;
  1908. }
  1909. //attack
  1910. int totalAttacks = stack->totalAttacks.getMeleeValue();
  1911. //TODO: move to CUnitState
  1912. const auto * attackingHero = gameHandler->gameState()->curB->battleGetFightingHero(ba.side);
  1913. if(attackingHero)
  1914. {
  1915. totalAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, stack->creatureIndex());
  1916. }
  1917. const bool firstStrike = destinationStack->hasBonusOfType(BonusType::FIRST_STRIKE);
  1918. const bool retaliation = destinationStack->ableToRetaliate();
  1919. for (int i = 0; i < totalAttacks; ++i)
  1920. {
  1921. //first strike
  1922. if(i == 0 && firstStrike && retaliation)
  1923. {
  1924. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, false, true);
  1925. }
  1926. //move can cause death, eg. by walking into the moat, first strike can cause death or paralysis/petrification
  1927. if(stack->alive() && !stack->hasBonusOfType(BonusType::NOT_ACTIVE) && destinationStack->alive())
  1928. {
  1929. makeAttack(stack, destinationStack, (i ? 0 : distance), destinationTile, i==0, false, false);//no distance travelled on second attack
  1930. }
  1931. //counterattack
  1932. //we check retaliation twice, so if it unblocked during attack it will work only on next attack
  1933. if(stack->alive()
  1934. && !stack->hasBonusOfType(BonusType::BLOCKS_RETALIATION)
  1935. && (i == 0 && !firstStrike)
  1936. && retaliation && destinationStack->ableToRetaliate())
  1937. {
  1938. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, false, true);
  1939. }
  1940. }
  1941. //return
  1942. if(stack->hasBonusOfType(BonusType::RETURN_AFTER_STRIKE)
  1943. && target.size() == 3
  1944. && startingPos != stack->getPosition()
  1945. && startingPos == target.at(2).hexValue
  1946. && stack->alive())
  1947. {
  1948. moveStack(ba.stackNumber, startingPos);
  1949. //NOTE: curStack->unitId() == ba.stackNumber (rev 1431)
  1950. }
  1951. break;
  1952. }
  1953. case EActionType::SHOOT:
  1954. {
  1955. if(target.size() < 1)
  1956. {
  1957. gameHandler->complain("Destination required for shot action.");
  1958. ok = false;
  1959. break;
  1960. }
  1961. auto destination = target.at(0).hexValue;
  1962. const CStack * destinationStack = gameHandler->gameState()->curB->battleGetStackByPos(destination);
  1963. if (!gameHandler->gameState()->curB->battleCanShoot(stack, destination))
  1964. {
  1965. gameHandler->complain("Cannot shoot!");
  1966. break;
  1967. }
  1968. if (!destinationStack)
  1969. {
  1970. gameHandler->complain("No target to shoot!");
  1971. break;
  1972. }
  1973. auto wrapper = wrapAction(ba);
  1974. makeAttack(stack, destinationStack, 0, destination, true, true, false);
  1975. //ranged counterattack
  1976. if (destinationStack->hasBonusOfType(BonusType::RANGED_RETALIATION)
  1977. && !stack->hasBonusOfType(BonusType::BLOCKS_RANGED_RETALIATION)
  1978. && destinationStack->ableToRetaliate()
  1979. && gameHandler->gameState()->curB->battleCanShoot(destinationStack, stack->getPosition())
  1980. && stack->alive()) //attacker may have died (fire shield)
  1981. {
  1982. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, true, true);
  1983. }
  1984. //allow more than one additional attack
  1985. int totalRangedAttacks = stack->totalAttacks.getRangedValue();
  1986. //TODO: move to CUnitState
  1987. const auto * attackingHero = gameHandler->gameState()->curB->battleGetFightingHero(ba.side);
  1988. if(attackingHero)
  1989. {
  1990. totalRangedAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, stack->creatureIndex());
  1991. }
  1992. for(int i = 1; i < totalRangedAttacks; ++i)
  1993. {
  1994. if(
  1995. stack->alive()
  1996. && destinationStack->alive()
  1997. && stack->shots.canUse()
  1998. )
  1999. {
  2000. makeAttack(stack, destinationStack, 0, destination, false, true, false);
  2001. }
  2002. }
  2003. break;
  2004. }
  2005. case EActionType::CATAPULT:
  2006. {
  2007. auto wrapper = wrapAction(ba);
  2008. const CStack * shooter = gameHandler->gameState()->curB->battleGetStackByID(ba.stackNumber);
  2009. std::shared_ptr<const Bonus> catapultAbility = stack->getBonusLocalFirst(Selector::type()(BonusType::CATAPULT));
  2010. if(!catapultAbility || catapultAbility->subtype < 0)
  2011. {
  2012. gameHandler->complain("We do not know how to shoot :P");
  2013. }
  2014. else
  2015. {
  2016. const CSpell * spell = SpellID(catapultAbility->subtype).toSpell();
  2017. spells::BattleCast parameters(gameHandler->gameState()->curB, shooter, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can shot infinitely by catapult
  2018. auto shotLevel = stack->valOfBonuses(Selector::typeSubtype(BonusType::CATAPULT_EXTRA_SHOTS, catapultAbility->subtype));
  2019. parameters.setSpellLevel(shotLevel);
  2020. parameters.cast(gameHandler->spellEnv, target);
  2021. }
  2022. //finish by scope guard
  2023. break;
  2024. }
  2025. case EActionType::STACK_HEAL: //healing with First Aid Tent
  2026. {
  2027. auto wrapper = wrapAction(ba);
  2028. const CStack * healer = gameHandler->gameState()->curB->battleGetStackByID(ba.stackNumber);
  2029. if(target.size() < 1)
  2030. {
  2031. gameHandler->complain("Destination required for heal action.");
  2032. ok = false;
  2033. break;
  2034. }
  2035. const battle::Unit * destStack = nullptr;
  2036. std::shared_ptr<const Bonus> healerAbility = stack->getBonusLocalFirst(Selector::type()(BonusType::HEALER));
  2037. if(target.at(0).unitValue)
  2038. destStack = target.at(0).unitValue;
  2039. else
  2040. destStack = gameHandler->gameState()->curB->battleGetUnitByPos(target.at(0).hexValue);
  2041. if(healer == nullptr || destStack == nullptr || !healerAbility || healerAbility->subtype < 0)
  2042. {
  2043. gameHandler->complain("There is either no healer, no destination, or healer cannot heal :P");
  2044. }
  2045. else
  2046. {
  2047. const CSpell * spell = SpellID(healerAbility->subtype).toSpell();
  2048. spells::BattleCast parameters(gameHandler->gameState()->curB, healer, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can heal infinitely by first aid tent
  2049. auto dest = battle::Destination(destStack, target.at(0).hexValue);
  2050. parameters.setSpellLevel(0);
  2051. parameters.cast(gameHandler->spellEnv, {dest});
  2052. }
  2053. break;
  2054. }
  2055. case EActionType::MONSTER_SPELL:
  2056. {
  2057. auto wrapper = wrapAction(ba);
  2058. const CStack * stack = gameHandler->gameState()->curB->battleGetStackByID(ba.stackNumber);
  2059. SpellID spellID = SpellID(ba.actionSubtype);
  2060. std::shared_ptr<const Bonus> randSpellcaster = stack->getBonus(Selector::type()(BonusType::RANDOM_SPELLCASTER));
  2061. std::shared_ptr<const Bonus> spellcaster = stack->getBonus(Selector::typeSubtype(BonusType::SPELLCASTER, spellID));
  2062. //TODO special bonus for genies ability
  2063. if (randSpellcaster && gameHandler->battleGetRandomStackSpell(gameHandler->getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_AIMED) < 0)
  2064. spellID = gameHandler->battleGetRandomStackSpell(gameHandler->getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_GENIE);
  2065. if (spellID < 0)
  2066. gameHandler->complain("That stack can't cast spells!");
  2067. else
  2068. {
  2069. const CSpell * spell = SpellID(spellID).toSpell();
  2070. spells::BattleCast parameters(gameHandler->gameState()->curB, stack, spells::Mode::CREATURE_ACTIVE, spell);
  2071. int32_t spellLvl = 0;
  2072. if(spellcaster)
  2073. vstd::amax(spellLvl, spellcaster->val);
  2074. if(randSpellcaster)
  2075. vstd::amax(spellLvl, randSpellcaster->val);
  2076. parameters.setSpellLevel(spellLvl);
  2077. parameters.cast(gameHandler->spellEnv, target);
  2078. }
  2079. break;
  2080. }
  2081. }
  2082. if(ba.actionType == EActionType::WAIT || ba.actionType == EActionType::DEFEND
  2083. || ba.actionType == EActionType::SHOOT || ba.actionType == EActionType::MONSTER_SPELL)
  2084. gameHandler->handleObstacleTriggersForUnit(*gameHandler->spellEnv, *stack);
  2085. if(ba.stackNumber == gameHandler->gameState()->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  2086. battleMadeAction.setn(true);
  2087. return ok;
  2088. }
  2089. bool BattleProcessor::makeCustomAction(BattleAction & ba)
  2090. {
  2091. switch(ba.actionType)
  2092. {
  2093. case EActionType::HERO_SPELL:
  2094. {
  2095. COMPLAIN_RET_FALSE_IF(ba.side > 1, "Side must be 0 or 1!");
  2096. const CGHeroInstance *h = gameHandler->gameState()->curB->battleGetFightingHero(ba.side);
  2097. COMPLAIN_RET_FALSE_IF((!h), "Wrong caster!");
  2098. const CSpell * s = SpellID(ba.actionSubtype).toSpell();
  2099. if (!s)
  2100. {
  2101. logGlobal->error("Wrong spell id (%d)!", ba.actionSubtype);
  2102. return false;
  2103. }
  2104. spells::BattleCast parameters(gameHandler->gameState()->curB, h, spells::Mode::HERO, s);
  2105. spells::detail::ProblemImpl problem;
  2106. auto m = s->battleMechanics(&parameters);
  2107. if(!m->canBeCast(problem))//todo: should we check aimed cast?
  2108. {
  2109. logGlobal->warn("Spell cannot be cast!");
  2110. std::vector<std::string> texts;
  2111. problem.getAll(texts);
  2112. for(auto s : texts)
  2113. logGlobal->warn(s);
  2114. return false;
  2115. }
  2116. StartAction start_action(ba);
  2117. gameHandler->sendAndApply(&start_action); //start spell casting
  2118. parameters.cast(gameHandler->spellEnv, ba.getTarget(gameHandler->gameState()->curB));
  2119. gameHandler->sendAndApply(&end_action);
  2120. if (!gameHandler->gameState()->curB->battleGetStackByID(gameHandler->gameState()->curB->activeStack))
  2121. {
  2122. battleMadeAction.setn(true);
  2123. }
  2124. checkBattleStateChanges();
  2125. if (battleResult.get())
  2126. {
  2127. battleMadeAction.setn(true);
  2128. //battle will be ended by startBattle function
  2129. //endBattle(gameHandler->gameState()->curB->tile, gameHandler->gameState()->curB->heroes[0], gameHandler->gameState()->curB->heroes[1]);
  2130. }
  2131. return true;
  2132. }
  2133. }
  2134. return false;
  2135. }
  2136. void BattleProcessor::stackEnchantedTrigger(const CStack * st)
  2137. {
  2138. auto bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTED)));
  2139. for(auto b : bl)
  2140. {
  2141. const CSpell * sp = SpellID(b->subtype).toSpell();
  2142. if(!sp)
  2143. continue;
  2144. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  2145. const int32_t level = ((val > 3) ? (val - 3) : val);
  2146. spells::BattleCast battleCast(gameHandler->gameState()->curB, st, spells::Mode::PASSIVE, sp);
  2147. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  2148. battleCast.setEffectDuration(50);
  2149. battleCast.setSpellLevel(level);
  2150. spells::Target target;
  2151. if(val > 3)
  2152. {
  2153. for(auto s : gameHandler->gameState()->curB->battleGetAllStacks())
  2154. if(gameHandler->battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  2155. target.emplace_back(s);
  2156. }
  2157. else
  2158. {
  2159. target.emplace_back(st);
  2160. }
  2161. battleCast.applyEffects(gameHandler->spellEnv, target, false, true);
  2162. }
  2163. }
  2164. void BattleProcessor::stackTurnTrigger(const CStack *st)
  2165. {
  2166. BattleTriggerEffect bte;
  2167. bte.stackID = st->unitId();
  2168. bte.effect = -1;
  2169. bte.val = 0;
  2170. bte.additionalInfo = 0;
  2171. if (st->alive())
  2172. {
  2173. //unbind
  2174. if (st->hasBonus(Selector::type()(BonusType::BIND_EFFECT)))
  2175. {
  2176. bool unbind = true;
  2177. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::BIND_EFFECT)));
  2178. auto adjacent = gameHandler->gameState()->curB->battleAdjacentUnits(st);
  2179. for (auto b : bl)
  2180. {
  2181. if(b->additionalInfo != CAddInfo::NONE)
  2182. {
  2183. const CStack * stack = gameHandler->gameState()->curB->battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  2184. if(stack)
  2185. {
  2186. if(vstd::contains(adjacent, stack)) //binding stack is still present
  2187. unbind = false;
  2188. }
  2189. }
  2190. else
  2191. {
  2192. unbind = false;
  2193. }
  2194. }
  2195. if (unbind)
  2196. {
  2197. BattleSetStackProperty ssp;
  2198. ssp.which = BattleSetStackProperty::UNBIND;
  2199. ssp.stackID = st->unitId();
  2200. gameHandler->sendAndApply(&ssp);
  2201. }
  2202. }
  2203. if (st->hasBonusOfType(BonusType::POISON))
  2204. {
  2205. std::shared_ptr<const Bonus> b = st->getBonusLocalFirst(Selector::source(BonusSource::SPELL_EFFECT, SpellID::POISON).And(Selector::type()(BonusType::STACK_HEALTH)));
  2206. if (b) //TODO: what if not?...
  2207. {
  2208. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  2209. if (bte.val < b->val) //(negative) poison effect increases - update it
  2210. {
  2211. bte.effect = vstd::to_underlying(BonusType::POISON);
  2212. gameHandler->sendAndApply(&bte);
  2213. }
  2214. }
  2215. }
  2216. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  2217. {
  2218. const PlayerColor opponent = gameHandler->gameState()->curB->otherPlayer(gameHandler->gameState()->curB->battleGetOwner(st));
  2219. const CGHeroInstance * opponentHero = gameHandler->gameState()->curB->getHero(opponent);
  2220. if(opponentHero)
  2221. {
  2222. ui32 manaDrained = st->valOfBonuses(BonusType::MANA_DRAIN);
  2223. vstd::amin(manaDrained, opponentHero->mana);
  2224. if(manaDrained)
  2225. {
  2226. bte.effect = vstd::to_underlying(BonusType::MANA_DRAIN);
  2227. bte.val = manaDrained;
  2228. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  2229. gameHandler->sendAndApply(&bte);
  2230. }
  2231. }
  2232. }
  2233. if (st->isLiving() && !st->hasBonusOfType(BonusType::FEARLESS))
  2234. {
  2235. bool fearsomeCreature = false;
  2236. for (CStack * stack : gameHandler->gameState()->curB->stacks)
  2237. {
  2238. if (gameHandler->battleMatchOwner(st, stack) && stack->alive() && stack->hasBonusOfType(BonusType::FEAR))
  2239. {
  2240. fearsomeCreature = true;
  2241. break;
  2242. }
  2243. }
  2244. if (fearsomeCreature)
  2245. {
  2246. if (gameHandler->getRandomGenerator().nextInt(99) < 10) //fixed 10%
  2247. {
  2248. bte.effect = vstd::to_underlying(BonusType::FEAR);
  2249. gameHandler->sendAndApply(&bte);
  2250. }
  2251. }
  2252. }
  2253. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTER)));
  2254. int side = gameHandler->gameState()->curB->whatSide(st->unitOwner());
  2255. if(st->canCast() && gameHandler->gameState()->curB->battleGetEnchanterCounter(side) == 0)
  2256. {
  2257. bool cast = false;
  2258. while(!bl.empty() && !cast)
  2259. {
  2260. auto bonus = *RandomGeneratorUtil::nextItem(bl, gameHandler->getRandomGenerator());
  2261. auto spellID = SpellID(bonus->subtype);
  2262. const CSpell * spell = SpellID(spellID).toSpell();
  2263. bl.remove_if([&bonus](const Bonus * b)
  2264. {
  2265. return b == bonus.get();
  2266. });
  2267. spells::BattleCast parameters(gameHandler->gameState()->curB, st, spells::Mode::ENCHANTER, spell);
  2268. parameters.setSpellLevel(bonus->val);
  2269. parameters.massive = true;
  2270. parameters.smart = true;
  2271. //todo: recheck effect level
  2272. if(parameters.castIfPossible(gameHandler->spellEnv, spells::Target(1, spells::Destination())))
  2273. {
  2274. cast = true;
  2275. int cooldown = bonus->additionalInfo[0];
  2276. BattleSetStackProperty ssp;
  2277. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  2278. ssp.absolute = false;
  2279. ssp.val = cooldown;
  2280. ssp.stackID = st->unitId();
  2281. gameHandler->sendAndApply(&ssp);
  2282. }
  2283. }
  2284. }
  2285. }
  2286. }
  2287. void BattleProcessor::makeStackDoNothing(const CStack * next)
  2288. {
  2289. BattleAction doNothing;
  2290. doNothing.actionType = EActionType::NO_ACTION;
  2291. doNothing.side = next->unitSide();
  2292. doNothing.stackNumber = next->unitId();
  2293. makeAutomaticAction(next, doNothing);
  2294. }
  2295. void BattleProcessor::setBattleResult(BattleResult::EResult resultType, int victoriusSide)
  2296. {
  2297. boost::unique_lock<boost::mutex> guard(battleResult.mx);
  2298. if (battleResult.data)
  2299. {
  2300. gameHandler->complain((boost::format("The battle result has been already set (to %d, asked to %d)")
  2301. % battleResult.data->result % resultType).str());
  2302. return;
  2303. }
  2304. auto br = new BattleResult();
  2305. br->result = resultType;
  2306. br->winner = victoriusSide; //surrendering side loses
  2307. gameHandler->gameState()->curB->calculateCasualties(br->casualties);
  2308. battleResult.data = br;
  2309. }
  2310. void BattleProcessor::removeObstacle(const CObstacleInstance & obstacle)
  2311. {
  2312. BattleObstaclesChanged obsRem;
  2313. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  2314. gameHandler->sendAndApply(&obsRem);
  2315. }
  2316. void BattleProcessor::updateGateState()
  2317. {
  2318. // GATE_BRIDGE - leftmost tile, located over moat
  2319. // GATE_OUTER - central tile, mostly covered by gate image
  2320. // GATE_INNER - rightmost tile, inside the walls
  2321. // GATE_OUTER or GATE_INNER:
  2322. // - if defender moves unit on these tiles, bridge will open
  2323. // - if there is a creature (dead or alive) on these tiles, bridge will always remain open
  2324. // - blocked to attacker if bridge is closed
  2325. // GATE_BRIDGE
  2326. // - if there is a unit or corpse here, bridge can't open (and can't close in fortress)
  2327. // - if Force Field is cast here, bridge can't open (but can close, in any town)
  2328. // - deals moat damage to attacker if bridge is closed (fortress only)
  2329. bool hasForceFieldOnBridge = !gameHandler->battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), true).empty();
  2330. bool hasStackAtGateInner = gameHandler->gameState()->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_INNER), false) != nullptr;
  2331. bool hasStackAtGateOuter = gameHandler->gameState()->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_OUTER), false) != nullptr;
  2332. bool hasStackAtGateBridge = gameHandler->gameState()->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_BRIDGE), false) != nullptr;
  2333. bool hasWideMoat = vstd::contains_if(gameHandler->battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  2334. {
  2335. return obst->obstacleType == CObstacleInstance::MOAT;
  2336. });
  2337. BattleUpdateGateState db;
  2338. db.state = gameHandler->gameState()->curB->si.gateState;
  2339. if (gameHandler->gameState()->curB->si.wallState[EWallPart::GATE] == EWallState::DESTROYED)
  2340. {
  2341. db.state = EGateState::DESTROYED;
  2342. }
  2343. else if (db.state == EGateState::OPENED)
  2344. {
  2345. bool hasStackOnLongBridge = hasStackAtGateBridge && hasWideMoat;
  2346. bool gateCanClose = !hasStackAtGateInner && !hasStackAtGateOuter && !hasStackOnLongBridge;
  2347. if (gateCanClose)
  2348. db.state = EGateState::CLOSED;
  2349. else
  2350. db.state = EGateState::OPENED;
  2351. }
  2352. else // CLOSED or BLOCKED
  2353. {
  2354. bool gateBlocked = hasForceFieldOnBridge || hasStackAtGateBridge;
  2355. if (gateBlocked)
  2356. db.state = EGateState::BLOCKED;
  2357. else
  2358. db.state = EGateState::CLOSED;
  2359. }
  2360. if (db.state != gameHandler->gameState()->curB->si.gateState)
  2361. gameHandler->sendAndApply(&db);
  2362. }