BattleState.cpp 71 KB

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