BattleState.cpp 81 KB

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