BattleProcessor.cpp 92 KB

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