BattleState.cpp 77 KB

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