BattleState.cpp 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963
  1. #include "StdInc.h"
  2. #include "BattleState.h"
  3. #include <numeric>
  4. #include <boost/random/linear_congruential.hpp>
  5. #include "VCMI_Lib.h"
  6. #include "CObjectHandler.h"
  7. #include "CHeroHandler.h"
  8. #include "CCreatureHandler.h"
  9. #include "CSpellHandler.h"
  10. #include "CTownHandler.h"
  11. #include "NetPacks.h"
  12. #include "../lib/JsonNode.h"
  13. /*
  14. * BattleState.h, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. extern boost::rand48 ran;
  23. const CStack * BattleInfo::getNextStack() const
  24. {
  25. std::vector<const CStack *> hlp;
  26. getStackQueue(hlp, 1, -1);
  27. if(hlp.size())
  28. return hlp[0];
  29. else
  30. return NULL;
  31. }
  32. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  33. {
  34. const CStack *ret = NULL;
  35. unsigned i, //fastest stack
  36. j; //fastest stack of the other side
  37. for(i = 0; i < st.size(); i++)
  38. if(st[i])
  39. break;
  40. //no stacks left
  41. if(i == st.size())
  42. return NULL;
  43. const CStack *fastest = st[i], *other = NULL;
  44. int bestSpeed = fastest->Speed(turn);
  45. if(fastest->attackerOwned != curside)
  46. {
  47. ret = fastest;
  48. }
  49. else
  50. {
  51. for(j = i + 1; j < st.size(); j++)
  52. {
  53. if(!st[j]) continue;
  54. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  55. break;
  56. }
  57. if(j >= st.size())
  58. {
  59. ret = fastest;
  60. }
  61. else
  62. {
  63. other = st[j];
  64. if(other->Speed(turn) != bestSpeed)
  65. ret = fastest;
  66. else
  67. ret = other;
  68. }
  69. }
  70. assert(ret);
  71. if(ret == fastest)
  72. st[i] = NULL;
  73. else
  74. st[j] = NULL;
  75. curside = ret->attackerOwned;
  76. return ret;
  77. }
  78. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  79. {
  80. for(ui32 g=0; g<stacks.size(); ++g)
  81. {
  82. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  83. return stacks[g];
  84. }
  85. return NULL;
  86. }
  87. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  88. {
  89. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  90. }
  91. CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive)
  92. {
  93. for(ui32 g=0; g<stacks.size(); ++g)
  94. {
  95. if(stacks[g]->position == tileID
  96. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  97. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  98. {
  99. if(!onlyAlive || stacks[g]->alive())
  100. {
  101. return stacks[g];
  102. }
  103. }
  104. }
  105. return NULL;
  106. }
  107. const CStack * BattleInfo::getStackT(BattleHex tileID, bool onlyAlive) const
  108. {
  109. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  110. }
  111. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<BattleHex> & occupyable, bool flying, const CStack * stackToOmmit) const
  112. {
  113. memset(accessibility, 1, GameConstants::BFIELD_SIZE); //initialize array with trues
  114. //removing accessibility for side columns of hexes
  115. for(int v = 0; v < GameConstants::BFIELD_SIZE; ++v)
  116. {
  117. if( v % GameConstants::BFIELD_WIDTH == 0 || v % GameConstants::BFIELD_WIDTH == (GameConstants::BFIELD_WIDTH - 1) )
  118. accessibility[v] = false;
  119. }
  120. for(ui32 g=0; g<stacks.size(); ++g)
  121. {
  122. if(!stacks[g]->alive() || (stackToOmmit && stacks[g]->ID==stackToOmmit->ID) || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  123. continue;
  124. accessibility[stacks[g]->position] = false;
  125. if(stacks[g]->doubleWide()) //if it's a double hex creature
  126. {
  127. if(stacks[g]->attackerOwned)
  128. accessibility[stacks[g]->position-1] = false;
  129. else
  130. accessibility[stacks[g]->position+1] = false;
  131. }
  132. }
  133. //obstacles
  134. for(ui32 b=0; b<obstacles.size(); ++b)
  135. {
  136. std::vector<BattleHex> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  137. for(ui32 c=0; c<blocked.size(); ++c)
  138. {
  139. if(blocked[c] >=0 && blocked[c] < GameConstants::BFIELD_SIZE)
  140. accessibility[blocked[c]] = false;
  141. }
  142. }
  143. //walls
  144. if(siege > 0)
  145. {
  146. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  147. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  148. {
  149. accessibility[permanentlyLocked[b]] = false;
  150. }
  151. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  152. {std::make_pair(2, BattleHex(182)), std::make_pair(3, BattleHex(130)),
  153. std::make_pair(4, BattleHex(62)), std::make_pair(5, BattleHex(29))};
  154. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  155. {
  156. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  157. {
  158. accessibility[lockedIfNotDestroyed[b].second] = false;
  159. }
  160. }
  161. //gate
  162. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  163. {
  164. accessibility[95] = accessibility[96] = false; //block gate's hexes
  165. }
  166. }
  167. //occupyability
  168. if(addOccupiable && twoHex)
  169. {
  170. std::set<BattleHex> rem; //tiles to unlock
  171. for(int h=0; h<GameConstants::BFIELD_HEIGHT; ++h)
  172. {
  173. for(int w=1; w<GameConstants::BFIELD_WIDTH-1; ++w)
  174. {
  175. BattleHex hex(w, h);
  176. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  177. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  178. )
  179. rem.insert(hex);
  180. }
  181. }
  182. occupyable = rem;
  183. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  184. {
  185. accessibility[*it] = true;
  186. }*/
  187. }
  188. }
  189. bool BattleInfo::isAccessible(BattleHex hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  190. {
  191. if(flying && !lastPos)
  192. return true;
  193. if(twoHex)
  194. {
  195. //if given hex is accessible and appropriate adjacent one is free too
  196. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  197. }
  198. else
  199. {
  200. return accessibility[hex];
  201. }
  202. }
  203. void BattleInfo::makeBFS(BattleHex start, bool *accessibility, BattleHex *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  204. {
  205. //inits
  206. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  207. predecessor[b] = -1;
  208. for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  209. dists[g] = 100000000;
  210. std::queue< std::pair<BattleHex, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  211. hexq.push(std::make_pair(start, true));
  212. dists[hexq.front().first] = 0;
  213. int curNext = -1; //for bfs loop only (helper var)
  214. while(!hexq.empty()) //bfs loop
  215. {
  216. std::pair<BattleHex, bool> curHex = hexq.front();
  217. std::vector<BattleHex> neighbours = curHex.first.neighbouringTiles();
  218. hexq.pop();
  219. for(ui32 nr=0; nr<neighbours.size(); nr++)
  220. {
  221. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  222. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  223. if( dists[curHex.first]+1 >= dists[curNext] )
  224. continue;
  225. if(accessible && curHex.second)
  226. {
  227. hexq.push(std::make_pair(curNext, true));
  228. dists[curNext] = dists[curHex.first] + 1;
  229. }
  230. else if(fillPredecessors && !(accessible && !curHex.second))
  231. {
  232. hexq.push(std::make_pair(curNext, false));
  233. dists[curNext] = dists[curHex.first] + 1;
  234. }
  235. predecessor[curNext] = curHex.first;
  236. }
  237. }
  238. };
  239. std::vector<BattleHex> BattleInfo::getAccessibility( const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable /*= NULL*/, bool forPassingBy /*= false*/ ) const
  240. {
  241. std::vector<BattleHex> ret;
  242. bool ac[GameConstants::BFIELD_SIZE];
  243. if(stack->position < 0) //turrets
  244. return std::vector<BattleHex>();
  245. std::set<BattleHex> occupyable;
  246. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, addOccupiable, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  247. BattleHex pr[GameConstants::BFIELD_SIZE];
  248. int dist[GameConstants::BFIELD_SIZE];
  249. makeBFS(stack->position, ac, pr, dist, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), false);
  250. if(stack->doubleWide())
  251. {
  252. if(!addOccupiable)
  253. {
  254. std::vector<BattleHex> rem;
  255. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  256. {
  257. //don't take into account most left and most right columns of hexes
  258. if( b % GameConstants::BFIELD_WIDTH == 0 || b % GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_WIDTH - 1 )
  259. continue;
  260. if( ac[b] && !(stack->attackerOwned ? ac[b-1] : ac[b+1]) )
  261. {
  262. rem.push_back(b);
  263. }
  264. }
  265. for(ui32 g=0; g<rem.size(); ++g)
  266. {
  267. ac[rem[g]] = false;
  268. }
  269. //removing accessibility for side hexes
  270. for(int v=0; v<GameConstants::BFIELD_SIZE; ++v)
  271. if(stack->attackerOwned ? (v%GameConstants::BFIELD_WIDTH)==1 : (v%GameConstants::BFIELD_WIDTH)==(GameConstants::BFIELD_WIDTH - 2))
  272. ac[v] = false;
  273. }
  274. }
  275. for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  276. {
  277. bool rangeFits;
  278. if (tacticDistance)
  279. {
  280. rangeFits = pr[i] >= 0; //reachable in terms of obstacles
  281. if(!forPassingBy) //only if we're passing through, we may step out of the tactic range -> otherwise check range
  282. rangeFits = rangeFits && isInTacticRange(i);
  283. }
  284. else
  285. rangeFits = dist[i] <= stack->Speed(0, true); //we can reach the stack
  286. if( ( !addOccupiable && rangeFits && ac[i] )
  287. || ( addOccupiable && rangeFits && isAccessible(i, ac, stack->doubleWide(), stack->attackerOwned, stack->hasBonusOfType(Bonus::FLYING), true) )//we can reach it
  288. || (vstd::contains(occupyable, i) && (!tacticDistance && dist[ i + (stack->attackerOwned ? 1 : -1 ) ] <= stack->Speed(0, true) ) && ac[i + (stack->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  289. )
  290. {
  291. ret.push_back(i);
  292. }
  293. }
  294. if(attackable)
  295. {
  296. struct HLP
  297. {
  298. static bool meleeAttackable(BattleHex hex, const std::vector<BattleHex> & baseRng)
  299. {
  300. BOOST_FOREACH(BattleHex h, baseRng)
  301. {
  302. if(BattleHex::mutualPosition(h, hex) > 0)
  303. return true;
  304. }
  305. return false;
  306. }
  307. };
  308. BOOST_FOREACH(const CStack * otherSt, stacks)
  309. {
  310. if(otherSt->owner == stack->owner || !otherSt->isValidTarget(false))
  311. continue;
  312. std::vector<BattleHex> occupiedBySecond;
  313. occupiedBySecond.push_back(otherSt->position);
  314. if(otherSt->doubleWide())
  315. occupiedBySecond.push_back(otherSt->occupiedHex());
  316. if(battleCanShoot(stack, otherSt->position))
  317. {
  318. attackable->insert(attackable->end(), occupiedBySecond.begin(), occupiedBySecond.end());
  319. continue;
  320. }
  321. BOOST_FOREACH(BattleHex he, occupiedBySecond)
  322. {
  323. if(HLP::meleeAttackable(he, ret))
  324. attackable->push_back(he);
  325. }
  326. }
  327. }
  328. return ret;
  329. }
  330. int BattleInfo::getAvaliableHex(TCreature creID, bool attackerOwned, int initialPos) const
  331. {
  332. int pos;
  333. if (initialPos > -1)
  334. pos = initialPos;
  335. else
  336. {
  337. if (attackerOwned)
  338. pos = 0; //top left
  339. else
  340. pos = GameConstants::BFIELD_WIDTH; //top right
  341. }
  342. bool ac[GameConstants::BFIELD_SIZE];
  343. std::set<BattleHex> occupyable;
  344. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  345. bool flying = VLC->creh->creatures[creID]->isFlying();// vstd::contains(VLC->creh->creatures[creID]->bonuses, Bonus::FLYING);
  346. getAccessibilityMap(ac, twoHex, attackerOwned, true, occupyable, flying);
  347. for (int g = pos; (-1 < g) && (g < GameConstants::BFIELD_SIZE); )
  348. {
  349. if ((g % GameConstants::BFIELD_WIDTH != 0) && (g % GameConstants::BFIELD_WIDTH != GameConstants::BFIELD_WIDTH-1) && BattleInfo::isAccessible (g, ac, twoHex, attackerOwned, flying, true))
  350. {
  351. pos = g;
  352. break;
  353. }
  354. if (attackerOwned)
  355. ++g; //probably some more sophisticated range-based iteration is needed
  356. else
  357. --g;
  358. }
  359. return pos;
  360. }
  361. bool BattleInfo::isStackBlocked(const CStack * stack) const
  362. {
  363. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  364. return false;
  365. BOOST_FOREACH(CStack * s, getAdjacentCreatures(stack))
  366. {
  367. if (s->owner != stack->owner) //blocked by enemy stack
  368. return true;
  369. }
  370. return false;
  371. }
  372. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  373. {
  374. BattleHex predecessor[GameConstants::BFIELD_SIZE]; //for getting the Path
  375. int dist[GameConstants::BFIELD_SIZE]; //calculated distances
  376. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  377. if(predecessor[dest] == -1) //cannot reach destination
  378. {
  379. return std::make_pair(std::vector<BattleHex>(), 0);
  380. }
  381. //making the Path
  382. std::vector<BattleHex> path;
  383. BattleHex curElem = dest;
  384. while(curElem != start)
  385. {
  386. path.push_back(curElem);
  387. curElem = predecessor[curElem];
  388. }
  389. return std::make_pair(path, dist[dest]);
  390. }
  391. TDmgRange BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount, TQuantity defenderCount, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  392. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg ) const
  393. {
  394. double additiveBonus = 1.0, multBonus = 1.0,
  395. minDmg = attacker->getMinDamage() * attackerCount,
  396. maxDmg = attacker->getMaxDamage() * attackerCount;
  397. if(attacker->getCreature()->idNumber == 149) //arrow turret
  398. {
  399. switch(attacker->position)
  400. {
  401. case -2: //keep
  402. minDmg = 15;
  403. maxDmg = 15;
  404. break;
  405. case -3: case -4: //turrets
  406. minDmg = 7.5;
  407. maxDmg = 7.5;
  408. break;
  409. }
  410. }
  411. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->getCreature()->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  412. { //minDmg and maxDmg are multiplied by hero attack + 1
  413. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  414. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  415. }
  416. int attackDefenceDifference = 0;
  417. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  418. {
  419. double multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0;
  420. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  421. }
  422. else
  423. {
  424. attackDefenceDifference = attacker->Attack();
  425. }
  426. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  427. {
  428. double multDefenceReduction = (100 - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0;
  429. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  430. }
  431. else
  432. {
  433. attackDefenceDifference -= defender->Defense();
  434. }
  435. //calculating total attack/defense skills modifier
  436. if(shooting) //precision handling (etc.)
  437. attackDefenceDifference += attacker->getBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT))->totalValue();
  438. else //bloodlust handling (etc.)
  439. attackDefenceDifference += attacker->getBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT))->totalValue();
  440. if(attacker->getEffect(55)) //slayer handling
  441. {
  442. std::vector<int> affectedIds;
  443. int spLevel = attacker->getEffect(55)->val;
  444. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  445. {
  446. BOOST_FOREACH(const Bonus *b, VLC->creh->creatures[g]->getBonusList())
  447. {
  448. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  449. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  450. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  451. {
  452. affectedIds.push_back(g);
  453. break;
  454. }
  455. }
  456. }
  457. for(ui32 g=0; g<affectedIds.size(); ++g)
  458. {
  459. if(defender->getCreature()->idNumber == affectedIds[g])
  460. {
  461. attackDefenceDifference += VLC->spellh->spells[55]->powers[attacker->getEffect(55)->val];
  462. break;
  463. }
  464. }
  465. }
  466. //bonus from attack/defense skills
  467. if(attackDefenceDifference < 0) //decreasing dmg
  468. {
  469. double dec = 0.025 * (-attackDefenceDifference);
  470. if(dec > 0.7)
  471. {
  472. multBonus *= 0.3; //1.0 - 0.7
  473. }
  474. else
  475. {
  476. multBonus *= 1.0 - dec;
  477. }
  478. }
  479. else //increasing dmg
  480. {
  481. double inc = 0.05 * attackDefenceDifference;
  482. if(inc > 4.0)
  483. {
  484. additiveBonus += 4.0;
  485. }
  486. else
  487. {
  488. additiveBonus += inc;
  489. }
  490. }
  491. //applying jousting bonus
  492. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  493. additiveBonus += charge * 0.05;
  494. //handling secondary abilities and artifacts giving premies to them
  495. if(attackerHero)
  496. {
  497. if(shooting)
  498. {
  499. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARCHERY) / 100.0;
  500. }
  501. else
  502. {
  503. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::OFFENCE) / 100.0;
  504. }
  505. }
  506. if(defendingHero)
  507. {
  508. multBonus *= (std::max(0, 100-defendingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::ARMORER))) / 100.0;
  509. }
  510. //handling hate effect
  511. additiveBonus += attacker->valOfBonuses(Bonus::HATE, defender->getCreature()->idNumber) / 100.;
  512. //luck bonus
  513. if (lucky)
  514. {
  515. additiveBonus += 1.0;
  516. }
  517. //ballista double dmg
  518. if(ballistaDoubleDmg)
  519. {
  520. additiveBonus += 1.0;
  521. }
  522. if (deathBlow) //Dread Knight and many WoGified creatures
  523. {
  524. additiveBonus += 1.0;
  525. }
  526. //handling spell effects
  527. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  528. {
  529. multBonus *= defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0) / 100.0;
  530. }
  531. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  532. {
  533. multBonus *= defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1) / 100.0;
  534. }
  535. TBonusListPtr curseEffects = attacker->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE)); //attacker->getEffect(42);
  536. TBonusListPtr blessEffects = attacker->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE)); //attacker->getEffect(43);
  537. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  538. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo))->additionalInfo : 0;
  539. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  540. {
  541. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  542. }
  543. class HLP
  544. {
  545. public:
  546. static bool hasAdvancedAirShield(const CStack * stack)
  547. {
  548. BOOST_FOREACH(const Bonus *it, stack->getBonusList())
  549. {
  550. if (it->source == Bonus::SPELL_EFFECT && it->sid == 28 && it->val >= 2)
  551. {
  552. return true;
  553. }
  554. }
  555. return false;
  556. }
  557. };
  558. //wall / distance penalty + advanced air shield
  559. bool distPenalty = !NBonus::hasOfType(attackerHero, Bonus::NO_DISTANCE_PENALTY) &&
  560. hasDistancePenalty(attacker, defender->position);
  561. bool obstaclePenalty = hasWallPenalty(attacker, defender->position);
  562. if (shooting)
  563. {
  564. if (distPenalty || HLP::hasAdvancedAirShield(defender))
  565. {
  566. multBonus *= 0.5;
  567. }
  568. if (obstaclePenalty)
  569. {
  570. multBonus *= 0.5; //cumulative
  571. }
  572. }
  573. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  574. {
  575. multBonus *= 0.5;
  576. }
  577. minDmg *= additiveBonus * multBonus;
  578. maxDmg *= additiveBonus * multBonus;
  579. TDmgRange returnedVal;
  580. if(curseEffects->size()) //curse handling (rest)
  581. {
  582. minDmg += curseBlessAdditiveModifier;
  583. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  584. }
  585. else if(blessEffects->size()) //bless handling
  586. {
  587. maxDmg += curseBlessAdditiveModifier;
  588. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  589. }
  590. else
  591. {
  592. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  593. }
  594. //damage cannot be less than 1
  595. vstd::amax(returnedVal.first, 1);
  596. vstd::amax(returnedVal.second, 1);
  597. return returnedVal;
  598. }
  599. TDmgRange BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  600. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg) const
  601. {
  602. return calculateDmgRange(attacker, defender, attacker->count, defender->count, attackerHero, defendingHero, shooting, charge, lucky, deathBlow, ballistaDoubleDmg);
  603. }
  604. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  605. bool shooting, ui8 charge, bool lucky, bool deathBlow, bool ballistaDoubleDmg )
  606. {
  607. TDmgRange range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky, deathBlow, ballistaDoubleDmg);
  608. if(range.first != range.second)
  609. {
  610. int valuesToAverage[10];
  611. int howManyToAv = std::min<ui32>(10, attacker->count);
  612. for (int g=0; g<howManyToAv; ++g)
  613. {
  614. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  615. }
  616. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  617. }
  618. else
  619. return range.first;
  620. }
  621. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  622. {
  623. for(ui32 i=0; i<stacks.size();i++)//setting casualties
  624. {
  625. const CStack * const st = stacks[i];
  626. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  627. vstd::amax(killed, 0);
  628. if(killed)
  629. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  630. }
  631. }
  632. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, int skillLevel, ui8 attackerOwner, BattleHex destinationTile )
  633. {
  634. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  635. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  636. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  637. if(s->id == Spells::DEATH_RIPPLE || s->id == Spells::DESTROY_UNDEAD || s->id == Spells::ARMAGEDDON)
  638. {
  639. for(int it=0; it<stacks.size(); ++it)
  640. {
  641. if((s->id == Spells::DEATH_RIPPLE && !stacks[it]->getCreature()->isUndead()) //death ripple
  642. || (s->id == Spells::DESTROY_UNDEAD && stacks[it]->getCreature()->isUndead()) //destroy undead
  643. || (s->id == Spells::ARMAGEDDON) //Armageddon
  644. )
  645. {
  646. if(stacks[it]->isValidTarget())
  647. attackedCres.insert(stacks[it]);
  648. }
  649. }
  650. }
  651. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  652. {
  653. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  654. {
  655. CStack * st = getStackT(*it, onlyAlive);
  656. if(st)
  657. {
  658. if (s->id == 76) //Death Cloud //TODO: fireball and fire immunity
  659. {
  660. if (st->isLiving() || st->coversPos(destinationTile)) //directly hit or alive
  661. {
  662. attackedCres.insert(st);
  663. }
  664. }
  665. else
  666. attackedCres.insert(st);
  667. }
  668. }
  669. }
  670. else if(s->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  671. {
  672. if(skillLevel < 3) /*not expert */
  673. {
  674. CStack * st = getStackT(destinationTile, onlyAlive);
  675. if(st)
  676. attackedCres.insert(st);
  677. }
  678. else
  679. {
  680. for(int it=0; it<stacks.size(); ++it)
  681. {
  682. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  683. if((!s->isNegative() && stacks[it]->owner == attackerOwner)
  684. ||(!s->isPositive() && stacks[it]->owner != attackerOwner )
  685. )
  686. {
  687. if(stacks[it]->isValidTarget(!onlyAlive))
  688. attackedCres.insert(stacks[it]);
  689. }
  690. }
  691. } //if(caster->getSpellSchoolLevel(s) < 3)
  692. }
  693. else if(s->getTargetType() == CSpell::CREATURE)
  694. {
  695. CStack * st = getStackT(destinationTile, onlyAlive);
  696. if(st)
  697. attackedCres.insert(st);
  698. }
  699. else //custom range from attackedHexes
  700. {
  701. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  702. {
  703. CStack * st = getStackT(*it, onlyAlive);
  704. if(st)
  705. attackedCres.insert(st);
  706. }
  707. }
  708. return attackedCres;
  709. }
  710. void BattleInfo::getPotentiallyAttackableHexes(AttackableTiles &at, const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos)
  711. {
  712. const int WN = GameConstants::BFIELD_WIDTH;
  713. ui16 hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
  714. if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  715. {
  716. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  717. BOOST_FOREACH (BattleHex tile, hexes)
  718. {
  719. at.hostileCreaturePositions.insert(tile);
  720. }
  721. }
  722. if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  723. {
  724. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  725. BOOST_FOREACH (BattleHex tile, hexes)
  726. {
  727. if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, hex) > -1) //adjacent both to attacker's head and attacked tile
  728. || tile == destinationTile) //or simply attacked directly
  729. {
  730. CStack * st = getStackT(tile, true);
  731. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  732. {
  733. at.hostileCreaturePositions.insert(tile);
  734. }
  735. }
  736. }
  737. }
  738. if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  739. {
  740. std::vector<BattleHex> hexes; //only one, in fact
  741. int pseudoVector = destinationTile.hex - hex;
  742. switch (pseudoVector)
  743. {
  744. case 1:
  745. case -1:
  746. BattleHex::checkAndPush(destinationTile.hex + pseudoVector, hexes);
  747. break;
  748. case WN: //17
  749. case WN + 1: //18
  750. case -WN: //-17
  751. case -WN + 1: //-16
  752. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : -1 ), hexes);
  753. break;
  754. case WN-1: //16
  755. case -WN-1: //-18
  756. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : 0), hexes);
  757. break;
  758. }
  759. BOOST_FOREACH (BattleHex tile, hexes)
  760. {
  761. CStack * st = getStackT(tile, true);
  762. if(st) //friendly stacks can also be damaged by Dragon Breath
  763. {
  764. at.friendlyCreaturePositions.insert(tile);
  765. }
  766. }
  767. }
  768. }
  769. std::set<CStack*> BattleInfo::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos)
  770. { //TODO: caching?
  771. AttackableTiles at;
  772. getPotentiallyAttackableHexes(at, attacker, destinationTile, attackerPos);
  773. std::set<CStack*> attackedCres;
  774. BOOST_FOREACH (BattleHex tile, at.hostileCreaturePositions) //all around & three-headed attack
  775. {
  776. CStack * st = getStackT(tile, true);
  777. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  778. {
  779. attackedCres.insert(st);
  780. }
  781. }
  782. BOOST_FOREACH (BattleHex tile, at.friendlyCreaturePositions)
  783. {
  784. CStack * st = getStackT(tile, true);
  785. if(st) //friendly stacks can also be damaged by Dragon Breath
  786. {
  787. attackedCres.insert(st);
  788. }
  789. }
  790. return attackedCres;
  791. }
  792. std::set<BattleHex> BattleInfo::getAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos)
  793. {
  794. AttackableTiles at;
  795. getPotentiallyAttackableHexes(at, attacker, destinationTile, attackerPos);
  796. std::set<BattleHex> attackedHexes;
  797. BOOST_FOREACH (BattleHex tile, at.hostileCreaturePositions)
  798. {
  799. CStack * st = getStackT(tile, true);
  800. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  801. {
  802. attackedHexes.insert(tile);
  803. }
  804. }
  805. BOOST_FOREACH (BattleHex tile, at.friendlyCreaturePositions)
  806. {
  807. CStack * st = getStackT(tile, true);
  808. if(st) //friendly stacks can also be damaged by Dragon Breath
  809. {
  810. attackedHexes.insert(tile);
  811. }
  812. }
  813. return attackedHexes;
  814. }
  815. std::set<CStack*> BattleInfo::getAdjacentCreatures (const CStack * stack) const
  816. {
  817. std::set<CStack*> stacks;
  818. CStack * localStack;
  819. BOOST_FOREACH (BattleHex hex, stack->getSurroundingHexes())
  820. {
  821. localStack = const_cast<CStack*>(getStackT(hex, true)); //only alive?
  822. if (localStack)
  823. stacks.insert(localStack);
  824. }
  825. return stacks;
  826. }
  827. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower)
  828. {
  829. if(!caster)
  830. {
  831. if (!usedSpellPower)
  832. return 3; //default duration of all creature spells
  833. else
  834. return usedSpellPower; //use creature spell power
  835. }
  836. switch(spell->id)
  837. {
  838. case Spells::FRENZY:
  839. return 1;
  840. default: //other spells
  841. return caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  842. }
  843. }
  844. CStack * BattleInfo::generateNewStack(const CStackInstance &base, bool attackerOwned, int slot, BattleHex position) const
  845. {
  846. int stackID = getIdForNewStack();
  847. int owner = attackerOwned ? sides[0] : sides[1];
  848. assert((owner >= GameConstants::PLAYER_LIMIT) ||
  849. (base.armyObj && base.armyObj->tempOwner == owner));
  850. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  851. ret->position = position;
  852. return ret;
  853. }
  854. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, int slot, BattleHex position) const
  855. {
  856. int stackID = getIdForNewStack();
  857. int owner = attackerOwned ? sides[0] : sides[1];
  858. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  859. ret->position = position;
  860. return ret;
  861. }
  862. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  863. {
  864. ui32 ret = caster->getSpellCost(sp);
  865. //checking for friendly stacks reducing cost of the spell and
  866. //enemy stacks increasing it
  867. si32 manaReduction = 0;
  868. si32 manaIncrease = 0;
  869. for(int g=0; g<stacks.size(); ++g)
  870. {
  871. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  872. {
  873. vstd::amax(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  874. }
  875. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  876. {
  877. vstd::amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  878. }
  879. }
  880. return ret - manaReduction + manaIncrease;
  881. }
  882. int BattleInfo::hexToWallPart(BattleHex hex) const
  883. {
  884. if(siege == 0) //there is no battle!
  885. return -1;
  886. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  887. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  888. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7),
  889. std::make_pair(45, -2), std::make_pair(78, -2), std::make_pair(112, -2), std::make_pair(147, -2)}; // -2 - indestructible walls
  890. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  891. {
  892. if(attackable[g].first == hex)
  893. return attackable[g].second;
  894. }
  895. return -1; //not found!
  896. }
  897. int BattleInfo::lineToWallHex( int line ) const
  898. {
  899. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  900. return lineToHex[line];
  901. }
  902. std::pair<const CStack *, BattleHex> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  903. {
  904. bool ac[GameConstants::BFIELD_SIZE];
  905. std::set<BattleHex> occupyable;
  906. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest);
  907. BattleHex predecessor[GameConstants::BFIELD_SIZE];
  908. int dist[GameConstants::BFIELD_SIZE];
  909. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  910. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  911. for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  912. {
  913. const CStack * atG = getStackT(g);
  914. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  915. continue;
  916. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  917. {
  918. if(predecessor[g] == -1) //TODO: is it really the best solution?
  919. continue;
  920. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  921. }
  922. }
  923. if(stackPairs.size() > 0)
  924. {
  925. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  926. minimalPairs.push_back(stackPairs[0]);
  927. for(int b=1; b<stackPairs.size(); ++b)
  928. {
  929. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  930. {
  931. minimalPairs.clear();
  932. minimalPairs.push_back(stackPairs[b]);
  933. }
  934. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  935. {
  936. minimalPairs.push_back(stackPairs[b]);
  937. }
  938. }
  939. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  940. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  941. }
  942. return std::make_pair<const CStack * , BattleHex>(NULL, BattleHex::INVALID);
  943. }
  944. ui32 BattleInfo::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  945. {
  946. ui32 ret = baseDamage;
  947. //applying sorcery secondary skill
  948. if(caster)
  949. {
  950. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, CGHeroInstance::SORCERY)) / 100.0;
  951. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0;
  952. if(sp->air)
  953. ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
  954. else if(sp->fire) //only one type of bonus for Magic Arrow
  955. ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
  956. else if(sp->water)
  957. ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
  958. else if(sp->earth)
  959. ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
  960. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  961. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  962. }
  963. return ret;
  964. }
  965. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  966. {
  967. ui32 ret = 0; //value to return
  968. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  969. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  970. //check if spell really does damage - if not, return 0
  971. if(VLC->spellh->damageSpells.find(sp->id) == VLC->spellh->damageSpells.end())
  972. return 0;
  973. ret = usedSpellPower * sp->power;
  974. ret += sp->powers[spellSchoolLevel];
  975. //affected creature-specific part
  976. if(affectedCreature)
  977. {
  978. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  979. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  980. {
  981. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  982. ret /= 100;
  983. }
  984. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  985. {
  986. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  987. ret /= 100;
  988. }
  989. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  990. {
  991. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  992. ret /= 100;
  993. }
  994. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  995. {
  996. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  997. ret /= 100;
  998. }
  999. //general spell dmg reduction
  1000. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  1001. {
  1002. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  1003. ret /= 100;
  1004. }
  1005. //dmg increasing
  1006. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  1007. {
  1008. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  1009. ret /= 100;
  1010. }
  1011. }
  1012. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  1013. return ret;
  1014. }
  1015. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack) const
  1016. {
  1017. bool resurrect = resurrects(spell->id);
  1018. int healedHealth = caster->getPrimSkillLevel(2) * spell->power + spell->powers[caster->getSpellSchoolLevel(spell)];
  1019. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  1020. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  1021. }
  1022. ui32 BattleInfo::calculateHealedHP(int healedHealth, const CSpell * spell, const CStack * stack) const
  1023. {
  1024. bool resurrect = resurrects(spell->id);
  1025. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  1026. }
  1027. ui32 BattleInfo::calculateHealedHP(const CSpell * spell, int usedSpellPower, int spellSchoolLevel, const CStack * stack) const
  1028. {
  1029. bool resurrect = resurrects(spell->id);
  1030. int healedHealth = usedSpellPower * spell->power + spell->powers[spellSchoolLevel];
  1031. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  1032. }
  1033. bool BattleInfo::resurrects(TSpell spellid) const
  1034. {
  1035. return vstd::contains(VLC->spellh->risingSpells, spellid);
  1036. }
  1037. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  1038. {
  1039. //we'll split creatures with remaining movement to 4 parts
  1040. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  1041. int toMove = 0; //how many stacks still has move
  1042. const CStack *active = getStack(activeStack);
  1043. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  1044. if(!turn && active && active->willMove() && !vstd::contains(active->state, EBattleStackState::WAITING))
  1045. {
  1046. out.push_back(active);
  1047. if(out.size() == howMany)
  1048. return;
  1049. }
  1050. for(ui32 i=0; i<stacks.size(); ++i)
  1051. {
  1052. const CStack * const s = stacks[i];
  1053. if((turn <= 0 && !s->willMove()) //we are considering current round and stack won't move
  1054. || (turn > 0 && !s->canMove(turn)) //stack won't be able to move in later rounds
  1055. || (turn <= 0 && s == active && out.size() && s == out.front())) //it's active stack already added at the beginning of queue
  1056. {
  1057. continue;
  1058. }
  1059. int p = -1; //in which phase this tack will move?
  1060. if(turn <= 0 && vstd::contains(s->state, EBattleStackState::WAITING)) //consider waiting state only for ongoing round
  1061. {
  1062. if(vstd::contains(s->state, EBattleStackState::HAD_MORALE))
  1063. p = 2;
  1064. else
  1065. p = 3;
  1066. }
  1067. else if(s->getCreature()->idNumber == 145 || s->getCreature()->idNumber == 149) //catapult and turrets are first
  1068. {
  1069. p = 0;
  1070. }
  1071. else
  1072. {
  1073. p = 1;
  1074. }
  1075. phase[p].push_back(s);
  1076. toMove++;
  1077. }
  1078. for(int i = 0; i < 4; i++)
  1079. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  1080. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  1081. out.push_back(phase[0][i]);
  1082. if(out.size() == howMany)
  1083. return;
  1084. if(lastMoved == -1)
  1085. {
  1086. if(active)
  1087. {
  1088. if(out.size() && out.front() == active)
  1089. lastMoved = active->attackerOwned;
  1090. else
  1091. lastMoved = active->attackerOwned;
  1092. }
  1093. else
  1094. {
  1095. lastMoved = 0;
  1096. }
  1097. }
  1098. int pi = 1;
  1099. while(out.size() < howMany)
  1100. {
  1101. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  1102. if(!hlp)
  1103. {
  1104. pi++;
  1105. if(pi > 3)
  1106. {
  1107. //if(turn != 2)
  1108. getStackQueue(out, howMany, turn + 1, lastMoved);
  1109. return;
  1110. }
  1111. }
  1112. else
  1113. {
  1114. out.push_back(hlp);
  1115. }
  1116. }
  1117. }
  1118. si8 BattleInfo::hasDistancePenalty( const CStack * stack, BattleHex destHex ) const
  1119. {
  1120. struct HLP
  1121. {
  1122. static bool lowerAnalyze(const CStack * stack, BattleHex hex)
  1123. {
  1124. int distance = BattleHex::getDistance(hex, stack->position);
  1125. //I hope it's approximately correct
  1126. return distance > 10 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  1127. }
  1128. };
  1129. const CStack * dstStack = getStackT(destHex, false);
  1130. if (dstStack->doubleWide())
  1131. return HLP::lowerAnalyze(stack, destHex) && HLP::lowerAnalyze(stack, dstStack->occupiedHex());
  1132. else
  1133. return HLP::lowerAnalyze(stack, destHex);
  1134. }
  1135. si8 BattleInfo::sameSideOfWall(int pos1, int pos2) const
  1136. {
  1137. int wallInStackLine = lineToWallHex(pos1/GameConstants::BFIELD_WIDTH);
  1138. int wallInDestLine = lineToWallHex(pos2/GameConstants::BFIELD_WIDTH);
  1139. bool stackLeft = pos1 < wallInStackLine;
  1140. bool destLeft = pos2 < wallInDestLine;
  1141. return stackLeft != destLeft;
  1142. }
  1143. si8 BattleInfo::hasWallPenalty( const CStack* stack, BattleHex destHex ) const
  1144. {
  1145. if (!siege || stack->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  1146. {
  1147. return false;
  1148. }
  1149. int wallInStackLine = lineToWallHex(stack->position/GameConstants::BFIELD_WIDTH);
  1150. int wallInDestLine = lineToWallHex(destHex/GameConstants::BFIELD_WIDTH);
  1151. bool stackLeft = stack->position < wallInStackLine;
  1152. bool destRight = destHex > wallInDestLine;
  1153. if (stackLeft && destRight) //shooting from outside to inside
  1154. {
  1155. int row = (stack->position + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  1156. if (stack->position > destHex && ((destHex % GameConstants::BFIELD_WIDTH - stack->position % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  1157. row -= 2;
  1158. int wallPos = lineToWallHex(row);
  1159. if (hexToWallPart(wallPos) != -1) //wall still exists or is indestructible
  1160. return true;
  1161. }
  1162. return false;
  1163. }
  1164. si8 BattleInfo::canTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const
  1165. {
  1166. bool ac[GameConstants::BFIELD_SIZE];
  1167. std::set<BattleHex> occupyable;
  1168. getAccessibilityMap(ac, stack->doubleWide(), stack->attackerOwned, false, occupyable, stack->hasBonusOfType(Bonus::FLYING), stack);
  1169. if (siege && telportLevel < 2) //check for wall
  1170. {
  1171. return ac[destHex] && sameSideOfWall(stack->position, destHex);
  1172. }
  1173. else
  1174. {
  1175. return ac[destHex];
  1176. }
  1177. }
  1178. bool BattleInfo::battleCanShoot(const CStack * stack, BattleHex dest) const
  1179. {
  1180. if(tacticDistance) //no shooting during tactics
  1181. return false;
  1182. const CStack *dst = getStackT(dest);
  1183. if(!stack || !dst) return false;
  1184. const CGHeroInstance * stackHero = battleGetOwner(stack);
  1185. if(stack->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  1186. return false;
  1187. if(stack->getCreature()->idNumber == 145 && dst) //catapult cannot attack creatures
  1188. return false;
  1189. if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  1190. && stack->owner != dst->owner
  1191. && dst->alive()
  1192. && (!isStackBlocked(stack) || NBonus::hasOfType(stackHero, Bonus::FREE_SHOOTING))
  1193. && stack->shots
  1194. )
  1195. return true;
  1196. return false;
  1197. }
  1198. bool BattleInfo::battleCanFlee(int player) const
  1199. {
  1200. if (player == sides[0])
  1201. {
  1202. if (!heroes[0])
  1203. return false;//current player have no hero
  1204. }
  1205. else
  1206. {
  1207. if (!heroes[1])
  1208. return false;
  1209. }
  1210. if( ( heroes[0] && heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) ) //eg. one of heroes is wearing shakles of war
  1211. || ( heroes[1] && heroes[1]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE)))
  1212. return false;
  1213. if (player == sides[1] && siege //defender in siege
  1214. && !(town->subID == 6 && vstd::contains(town->builtBuildings, 17)))//without escape tunnel
  1215. return false;
  1216. return true;
  1217. }
  1218. const CStack * BattleInfo::battleGetStack(BattleHex pos, bool onlyAlive)
  1219. {
  1220. CStack * stack = NULL;
  1221. for(ui32 g=0; g<stacks.size(); ++g)
  1222. {
  1223. if(stacks[g]->position == pos
  1224. || (stacks[g]->doubleWide()
  1225. &&( (stacks[g]->attackerOwned && stacks[g]->position-1 == pos)
  1226. || (!stacks[g]->attackerOwned && stacks[g]->position+1 == pos) )
  1227. ) )
  1228. {
  1229. if (stacks[g]->alive())
  1230. return stacks[g]; //we prefer living stacks - there cna be only one stack on te tile, so return it imediately
  1231. else if (!onlyAlive)
  1232. stack = stacks[g]; //dead stacks are only accessible when there's no alive stack on this tile
  1233. }
  1234. }
  1235. return stack;
  1236. }
  1237. const CGHeroInstance * BattleInfo::battleGetOwner(const CStack * stack) const
  1238. {
  1239. return heroes[!stack->attackerOwned];
  1240. }
  1241. si8 BattleInfo::battleMinSpellLevel() const
  1242. {
  1243. si8 levelLimit = 0;
  1244. if(const CGHeroInstance *h1 = heroes[0])
  1245. {
  1246. vstd::amax(levelLimit, h1->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY));
  1247. }
  1248. if(const CGHeroInstance *h2 = heroes[1])
  1249. {
  1250. vstd::amax(levelLimit, h2->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY));
  1251. }
  1252. return levelLimit;
  1253. }
  1254. void BattleInfo::localInit()
  1255. {
  1256. belligerents[0]->battle = belligerents[1]->battle = this;
  1257. BOOST_FOREACH(CArmedInstance *b, belligerents)
  1258. b->attachTo(this);
  1259. BOOST_FOREACH(CStack *s, stacks)
  1260. localInitStack(s);
  1261. exportBonuses();
  1262. }
  1263. void BattleInfo::localInitStack(CStack * s)
  1264. {
  1265. s->exportBonuses();
  1266. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  1267. {
  1268. s->attachTo(const_cast<CStackInstance*>(s->base));
  1269. }
  1270. else //attach directly to obj to which stack belongs and creature type
  1271. {
  1272. CArmedInstance *army = belligerents[!s->attackerOwned];
  1273. s->attachTo(army);
  1274. assert(s->type);
  1275. s->attachTo(const_cast<CCreature*>(s->type));
  1276. }
  1277. s->postInit();
  1278. }
  1279. namespace CGH
  1280. {
  1281. using namespace std;
  1282. static void readBattlePositions(const JsonNode &node, vector< vector<int> > & dest)
  1283. {
  1284. BOOST_FOREACH(const JsonNode &level, node.Vector())
  1285. {
  1286. std::vector<int> pom;
  1287. BOOST_FOREACH(const JsonNode &value, level.Vector())
  1288. {
  1289. pom.push_back(value.Float());
  1290. }
  1291. dest.push_back(pom);
  1292. }
  1293. }
  1294. }
  1295. BattleInfo * BattleInfo::setupBattle( int3 tile, int terrain, int terType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  1296. {
  1297. CMP_stack cmpst;
  1298. BattleInfo *curB = new BattleInfo;
  1299. curB->castSpells[0] = curB->castSpells[1] = 0;
  1300. curB->sides[0] = armies[0]->tempOwner;
  1301. curB->sides[1] = armies[1]->tempOwner;
  1302. if(curB->sides[1] == 254)
  1303. curB->sides[1] = 255;
  1304. std::vector<CStack*> & stacks = (curB->stacks);
  1305. curB->tile = tile;
  1306. curB->battlefieldType = terType;
  1307. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  1308. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  1309. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  1310. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  1311. curB->round = -2;
  1312. curB->activeStack = -1;
  1313. curB->enchanterCounter[0] = curB->enchanterCounter[1] = 0; //ready to cast
  1314. if(town)
  1315. {
  1316. curB->town = town;
  1317. curB->siege = town->fortLevel();
  1318. }
  1319. else
  1320. {
  1321. curB->town = NULL;
  1322. curB->siege = 0;
  1323. }
  1324. //reading battleStartpos
  1325. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1326. const JsonNode config(GameConstants::DATA_DIR + "/config/battleStartpos.json");
  1327. const JsonVector &positions = config["battle_positions"].Vector();
  1328. CGH::readBattlePositions(positions[0]["levels"], attackerLoose);
  1329. CGH::readBattlePositions(positions[1]["levels"], defenderLoose);
  1330. CGH::readBattlePositions(positions[2]["levels"], attackerTight);
  1331. CGH::readBattlePositions(positions[3]["levels"], defenderTight);
  1332. CGH::readBattlePositions(positions[4]["levels"], attackerCreBank);
  1333. CGH::readBattlePositions(positions[5]["levels"], defenderCreBank);
  1334. //battleStartpos read
  1335. int k = 0; //stack serial
  1336. for(TSlots::const_iterator i = armies[0]->Slots().begin(); i!=armies[0]->Slots().end(); i++, k++)
  1337. {
  1338. int pos;
  1339. if(creatureBank)
  1340. pos = attackerCreBank[armies[0]->stacksCount()-1][k];
  1341. else if(armies[0]->formation)
  1342. pos = attackerTight[armies[0]->stacksCount()-1][k];
  1343. else
  1344. pos = attackerLoose[armies[0]->stacksCount()-1][k];
  1345. CStack * stack = curB->generateNewStack(*i->second, true, i->first, pos);
  1346. stacks.push_back(stack);
  1347. }
  1348. k = 0;
  1349. for(TSlots::const_iterator i = armies[1]->Slots().begin(); i!=armies[1]->Slots().end(); i++, k++)
  1350. {
  1351. int pos;
  1352. if(creatureBank)
  1353. pos = defenderCreBank[armies[1]->stacksCount()-1][k];
  1354. else if(armies[1]->formation)
  1355. pos = defenderTight[armies[1]->stacksCount()-1][k];
  1356. else
  1357. pos = defenderLoose[armies[1]->stacksCount()-1][k];
  1358. CStack * stack = curB->generateNewStack(*i->second, false, i->first, pos);
  1359. stacks.push_back(stack);
  1360. }
  1361. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1362. {
  1363. //we should do that for creature bank too
  1364. if(stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1365. {
  1366. stacks[g]->position += BattleHex::RIGHT;
  1367. }
  1368. else if(stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1369. {
  1370. if (stacks[g]->position.getX() > 1)
  1371. stacks[g]->position += BattleHex::LEFT;
  1372. }
  1373. }
  1374. //adding war machines
  1375. if(!creatureBank)
  1376. {
  1377. if(heroes[0])
  1378. {
  1379. if(heroes[0]->getArt(13)) //ballista
  1380. {
  1381. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), true, 255, 52);
  1382. stacks.push_back(stack);
  1383. }
  1384. if(heroes[0]->getArt(14)) //ammo cart
  1385. {
  1386. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), true, 255, 18);
  1387. stacks.push_back(stack);
  1388. }
  1389. if(heroes[0]->getArt(15)) //first aid tent
  1390. {
  1391. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), true, 255, 154);
  1392. stacks.push_back(stack);
  1393. }
  1394. }
  1395. if(heroes[1])
  1396. {
  1397. //defending hero shouldn't receive ballista (bug #551)
  1398. if(heroes[1]->getArt(13) && !town) //ballista
  1399. {
  1400. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), false, 255, 66);
  1401. stacks.push_back(stack);
  1402. }
  1403. if(heroes[1]->getArt(14)) //ammo cart
  1404. {
  1405. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), false, 255, 32);
  1406. stacks.push_back(stack);
  1407. }
  1408. if(heroes[1]->getArt(15)) //first aid tent
  1409. {
  1410. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), false, 255, 168);
  1411. stacks.push_back(stack);
  1412. }
  1413. }
  1414. if(town && heroes[0] && town->hasFort()) //catapult
  1415. {
  1416. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(145, 1), true, 255, 120);
  1417. stacks.push_back(stack);
  1418. }
  1419. }
  1420. //war machines added
  1421. if (curB->siege == 2 || curB->siege == 3)
  1422. {
  1423. // keep tower
  1424. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -2);
  1425. stacks.push_back(stack);
  1426. if (curB->siege == 3)
  1427. {
  1428. // lower tower + upper tower
  1429. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -4);
  1430. stacks.push_back(stack);
  1431. stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), false, 255, -3);
  1432. stacks.push_back(stack);
  1433. }
  1434. }
  1435. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1436. //setting up siege
  1437. if(town && town->hasFort())
  1438. {
  1439. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1440. {
  1441. curB->si.wallState[b] = 1;
  1442. }
  1443. }
  1444. //randomize obstacles
  1445. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1446. {
  1447. bool obAv[GameConstants::BFIELD_SIZE]; //availability of hexes for obstacles;
  1448. std::vector<int> possibleObstacles;
  1449. for(int i=0; i<GameConstants::BFIELD_SIZE; ++i)
  1450. {
  1451. if(i%17 < 4 || i%17 > 12)
  1452. {
  1453. obAv[i] = false;
  1454. }
  1455. else
  1456. {
  1457. obAv[i] = true;
  1458. }
  1459. }
  1460. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1461. {
  1462. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  1463. {
  1464. possibleObstacles.push_back(g->first);
  1465. }
  1466. }
  1467. srand(time(NULL));
  1468. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1469. {
  1470. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1471. while(toBlock>0)
  1472. {
  1473. CObstacleInstance coi;
  1474. coi.uniqueID = curB->obstacles.size();
  1475. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1476. coi.pos = rand()%GameConstants::BFIELD_SIZE;
  1477. std::vector<BattleHex> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1478. bool badObstacle = false;
  1479. for(int b=0; b<block.size(); ++b)
  1480. {
  1481. if(block[b] < 0 || block[b] >= GameConstants::BFIELD_SIZE || !obAv[block[b]])
  1482. {
  1483. badObstacle = true;
  1484. break;
  1485. }
  1486. }
  1487. if(badObstacle) continue;
  1488. //obstacle can be placed
  1489. curB->obstacles.push_back(coi);
  1490. for(int b=0; b<block.size(); ++b)
  1491. {
  1492. if(block[b] >= 0 && block[b] < GameConstants::BFIELD_SIZE)
  1493. obAv[block[b]] = false;
  1494. }
  1495. toBlock -= block.size();
  1496. }
  1497. }
  1498. }
  1499. //spell level limiting bonus
  1500. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  1501. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  1502. //giving terrain overalay premies
  1503. int bonusSubtype = -1;
  1504. switch(terType)
  1505. {
  1506. case 9: //magic plains
  1507. {
  1508. bonusSubtype = 0;
  1509. }
  1510. case 14: //fiery fields
  1511. {
  1512. if(bonusSubtype == -1) bonusSubtype = 1;
  1513. }
  1514. case 15: //rock lands
  1515. {
  1516. if(bonusSubtype == -1) bonusSubtype = 8;
  1517. }
  1518. case 16: //magic clouds
  1519. {
  1520. if(bonusSubtype == -1) bonusSubtype = 2;
  1521. }
  1522. case 17: //lucid pools
  1523. {
  1524. if(bonusSubtype == -1) bonusSubtype = 4;
  1525. }
  1526. { //common part for cases 9, 14, 15, 16, 17
  1527. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  1528. break;
  1529. }
  1530. case 18: //holy ground
  1531. {
  1532. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  1533. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  1534. break;
  1535. }
  1536. case 19: //clover field
  1537. { //+2 luck bonus for neutral creatures
  1538. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureFactionLimiter>(-1)));
  1539. break;
  1540. }
  1541. case 20: //evil fog
  1542. {
  1543. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  1544. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  1545. break;
  1546. }
  1547. case 22: //cursed ground
  1548. {
  1549. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1550. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1551. Bonus * b = makeFeature(Bonus::LEVEL_SPELL_IMMUNITY, Bonus::ONE_BATTLE, GameConstants::SPELL_LEVELS, 1, Bonus::TERRAIN_OVERLAY);
  1552. b->valType = Bonus::INDEPENDENT_MAX;
  1553. curB->addNewBonus(b);
  1554. break;
  1555. }
  1556. }
  1557. //overlay premies given
  1558. //native terrain bonuses
  1559. if(town) //during siege always take premies for native terrain of faction
  1560. terrain = VLC->heroh->nativeTerrains[town->town->typeID];
  1561. auto nativeTerrain = make_shared<CreatureNativeTerrainLimiter>(terrain);
  1562. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1563. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1564. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1565. //////////////////////////////////////////////////////////////////////////
  1566. //tactics
  1567. bool isTacticsAllowed = !creatureBank; //no tactics in crebanks
  1568. int tacticLvls[2] = {0};
  1569. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  1570. {
  1571. if(heroes[i])
  1572. tacticLvls[i] += heroes[i]->getSecSkillLevel(CGHeroInstance::TACTICS);
  1573. }
  1574. int tacticsSkillDiff = tacticLvls[0] - tacticLvls[1];
  1575. if(tacticsSkillDiff && isTacticsAllowed)
  1576. {
  1577. curB->tacticsSide = tacticsSkillDiff < 0;
  1578. curB->tacticDistance = std::abs(tacticsSkillDiff)*2 + 1;
  1579. }
  1580. else
  1581. curB->tacticDistance = 0;
  1582. // workaround — bonuses affecting only enemy
  1583. for(int i = 0; i < 2; i++)
  1584. {
  1585. TNodes nodes;
  1586. curB->belligerents[i]->getRedAncestors(nodes);
  1587. BOOST_FOREACH(CBonusSystemNode *n, nodes)
  1588. {
  1589. BOOST_FOREACH(Bonus *b, n->getExportedBonusList())
  1590. {
  1591. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  1592. {
  1593. Bonus *bCopy = new Bonus(*b);
  1594. bCopy->effectRange = Bonus::NO_LIMIT;
  1595. bCopy->propagator.reset();
  1596. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i]));
  1597. curB->addNewBonus(bCopy);
  1598. }
  1599. }
  1600. }
  1601. }
  1602. return curB;
  1603. }
  1604. bool BattleInfo::isInTacticRange( BattleHex dest ) const
  1605. {
  1606. return ((!tacticsSide && dest.getX() > 0 && dest.getX() <= tacticDistance)
  1607. || (tacticsSide && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - tacticDistance - 1));
  1608. }
  1609. ESpellCastProblem::ESpellCastProblem BattleInfo::battleCanCastSpell(int player, ECastingMode::ECastingMode mode) const
  1610. {
  1611. int side = sides[0] == player ? 0 : 1;
  1612. switch (mode)
  1613. {
  1614. case ECastingMode::HERO_CASTING:
  1615. {
  1616. if(tacticDistance)
  1617. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  1618. if(castSpells[side] > 0)
  1619. return ESpellCastProblem::ALREADY_CASTED_THIS_TURN;
  1620. if(!heroes[side])
  1621. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  1622. if(!heroes[side]->getArt(17))
  1623. return ESpellCastProblem::NO_SPELLBOOK;
  1624. }
  1625. break;
  1626. }
  1627. return ESpellCastProblem::OK;
  1628. }
  1629. ESpellCastProblem::ESpellCastProblem BattleInfo::battleCanCastThisSpell( int player, const CSpell * spell, ECastingMode::ECastingMode mode ) const
  1630. {
  1631. ESpellCastProblem::ESpellCastProblem genProblem = battleCanCastSpell(player, mode);
  1632. if(genProblem != ESpellCastProblem::OK)
  1633. return genProblem;
  1634. int cside = sides[0] == player ? 0 : 1; //caster's side
  1635. switch(mode)
  1636. {
  1637. case ECastingMode::HERO_CASTING:
  1638. {
  1639. const CGHeroInstance * caster = heroes[cside];
  1640. if(!caster->canCastThisSpell(spell))
  1641. return ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
  1642. if(caster->mana < getSpellCost(spell, caster)) //not enough mana
  1643. return ESpellCastProblem::NOT_ENOUGH_MANA;
  1644. }
  1645. break;
  1646. }
  1647. if(spell->id < 10) //it's adventure spell (not combat))
  1648. return ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
  1649. if(NBonus::hasOfType(heroes[1-cside], Bonus::SPELL_IMMUNITY, spell->id)) //non - casting hero provides immunity for this spell
  1650. return ESpellCastProblem::SECOND_HEROS_SPELL_IMMUNITY;
  1651. if(battleMinSpellLevel() > spell->level) //non - casting hero stops caster from casting this spell
  1652. return ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED;
  1653. int spellIDs[] = {66, 67, 68, 69}; //IDs of summon elemental spells (fire, earth, water, air)
  1654. int creIDs[] = {114, 113, 115, 112}; //(fire, earth, water, air)
  1655. int * idp = std::find(spellIDs, spellIDs + ARRAY_COUNT(spellIDs), spell->id);
  1656. int arpos = idp - spellIDs;
  1657. if(arpos < ARRAY_COUNT(spellIDs))
  1658. {
  1659. //check if there are summoned elementals of other type
  1660. BOOST_FOREACH ( const CStack * st, stacks)
  1661. {
  1662. if (vstd::contains(st->state, EBattleStackState::SUMMONED) && st->getCreature()->idNumber != creIDs[arpos])
  1663. {
  1664. return ESpellCastProblem::ANOTHER_ELEMENTAL_SUMMONED;
  1665. }
  1666. }
  1667. }
  1668. //checking if there exists an appropriate target
  1669. switch(spell->getTargetType())
  1670. {
  1671. case CSpell::CREATURE:
  1672. case CSpell::CREATURE_EXPERT_MASSIVE:
  1673. if(mode == ECastingMode::HERO_CASTING)
  1674. {
  1675. const CGHeroInstance * caster = getHero(player);
  1676. bool targetExists = false;
  1677. BOOST_FOREACH(const CStack * stack, stacks)
  1678. {
  1679. switch (spell->positiveness)
  1680. {
  1681. case CSpell::POSITIVE:
  1682. if(stack->owner == caster->getOwner())
  1683. {
  1684. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1685. {
  1686. targetExists = true;
  1687. break;
  1688. }
  1689. }
  1690. break;
  1691. case CSpell::NEUTRAL:
  1692. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1693. {
  1694. targetExists = true;
  1695. break;
  1696. }
  1697. break;
  1698. case CSpell::NEGATIVE:
  1699. if(stack->owner != caster->getOwner())
  1700. {
  1701. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1702. {
  1703. targetExists = true;
  1704. break;
  1705. }
  1706. }
  1707. break;
  1708. }
  1709. }
  1710. if(!targetExists)
  1711. {
  1712. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1713. }
  1714. }
  1715. break;
  1716. case CSpell::OBSTACLE:
  1717. break;
  1718. }
  1719. return ESpellCastProblem::OK;
  1720. }
  1721. ESpellCastProblem::ESpellCastProblem BattleInfo::battleCanCastThisSpellHere( int player, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest ) const
  1722. {
  1723. ESpellCastProblem::ESpellCastProblem moreGeneralProblem = battleCanCastThisSpell(player, spell, mode);
  1724. if(moreGeneralProblem != ESpellCastProblem::OK)
  1725. return moreGeneralProblem;
  1726. if(spell->getTargetType() == CSpell::OBSTACLE && !isObstacleOnTile(dest))
  1727. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1728. //get dead stack if we cast resurrection or animate dead
  1729. const CStack *deadStack = getStackIf([dest](const CStack *s) { return !s->alive() && s->position == dest; });
  1730. const CStack *aliveStack = getStackIf([dest](const CStack *s) { return s->alive() && s->position == dest; });
  1731. if(spell->isRisingSpell())
  1732. {
  1733. if(!deadStack || aliveStack)
  1734. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1735. if(spell->id == Spells::ANIMATE_DEAD && !deadStack->hasBonusOfType(Bonus::UNDEAD))
  1736. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1737. if(deadStack->owner != player) //you can resurrect only your own stacks
  1738. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1739. }
  1740. else if(spell->getTargetType() == CSpell::CREATURE || spell->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  1741. {
  1742. if(!aliveStack)
  1743. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1744. if(spell->isNegative() && aliveStack->owner == player)
  1745. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1746. if(spell->isPositive() && aliveStack->owner != player)
  1747. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1748. }
  1749. if (mode != ECastingMode::CREATURE_ACTIVE_CASTING && mode != ECastingMode::ENCHANTER_CASTING)
  1750. return battleIsImmune(getHero(player), spell, mode, dest);
  1751. else
  1752. return battleIsImmune(NULL, spell, mode, dest);
  1753. }
  1754. TSpell BattleInfo::getRandomBeneficialSpell(const CStack * subject) const
  1755. {
  1756. std::vector<TSpell> possibleSpells;
  1757. CSpell * spell;
  1758. for (int i = 0; i < GameConstants::SPELLS_QUANTITY; ++i) //should not use future spells added by mods
  1759. {
  1760. spell = VLC->spellh->spells[i];
  1761. if (spell->isPositive()) //only positive
  1762. {
  1763. if (subject->hasBonusFrom(Bonus::SPELL_EFFECT, i) ||
  1764. battleCanCastThisSpellHere(subject->owner, spell, ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
  1765. continue;
  1766. switch (i)
  1767. {
  1768. case Spells::SHIELD:
  1769. case Spells::FIRE_SHIELD: // not if all enemy units are shooters
  1770. {
  1771. bool walkerPresent = false;
  1772. BOOST_FOREACH (CStack * stack, stacks)
  1773. {
  1774. if ((stack->owner != subject->owner) && !stack->shots)
  1775. {
  1776. walkerPresent = true;
  1777. break;
  1778. }
  1779. }
  1780. if (!walkerPresent)
  1781. continue;
  1782. }
  1783. break;
  1784. case Spells::AIR_SHIELD: //only against active shooters
  1785. {
  1786. bool shooterPresent = false;
  1787. BOOST_FOREACH (CStack * stack, stacks)
  1788. {
  1789. if ((stack->owner != subject->owner) && stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots)
  1790. {
  1791. shooterPresent = true;
  1792. break;
  1793. }
  1794. }
  1795. if (!shooterPresent)
  1796. continue;
  1797. break;
  1798. }
  1799. case Spells::ANTI_MAGIC:
  1800. case Spells::MAGIC_MIRROR:
  1801. {
  1802. if (!heroes[whatSide(theOtherPlayer(subject->owner))]) //only if there is enemy hero
  1803. continue;
  1804. }
  1805. break;
  1806. case Spells::CURE: //only damaged units - what about affected by curse?
  1807. {
  1808. if (subject->firstHPleft >= subject->MaxHealth())
  1809. continue;
  1810. }
  1811. break;
  1812. case Spells::BLOODLUST:
  1813. {
  1814. if (subject->shots) //if can shoot - only if enemy uits are adjacent
  1815. continue;
  1816. }
  1817. break;
  1818. case Spells::PRECISION:
  1819. {
  1820. if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
  1821. continue;
  1822. }
  1823. break;
  1824. case Spells::SLAYER://only if monsters are present
  1825. {
  1826. bool monsterPresent = false;
  1827. BOOST_FOREACH (CStack * stack, stacks)
  1828. {
  1829. if ((stack->owner != subject->owner) &&
  1830. (stack->hasBonus(Selector::type(Bonus::KING1) || Selector::type(Bonus::KING2) || Selector::type(Bonus::KING3))))
  1831. {
  1832. monsterPresent = true;
  1833. break;
  1834. }
  1835. }
  1836. if (!monsterPresent)
  1837. continue;
  1838. }
  1839. break;
  1840. case Spells::CLONE: //not allowed
  1841. continue;
  1842. break;
  1843. }
  1844. possibleSpells.push_back(i);
  1845. }
  1846. }
  1847. if (possibleSpells.size())
  1848. return possibleSpells[ran() % possibleSpells.size()];
  1849. else
  1850. return -1;
  1851. }
  1852. TSpell BattleInfo::getRandomCastedSpell(const CStack * caster) const
  1853. {
  1854. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1855. if (!bl->size())
  1856. return -1;
  1857. int totalWeight = 0;
  1858. BOOST_FOREACH(Bonus * b, *bl)
  1859. {
  1860. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1861. }
  1862. int randomPos = ran() % totalWeight;
  1863. BOOST_FOREACH(Bonus * b, *bl)
  1864. {
  1865. randomPos -= std::max(b->additionalInfo, 1);
  1866. if(randomPos < 0)
  1867. {
  1868. return b->subtype;
  1869. }
  1870. }
  1871. return -1;
  1872. }
  1873. const CGHeroInstance * BattleInfo::getHero( int player ) const
  1874. {
  1875. assert(sides[0] == player || sides[1] == player);
  1876. if(heroes[0] && heroes[0]->getOwner() == player)
  1877. return heroes[0];
  1878. return heroes[1];
  1879. }
  1880. bool NegateRemover(const Bonus* b)
  1881. {
  1882. return b->source == Bonus::CREATURE_ABILITY;
  1883. }
  1884. bool BattleInfo::battleTestElementalImmunity(const CStack * subject, const CSpell * spell, Bonus::BonusType element, bool damageSpell) const //helper for battleisImmune
  1885. {
  1886. if (!spell->isPositive()) //negative or indifferent
  1887. {
  1888. if ((damageSpell && subject->hasBonusOfType(element, 2)) || subject->hasBonusOfType(element, 1))
  1889. return true;
  1890. }
  1891. else if (spell->isPositive()) //positive
  1892. {
  1893. if (subject->hasBonusOfType(element, 0)) //must be immune to all spells
  1894. return true;
  1895. }
  1896. return false;
  1897. }
  1898. ESpellCastProblem::ESpellCastProblem BattleInfo::battleIsImmune(const CGHeroInstance * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const
  1899. {
  1900. const CStack * subject;
  1901. bool risingSpell = vstd::contains(VLC->spellh->risingSpells, spell->id);
  1902. if (risingSpell)
  1903. subject = getStackT(dest, false); //including dead stacks
  1904. else
  1905. subject = getStackT(dest, true); //only alive
  1906. if(subject)
  1907. {
  1908. if (spell->isPositive() && subject->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  1909. return ESpellCastProblem::OK;
  1910. switch (spell->id) //TODO: more general logic for new spells?
  1911. {
  1912. case Spells::DESTROY_UNDEAD:
  1913. if (!subject->hasBonusOfType(Bonus::UNDEAD))
  1914. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1915. break;
  1916. case Spells::DEATH_RIPPLE:
  1917. if (subject->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1918. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL; //don't break here - undeads and war machines are immune, non-living are not
  1919. case Spells::BLESS:
  1920. case Spells::CURSE: //undeads are immune to bless & curse
  1921. if (subject->hasBonusOfType(Bonus::UNDEAD))
  1922. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1923. break;
  1924. case Spells::HASTE:
  1925. case Spells::SLOW:
  1926. case Spells::TELEPORT:
  1927. case Spells::CLONE:
  1928. if (subject->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1929. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL; //war machines are immune to some spells than involve movement
  1930. if (spell->id == Spells::CLONE && caster) //TODO: how about stacks casting Clone?
  1931. {
  1932. if (vstd::contains(subject->state, EBattleStackState::CLONED))
  1933. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL; //can't clone already cloned creature
  1934. int maxLevel = (std::max(caster->getSpellSchoolLevel(spell), (ui8)1) + 4);
  1935. int creLevel = subject->getCreature()->level;
  1936. if (maxLevel < creLevel) //tier 1-5 for basic, 1-6 for advanced, 1-7 for expert
  1937. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1938. }
  1939. break;
  1940. case Spells::FORGETFULNESS:
  1941. if (!subject->hasBonusOfType(Bonus::SHOOTER))
  1942. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1943. break;
  1944. case Spells::DISPEL_HELPFUL_SPELLS:
  1945. {
  1946. TBonusListPtr spellBon = subject->getSpellBonuses();
  1947. bool hasPositiveSpell = false;
  1948. BOOST_FOREACH(const Bonus * b, *spellBon)
  1949. {
  1950. if(VLC->spellh->spells[b->sid]->isPositive())
  1951. {
  1952. hasPositiveSpell = true;
  1953. break;
  1954. }
  1955. }
  1956. if(!hasPositiveSpell)
  1957. {
  1958. return ESpellCastProblem::NO_SPELLS_TO_DISPEL;
  1959. }
  1960. }
  1961. break;
  1962. }
  1963. bool damageSpell = (vstd::contains(VLC->spellh->damageSpells, spell->id));
  1964. if (damageSpell && subject->hasBonusOfType(Bonus::DIRECT_DAMAGE_IMMUNITY))
  1965. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1966. if (spell->fire)
  1967. {
  1968. if (battleTestElementalImmunity(subject, spell, Bonus::FIRE_IMMUNITY, damageSpell))
  1969. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1970. }
  1971. if (spell->water)
  1972. {
  1973. if (battleTestElementalImmunity(subject, spell, Bonus::WATER_IMMUNITY, damageSpell))
  1974. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1975. }
  1976. if (spell->earth)
  1977. {
  1978. if (battleTestElementalImmunity(subject, spell, Bonus::EARTH_IMMUNITY, damageSpell))
  1979. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1980. }
  1981. if (spell->air)
  1982. {
  1983. if (battleTestElementalImmunity(subject, spell, Bonus::AIR_IMMUNITY, damageSpell))
  1984. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1985. }
  1986. if (vstd::contains(VLC->spellh->mindSpells, spell->id))
  1987. {
  1988. if (subject->hasBonusOfType(Bonus::MIND_IMMUNITY))
  1989. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1990. }
  1991. if (risingSpell)
  1992. {
  1993. if (subject->count >= subject->baseAmount) //TODO: calculate potential hp raised
  1994. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1995. }
  1996. TBonusListPtr immunities = subject->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  1997. if(subject->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES))
  1998. {
  1999. //std::remove_if(immunities->begin(), immunities->end(), NegateRemover);
  2000. immunities->remove_if(NegateRemover);
  2001. }
  2002. if(subject->hasBonusOfType(Bonus::SPELL_IMMUNITY, spell->id) ||
  2003. ( immunities->size() > 0 && immunities->totalValue() >= spell->level && spell->level))
  2004. {
  2005. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  2006. }
  2007. }
  2008. else //no target stack on this tile
  2009. {
  2010. if(spell->getTargetType() == CSpell::CREATURE ||
  2011. (spell->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE && mode == ECastingMode::HERO_CASTING && caster && caster->getSpellSchoolLevel(spell) < 3))
  2012. {
  2013. return ESpellCastProblem::WRONG_SPELL_TARGET;
  2014. }
  2015. }
  2016. return ESpellCastProblem::OK;
  2017. }
  2018. std::vector<ui32> BattleInfo::calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures, int casterSideOwner, ECastingMode::ECastingMode mode, int usedSpellPower, int spellLevel) const
  2019. {
  2020. std::vector<ui32> ret;
  2021. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2022. {
  2023. if(battleIsImmune(caster, sp, mode, (*it)->position) != ESpellCastProblem::OK)
  2024. {
  2025. ret.push_back((*it)->ID);
  2026. continue;
  2027. }
  2028. //non-negative spells on friendly stacks should always succeed, unless immune
  2029. if(!sp->isNegative() && (*it)->owner == casterSideOwner)
  2030. continue;
  2031. /*
  2032. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  2033. if((*it)->owner == casterSideOwner)
  2034. bonusHero = caster;
  2035. else
  2036. bonusHero = hero2;*/
  2037. int prob = (*it)->magicResistance(); //probability of resistance in %
  2038. if(prob > 100) prob = 100;
  2039. if(rand()%100 < prob) //immunity from resistance
  2040. ret.push_back((*it)->ID);
  2041. }
  2042. if(sp->id == 60) //hypnotize
  2043. {
  2044. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2045. {
  2046. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2047. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  2048. >
  2049. usedSpellPower * 25 + sp->powers[spellLevel]
  2050. )
  2051. {
  2052. ret.push_back((*it)->ID);
  2053. }
  2054. }
  2055. }
  2056. return ret;
  2057. }
  2058. int BattleInfo::getSurrenderingCost(int player) const
  2059. {
  2060. if(!battleCanFlee(player)) //to surrender, conditions of fleeing must be fulfilled
  2061. return -1;
  2062. if(!getHero(theOtherPlayer(player))) //additionally, there must be an enemy hero
  2063. return -2;
  2064. int ret = 0;
  2065. double discount = 0;
  2066. BOOST_FOREACH(const CStack *s, stacks)
  2067. if(s->owner == player && s->base) //we pay for our stack that comes from our army (the last condition eliminates summoned cres and war machines)
  2068. ret += s->getCreature()->cost[Res::GOLD] * s->count;
  2069. if(const CGHeroInstance *h = getHero(player))
  2070. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  2071. ret *= (100.0 - discount) / 100.0;
  2072. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  2073. return ret;
  2074. }
  2075. int BattleInfo::theOtherPlayer(int player) const
  2076. {
  2077. return sides[!whatSide(player)];
  2078. }
  2079. ui8 BattleInfo::whatSide(int player) const
  2080. {
  2081. for(int i = 0; i < ARRAY_COUNT(sides); i++)
  2082. if(sides[i] == player)
  2083. return i;
  2084. tlog1 << "BattleInfo::whatSide: Player " << player << " is not in battle!\n";
  2085. return -1;
  2086. }
  2087. int BattleInfo::getIdForNewStack() const
  2088. {
  2089. if(stacks.size())
  2090. {
  2091. //stacks vector may be sorted not by ID and they may be not contiguous -> find stack with max ID
  2092. auto highestIDStack = *std::max_element(stacks.begin(), stacks.end(),
  2093. [](const CStack *a, const CStack *b) { return a->ID < b->ID; });
  2094. return highestIDStack->ID + 1;
  2095. }
  2096. return 0;
  2097. }
  2098. bool BattleInfo::isObstacleOnTile(BattleHex tile) const
  2099. {
  2100. std::set<BattleHex> coveredHexes;
  2101. BOOST_FOREACH(const CObstacleInstance &obs, obstacles)
  2102. {
  2103. std::vector<BattleHex> blocked = VLC->heroh->obstacles.find(obs.ID)->second.getBlocked(obs.pos);
  2104. for(size_t w = 0; w < blocked.size(); ++w)
  2105. coveredHexes.insert(blocked[w]);
  2106. }
  2107. return vstd::contains(coveredHexes, tile);
  2108. }
  2109. const CStack * BattleInfo::getStackIf(boost::function<bool(const CStack*)> pred) const
  2110. {
  2111. auto stackItr = range::find_if(stacks, pred);
  2112. return stackItr == stacks.end()
  2113. ? NULL
  2114. : *stackItr;
  2115. }
  2116. CStack::CStack(const CStackInstance *Base, int O, int I, bool AO, int S)
  2117. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  2118. counterAttacks(1)
  2119. {
  2120. assert(base);
  2121. type = base->type;
  2122. count = baseAmount = base->count;
  2123. setNodeType(STACK_BATTLE);
  2124. }
  2125. CStack::CStack()
  2126. {
  2127. init();
  2128. setNodeType(STACK_BATTLE);
  2129. }
  2130. CStack::CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S)
  2131. : base(NULL), ID(I), owner(O), slot(S), attackerOwned(AO), counterAttacks(1)
  2132. {
  2133. type = stack->type;
  2134. count = baseAmount = stack->count;
  2135. setNodeType(STACK_BATTLE);
  2136. }
  2137. void CStack::init()
  2138. {
  2139. base = NULL;
  2140. type = NULL;
  2141. ID = -1;
  2142. count = baseAmount = -1;
  2143. firstHPleft = -1;
  2144. owner = 255;
  2145. slot = 255;
  2146. attackerOwned = false;
  2147. position = BattleHex();
  2148. counterAttacks = -1;
  2149. }
  2150. void CStack::postInit()
  2151. {
  2152. assert(type);
  2153. assert(getParentNodes().size());
  2154. firstHPleft = MaxHealth();
  2155. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  2156. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  2157. casts = valOfBonuses(Bonus::CASTS); //TODO: set them in cr_abils.txt
  2158. state.insert(EBattleStackState::ALIVE); //alive state indication
  2159. }
  2160. ui32 CStack::Speed( int turn /*= 0*/ , bool useBind /* = false*/) const
  2161. {
  2162. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  2163. return 0;
  2164. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  2165. int percentBonus = 0;
  2166. BOOST_FOREACH(const Bonus *b, getBonusList())
  2167. {
  2168. if(b->type == Bonus::STACKS_SPEED)
  2169. {
  2170. percentBonus += b->additionalInfo;
  2171. }
  2172. }
  2173. speed = ((100 + percentBonus) * speed)/100;
  2174. //bind effect check - doesn't influence stack initiative
  2175. if (useBind && getEffect(72))
  2176. {
  2177. return 0;
  2178. }
  2179. return speed;
  2180. }
  2181. si32 CStack::magicResistance() const
  2182. {
  2183. si32 magicResistance;
  2184. if (base) //TODO: make war machines receive aura of magic resistance
  2185. {
  2186. magicResistance = base->magicResistance();
  2187. int auraBonus = 0;
  2188. BOOST_FOREACH (CStack * stack, base->armyObj->battle->getAdjacentCreatures(this))
  2189. {
  2190. if (stack->owner == owner)
  2191. {
  2192. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  2193. }
  2194. }
  2195. magicResistance += auraBonus;
  2196. vstd::amin (magicResistance, 100);
  2197. }
  2198. else
  2199. magicResistance = type->magicResistance();
  2200. return magicResistance;
  2201. }
  2202. const Bonus * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  2203. {
  2204. BOOST_FOREACH(Bonus *it, getBonusList())
  2205. {
  2206. if(it->source == Bonus::SPELL_EFFECT && it->sid == id)
  2207. {
  2208. if(!turn || it->turnsRemain > turn)
  2209. return &(*it);
  2210. }
  2211. }
  2212. return NULL;
  2213. }
  2214. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  2215. {
  2216. si32 power = VLC->spellh->spells[sse.sid]->powers[sse.val];
  2217. switch(sse.sid)
  2218. {
  2219. case 27: //shield
  2220. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  2221. sf.back().sid = sse.sid;
  2222. break;
  2223. case 28: //air shield
  2224. sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  2225. sf.back().sid = sse.sid;
  2226. break;
  2227. case 29: //fire shield
  2228. sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  2229. sf.back().sid = sse.sid;
  2230. break;
  2231. case 30: //protection from air
  2232. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  2233. sf.back().sid = sse.sid;
  2234. break;
  2235. case 31: //protection from fire
  2236. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  2237. sf.back().sid = sse.sid;
  2238. break;
  2239. case 32: //protection from water
  2240. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  2241. sf.back().sid = sse.sid;
  2242. break;
  2243. case 33: //protection from earth
  2244. sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  2245. sf.back().sid = sse.sid;
  2246. break;
  2247. case 34: //anti-magic
  2248. sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, GameConstants::SPELL_LEVELS, power - 1, sse.turnsRemain));
  2249. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2250. sf.back().sid = sse.sid;
  2251. break;
  2252. case 36: //magic mirror
  2253. sf.push_back(featureGenerator(Bonus::MAGIC_MIRROR, -1, power, sse.turnsRemain));
  2254. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2255. sf.back().sid = sse.sid;
  2256. case 41: //bless
  2257. sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  2258. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2259. sf.back().sid = sse.sid;
  2260. break;
  2261. case 42: //curse
  2262. sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  2263. sf.back().valType = Bonus::INDEPENDENT_MAX;
  2264. sf.back().sid = sse.sid;
  2265. break;
  2266. case 43: //bloodlust
  2267. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  2268. sf.back().sid = sse.sid;
  2269. break;
  2270. case 44: //precision
  2271. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  2272. sf.back().sid = sse.sid;
  2273. break;
  2274. case 45: //weakness
  2275. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  2276. sf.back().sid = sse.sid;
  2277. break;
  2278. case 46: //stone skin
  2279. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  2280. sf.back().sid = sse.sid;
  2281. break;
  2282. case 47: //disrupting ray
  2283. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  2284. sf.back().sid = sse.sid;
  2285. sf.back().valType = Bonus::ADDITIVE_VALUE;
  2286. break;
  2287. case 48: //prayer
  2288. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  2289. sf.back().sid = sse.sid;
  2290. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  2291. sf.back().sid = sse.sid;
  2292. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  2293. sf.back().sid = sse.sid;
  2294. break;
  2295. case 49: //mirth
  2296. sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  2297. sf.back().sid = sse.sid;
  2298. break;
  2299. case 50: //sorrow
  2300. sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  2301. sf.back().sid = sse.sid;
  2302. break;
  2303. case 51: //fortune
  2304. sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  2305. sf.back().sid = sse.sid;
  2306. break;
  2307. case 52: //misfortune
  2308. sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  2309. sf.back().sid = sse.sid;
  2310. break;
  2311. case 53: //haste
  2312. sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  2313. sf.back().sid = sse.sid;
  2314. break;
  2315. case 54: //slow
  2316. sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  2317. sf.back().sid = sse.sid;
  2318. break;
  2319. case 55: //slayer
  2320. sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  2321. sf.back().sid = sse.sid;
  2322. break;
  2323. case 56: //frenzy
  2324. sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  2325. sf.back().sid = sse.sid;
  2326. break;
  2327. case 58: //counterstrike
  2328. sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  2329. sf.back().sid = sse.sid;
  2330. break;
  2331. case 59: //bersek
  2332. sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  2333. sf.back().sid = sse.sid;
  2334. break;
  2335. case 60: //hypnotize
  2336. sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  2337. sf.back().sid = sse.sid;
  2338. break;
  2339. case 61: //forgetfulness
  2340. sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  2341. sf.back().sid = sse.sid;
  2342. break;
  2343. case Spells::BLIND: //blind
  2344. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  2345. sf.back().sid = sse.sid;
  2346. sf.push_back(makeFeatureVal(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  2347. sf.back().sid = sse.sid;
  2348. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  2349. sf.back().sid = sse.sid;
  2350. break;
  2351. case Spells::STONE_GAZE: //Stone Gaze
  2352. case Spells::PARALYZE: //Paralyze
  2353. sf.push_back(makeFeatureVal(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, sse.sid, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  2354. sf.back().sid = sse.sid;
  2355. sf.push_back(makeFeatureVal(Bonus::NO_RETALIATION, Bonus::UNITL_BEING_ATTACKED, 0, 0, Bonus::SPELL_EFFECT, 0)); // don't retaliate after basilisk / unicorn attack
  2356. sf.back().sid = sse.sid;
  2357. break;
  2358. case 71: //Poison
  2359. sf.push_back(featureGeneratorVT(Bonus::POISON, 0, 30, sse.turnsRemain, Bonus::INDEPENDENT_MAX)); //max hp penalty from this source
  2360. sf.back().sid = sse.sid;
  2361. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -10, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  2362. sf.back().sid = sse.sid;
  2363. break;
  2364. case 72: //Bind
  2365. sf.push_back(featureGenerator(Bonus::BIND_EFFECT, 0, 0, 1)); //marker
  2366. sf.back().duration = Bonus::PERMANENT;
  2367. sf.back().sid = sse.sid;
  2368. break;
  2369. case 73: //Disease
  2370. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -2 , sse.turnsRemain));
  2371. sf.back().sid = sse.sid;
  2372. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -2 , sse.turnsRemain));
  2373. sf.back().sid = sse.sid;
  2374. break;
  2375. case 75: //Age
  2376. sf.push_back(featureGeneratorVT(Bonus::STACK_HEALTH, 0, -50, sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  2377. sf.back().sid = sse.sid;
  2378. break;
  2379. case 80: //Acid Breath
  2380. sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -sse.turnsRemain, 1));
  2381. sf.back().sid = sse.sid;
  2382. sf.back().duration = Bonus::PERMANENT;
  2383. sf.back().valType = Bonus::ADDITIVE_VALUE;
  2384. break;
  2385. }
  2386. }
  2387. ui8 CStack::howManyEffectsSet(ui16 id) const
  2388. {
  2389. ui8 ret = 0;
  2390. BOOST_FOREACH(const Bonus *it, getBonusList())
  2391. if(it->source == Bonus::SPELL_EFFECT && it->sid == id) //effect found
  2392. {
  2393. ++ret;
  2394. }
  2395. return ret;
  2396. }
  2397. bool CStack::willMove(int turn /*= 0*/) const
  2398. {
  2399. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  2400. && !moved(turn)
  2401. && canMove(turn);
  2402. }
  2403. bool CStack::canMove( int turn /*= 0*/ ) const
  2404. {
  2405. return alive()
  2406. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  2407. }
  2408. bool CStack::moved( int turn /*= 0*/ ) const
  2409. {
  2410. if(!turn)
  2411. return vstd::contains(state, EBattleStackState::MOVED);
  2412. else
  2413. return false;
  2414. }
  2415. bool CStack::doubleWide() const
  2416. {
  2417. return getCreature()->doubleWide;
  2418. }
  2419. BattleHex CStack::occupiedHex() const
  2420. {
  2421. if (doubleWide())
  2422. {
  2423. if (attackerOwned)
  2424. return position - 1;
  2425. else
  2426. return position + 1;
  2427. }
  2428. else
  2429. {
  2430. return BattleHex::INVALID;
  2431. }
  2432. }
  2433. std::vector<BattleHex> CStack::getHexes() const
  2434. {
  2435. std::vector<BattleHex> hexes;
  2436. hexes.push_back(BattleHex(position));
  2437. BattleHex occupied = occupiedHex();
  2438. if(occupied.isValid())
  2439. hexes.push_back(occupied);
  2440. return hexes;
  2441. }
  2442. bool CStack::coversPos(BattleHex pos) const
  2443. {
  2444. return vstd::contains(getHexes(), pos);
  2445. }
  2446. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  2447. {
  2448. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  2449. std::vector<BattleHex> hexes;
  2450. if (doubleWide())
  2451. {
  2452. const int WN = GameConstants::BFIELD_WIDTH;
  2453. if(attackerOwned)
  2454. { //position is equal to front hex
  2455. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  2456. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  2457. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  2458. BattleHex::checkAndPush(hex - 2, hexes);
  2459. BattleHex::checkAndPush(hex + 1, hexes);
  2460. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  2461. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  2462. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  2463. }
  2464. else
  2465. {
  2466. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  2467. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  2468. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  2469. BattleHex::checkAndPush(hex + 2, hexes);
  2470. BattleHex::checkAndPush(hex - 1, hexes);
  2471. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  2472. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  2473. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  2474. }
  2475. return hexes;
  2476. }
  2477. else
  2478. {
  2479. return hex.neighbouringTiles();
  2480. }
  2481. }
  2482. std::vector<si32> CStack::activeSpells() const
  2483. {
  2484. std::vector<si32> ret;
  2485. TBonusListPtr spellEffects = getSpellBonuses();
  2486. BOOST_FOREACH(const Bonus *it, *spellEffects)
  2487. {
  2488. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  2489. ret.push_back(it->sid);
  2490. }
  2491. return ret;
  2492. }
  2493. CStack::~CStack()
  2494. {
  2495. detachFromAll();
  2496. }
  2497. const CGHeroInstance * CStack::getMyHero() const
  2498. {
  2499. if(base)
  2500. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  2501. else //we are attached directly?
  2502. BOOST_FOREACH(const CBonusSystemNode *n, getParentNodes())
  2503. if(n->getNodeType() == HERO)
  2504. dynamic_cast<const CGHeroInstance *>(n);
  2505. return NULL;
  2506. }
  2507. std::string CStack::nodeName() const
  2508. {
  2509. std::ostringstream oss;
  2510. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  2511. if(type)
  2512. oss << type->namePl;
  2513. else
  2514. oss << "[UNDEFINED TYPE]";
  2515. oss << " from slot " << (int)slot;
  2516. if(base && base->armyObj)
  2517. oss << " of armyobj=" << base->armyObj->id;
  2518. return oss.str();
  2519. }
  2520. void CStack::prepareAttacked(BattleStackAttacked &bsa) const
  2521. {
  2522. bsa.killedAmount = bsa.damageAmount / MaxHealth();
  2523. unsigned damageFirst = bsa.damageAmount % MaxHealth();
  2524. if (bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  2525. {
  2526. bsa.killedAmount = count;
  2527. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  2528. return; // no rebirth I believe
  2529. }
  2530. if( firstHPleft <= damageFirst )
  2531. {
  2532. bsa.killedAmount++;
  2533. bsa.newHP = firstHPleft + MaxHealth() - damageFirst;
  2534. }
  2535. else
  2536. {
  2537. bsa.newHP = firstHPleft - damageFirst;
  2538. }
  2539. if(count <= bsa.killedAmount) //stack killed
  2540. {
  2541. bsa.newAmount = 0;
  2542. bsa.flags |= BattleStackAttacked::KILLED;
  2543. bsa.killedAmount = count; //we cannot kill more creatures than we have
  2544. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  2545. if (resurrectFactor > 0 && casts) //there must be casts left
  2546. {
  2547. int resurrectedCount = base->count * resurrectFactor / 100;
  2548. if (resurrectedCount)
  2549. resurrectedCount += ((base->count * resurrectFactor / 100.0 - resurrectedCount) > ran()%100 / 100.0) ? 1 : 0; //last stack has proportional chance to rebirth
  2550. else //only one unit
  2551. resurrectedCount += ((base->count * resurrectFactor / 100.0) > ran()%100 / 100.0) ? 1 : 0;
  2552. if (hasBonusOfType(Bonus::REBIRTH, 1))
  2553. vstd::amax (resurrectedCount, 1); //resurrect at least one Sacred Phoenix
  2554. if (resurrectedCount)
  2555. {
  2556. bsa.flags |= BattleStackAttacked::REBIRTH;
  2557. bsa.newAmount = resurrectedCount; //risky?
  2558. bsa.newHP = MaxHealth(); //resore full health
  2559. }
  2560. }
  2561. }
  2562. else
  2563. {
  2564. bsa.newAmount = count - bsa.killedAmount;
  2565. }
  2566. }
  2567. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  2568. {
  2569. if (!attackerPos.isValid())
  2570. {
  2571. attackerPos = attacker->position;
  2572. }
  2573. if (!defenderPos.isValid())
  2574. {
  2575. defenderPos = defender->position;
  2576. }
  2577. return
  2578. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  2579. || (attacker->doubleWide() //back <=> front
  2580. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  2581. || (defender->doubleWide() //front <=> back
  2582. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  2583. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  2584. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  2585. }
  2586. bool CStack::ableToRetaliate() const
  2587. {
  2588. return alive()
  2589. && (counterAttacks > 0 || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  2590. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  2591. && !hasBonusOfType(Bonus::HYPNOTIZED)
  2592. && !hasBonusOfType(Bonus::NO_RETALIATION);
  2593. }
  2594. std::string CStack::getName() const
  2595. {
  2596. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  2597. }
  2598. bool CStack::isValidTarget(bool allowDead/* = false*/) const /*alive non-turret stacks (can be attacked or be object of magic effect) */
  2599. {
  2600. return (alive() || allowDead) && position.isValid();
  2601. }
  2602. bool CStack::canBeHealed() const
  2603. {
  2604. return firstHPleft != MaxHealth()
  2605. && alive()
  2606. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  2607. }
  2608. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  2609. {
  2610. switch(phase)
  2611. {
  2612. case 0: //catapult moves after turrets
  2613. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  2614. case 1: //fastest first, upper slot first
  2615. {
  2616. int as = a->Speed(turn), bs = b->Speed(turn);
  2617. if(as != bs)
  2618. return as > bs;
  2619. else
  2620. return a->slot < b->slot;
  2621. }
  2622. case 2: //fastest last, upper slot first
  2623. //TODO: should be replaced with order of receiving morale!
  2624. case 3: //fastest last, upper slot first
  2625. {
  2626. int as = a->Speed(turn), bs = b->Speed(turn);
  2627. if(as != bs)
  2628. return as < bs;
  2629. else
  2630. return a->slot < b->slot;
  2631. }
  2632. default:
  2633. assert(0);
  2634. return false;
  2635. }
  2636. }
  2637. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  2638. {
  2639. phase = Phase;
  2640. turn = Turn;
  2641. }