BattleProcessor.cpp 94 KB

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