BattleState.cpp 80 KB

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