BattleState.cpp 72 KB

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