BattleState.cpp 75 KB

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