BattleState.cpp 75 KB

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