BattleState.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  1. #define VCMI_DLL
  2. #include "BattleState.h"
  3. #include <fstream>
  4. #include <queue>
  5. #include <algorithm>
  6. #include <numeric>
  7. #include <sstream>
  8. #include <boost/foreach.hpp>
  9. #include <boost/assign/list_of.hpp>
  10. #include "VCMI_Lib.h"
  11. #include "CObjectHandler.h"
  12. #include "CHeroHandler.h"
  13. #include "CCreatureHandler.h"
  14. #include "CSpellHandler.h"
  15. #include "CTownHandler.h"
  16. /*
  17. * BattleState.h, part of VCMI engine
  18. *
  19. * Authors: listed in file AUTHORS in main folder
  20. *
  21. * License: GNU General Public License v2.0 or later
  22. * Full text of license available in license.txt file, in main folder
  23. *
  24. */
  25. const CStack * BattleInfo::getNextStack() const
  26. {
  27. std::vector<const CStack *> hlp;
  28. getStackQueue(hlp, 1, -1);
  29. if(hlp.size())
  30. return hlp[0];
  31. else
  32. return NULL;
  33. }
  34. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  35. {
  36. const CStack *ret = NULL;
  37. unsigned i, //fastest stack
  38. j; //fastest stack of the other side
  39. for(i = 0; i < st.size(); i++)
  40. if(st[i])
  41. break;
  42. //no stacks left
  43. if(i == st.size())
  44. return NULL;
  45. const CStack *fastest = st[i], *other = NULL;
  46. int bestSpeed = fastest->Speed(turn);
  47. if(fastest->attackerOwned != curside)
  48. {
  49. ret = fastest;
  50. }
  51. else
  52. {
  53. for(j = i + 1; j < st.size(); j++)
  54. {
  55. if(!st[j]) continue;
  56. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  57. break;
  58. }
  59. if(j >= st.size())
  60. {
  61. ret = fastest;
  62. }
  63. else
  64. {
  65. other = st[j];
  66. if(other->Speed(turn) != bestSpeed)
  67. ret = fastest;
  68. else
  69. ret = other;
  70. }
  71. }
  72. assert(ret);
  73. if(ret == fastest)
  74. st[i] = NULL;
  75. else
  76. st[j] = NULL;
  77. curside = ret->attackerOwned;
  78. return ret;
  79. }
  80. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  81. {
  82. for(unsigned int g=0; g<stacks.size(); ++g)
  83. {
  84. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  85. return stacks[g];
  86. }
  87. return NULL;
  88. }
  89. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  90. {
  91. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  92. }
  93. CStack * BattleInfo::getStackT(THex tileID, bool onlyAlive)
  94. {
  95. for(unsigned int g=0; g<stacks.size(); ++g)
  96. {
  97. if(stacks[g]->position == tileID
  98. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  99. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  100. {
  101. if(!onlyAlive || stacks[g]->alive())
  102. {
  103. return stacks[g];
  104. }
  105. }
  106. }
  107. return NULL;
  108. }
  109. const CStack * BattleInfo::getStackT(THex tileID, bool onlyAlive) const
  110. {
  111. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  112. }
  113. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  114. {
  115. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  116. //removing accessibility for side columns of hexes
  117. for(int v = 0; v < BFIELD_SIZE; ++v)
  118. {
  119. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  120. accessibility[v] = false;
  121. }
  122. for(unsigned int g=0; g<stacks.size(); ++g)
  123. {
  124. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  125. continue;
  126. accessibility[stacks[g]->position] = false;
  127. if(stacks[g]->doubleWide()) //if it's a double hex creature
  128. {
  129. if(stacks[g]->attackerOwned)
  130. accessibility[stacks[g]->position-1] = false;
  131. else
  132. accessibility[stacks[g]->position+1] = false;
  133. }
  134. }
  135. //obstacles
  136. for(unsigned int b=0; b<obstacles.size(); ++b)
  137. {
  138. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  139. for(unsigned int c=0; c<blocked.size(); ++c)
  140. {
  141. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  142. accessibility[blocked[c]] = false;
  143. }
  144. }
  145. //walls
  146. if(siege > 0)
  147. {
  148. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  149. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  150. {
  151. accessibility[permanentlyLocked[b]] = false;
  152. }
  153. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  154. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  155. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  156. {
  157. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  158. {
  159. accessibility[lockedIfNotDestroyed[b].second] = false;
  160. }
  161. }
  162. //gate
  163. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  164. {
  165. accessibility[95] = accessibility[96] = false; //block gate's hexes
  166. }
  167. }
  168. //occupyability
  169. if(addOccupiable && twoHex)
  170. {
  171. std::set<int> rem; //tiles to unlock
  172. for(int h=0; h<BFIELD_HEIGHT; ++h)
  173. {
  174. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  175. {
  176. int hex = h * BFIELD_WIDTH + w;
  177. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  178. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  179. )
  180. rem.insert(hex);
  181. }
  182. }
  183. occupyable = rem;
  184. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  185. {
  186. accessibility[*it] = true;
  187. }*/
  188. }
  189. }
  190. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  191. {
  192. if(flying && !lastPos)
  193. return true;
  194. if(twoHex)
  195. {
  196. //if given hex is accessible and appropriate adjacent one is free too
  197. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  198. }
  199. else
  200. {
  201. return accessibility[hex];
  202. }
  203. }
  204. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  205. {
  206. //inits
  207. for(int b=0; b<BFIELD_SIZE; ++b)
  208. predecessor[b] = -1;
  209. for(int g=0; g<BFIELD_SIZE; ++g)
  210. dists[g] = 100000000;
  211. std::queue< std::pair<int, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  212. hexq.push(std::make_pair(start, true));
  213. dists[hexq.front().first] = 0;
  214. int curNext = -1; //for bfs loop only (helper var)
  215. while(!hexq.empty()) //bfs loop
  216. {
  217. std::pair<int, bool> curHex = hexq.front();
  218. std::vector<int> neighbours = neighbouringTiles(curHex.first);
  219. hexq.pop();
  220. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  221. {
  222. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  223. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  224. if( dists[curHex.first]+1 >= dists[curNext] )
  225. continue;
  226. if(accessible && curHex.second)
  227. {
  228. hexq.push(std::make_pair(curNext, true));
  229. dists[curNext] = dists[curHex.first] + 1;
  230. }
  231. else if(fillPredecessors && !(accessible && !curHex.second))
  232. {
  233. hexq.push(std::make_pair(curNext, false));
  234. dists[curNext] = dists[curHex.first] + 1;
  235. }
  236. predecessor[curNext] = curHex.first;
  237. }
  238. }
  239. };
  240. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  241. {
  242. std::vector<int> ret;
  243. bool ac[BFIELD_SIZE];
  244. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  245. if(s->position < 0) //turrets
  246. return std::vector<int>();
  247. std::set<int> occupyable;
  248. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, addOccupiable, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  249. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  250. makeBFS(s->position, ac, pr, dist, s->doubleWide(), s->attackerOwned, s->hasBonusOfType(Bonus::FLYING), false);
  251. if(s->doubleWide())
  252. {
  253. if(!addOccupiable)
  254. {
  255. std::vector<int> rem;
  256. for(int b=0; b<BFIELD_SIZE; ++b)
  257. {
  258. //don't take into account most left and most right columns of hexes
  259. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  260. continue;
  261. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  262. {
  263. rem.push_back(b);
  264. }
  265. }
  266. for(unsigned int g=0; g<rem.size(); ++g)
  267. {
  268. ac[rem[g]] = false;
  269. }
  270. //removing accessibility for side hexes
  271. for(int v=0; v<BFIELD_SIZE; ++v)
  272. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  273. ac[v] = false;
  274. }
  275. }
  276. for (int i=0; i < BFIELD_SIZE ; ++i) {
  277. if(
  278. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->doubleWide(), s->attackerOwned, s->hasBonusOfType(Bonus::FLYING), true) ) )//we can reach it
  279. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  280. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  281. )
  282. {
  283. ret.push_back(i);
  284. }
  285. }
  286. return ret;
  287. }
  288. bool BattleInfo::isStackBlocked(int ID)
  289. {
  290. CStack *our = getStack(ID);
  291. if(our->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  292. return false;
  293. for(unsigned int i=0; i<stacks.size();i++)
  294. {
  295. if( !stacks[i]->alive()
  296. || stacks[i]->owner==our->owner
  297. )
  298. continue; //we omit dead and allied stacks
  299. if(stacks[i]->doubleWide())
  300. {
  301. if( mutualPosition(stacks[i]->position, our->position) >= 0
  302. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  303. return true;
  304. }
  305. else
  306. {
  307. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  308. return true;
  309. }
  310. }
  311. return false;
  312. }
  313. signed char BattleInfo::mutualPosition(THex hex1, THex hex2)
  314. {
  315. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  316. return 0;
  317. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  318. return 1;
  319. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  320. return 5;
  321. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  322. return 2;
  323. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  324. return 4;
  325. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  326. return 3;
  327. return -1;
  328. }
  329. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  330. {
  331. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  332. std::vector<int> ret;
  333. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  334. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  335. CHECK_AND_PUSH(hex - 1);
  336. CHECK_AND_PUSH(hex + 1);
  337. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  338. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  339. #undef CHECK_AND_PUSH
  340. return ret;
  341. }
  342. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  343. {
  344. int predecessor[BFIELD_SIZE]; //for getting the Path
  345. int dist[BFIELD_SIZE]; //calculated distances
  346. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  347. if(predecessor[dest] == -1) //cannot reach destination
  348. {
  349. return std::make_pair(std::vector<int>(), 0);
  350. }
  351. //making the Path
  352. std::vector<int> path;
  353. int curElem = dest;
  354. while(curElem != start)
  355. {
  356. path.push_back(curElem);
  357. curElem = predecessor[curElem];
  358. }
  359. return std::make_pair(path, dist[dest]);
  360. }
  361. std::pair<ui32, ui32> BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  362. {
  363. float additiveBonus=1.0f, multBonus=1.0f,
  364. minDmg = attacker->getMinDamage() * attacker->count,
  365. maxDmg = attacker->getMaxDamage() * attacker->count;
  366. if(attacker->getCreature()->idNumber == 149) //arrow turret
  367. {
  368. switch(attacker->position)
  369. {
  370. case -2: //keep
  371. minDmg = 15;
  372. maxDmg = 15;
  373. break;
  374. case -3: case -4: //turrets
  375. minDmg = 7.5f;
  376. maxDmg = 7.5f;
  377. break;
  378. }
  379. }
  380. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->getCreature()->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  381. { //minDmg and maxDmg are multiplied by hero attack + 1
  382. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  383. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  384. }
  385. int attackDefenceDifference = 0;
  386. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  387. {
  388. float multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f;
  389. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  390. }
  391. else
  392. {
  393. attackDefenceDifference = attacker->Attack();
  394. }
  395. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  396. {
  397. float multDefenceReduction = (100.0f - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0f;
  398. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  399. }
  400. else
  401. {
  402. attackDefenceDifference -= defender->Defense();
  403. }
  404. //calculating total attack/defense skills modifier
  405. if(shooting) //precision handling (etc.)
  406. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)).totalValue();
  407. else //bloodlust handling (etc.)
  408. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)).totalValue();
  409. if(attacker->getEffect(55)) //slayer handling
  410. {
  411. std::vector<int> affectedIds;
  412. int spLevel = attacker->getEffect(55)->val;
  413. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  414. {
  415. BOOST_FOREACH(const Bonus *b, VLC->creh->creatures[g]->bonuses)
  416. {
  417. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  418. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  419. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  420. {
  421. affectedIds.push_back(g);
  422. break;
  423. }
  424. }
  425. }
  426. for(unsigned int g=0; g<affectedIds.size(); ++g)
  427. {
  428. if(defender->getCreature()->idNumber == affectedIds[g])
  429. {
  430. attackDefenceDifference += VLC->spellh->spells[55]->powers[attacker->getEffect(55)->val];
  431. break;
  432. }
  433. }
  434. }
  435. //bonus from attack/defense skills
  436. if(attackDefenceDifference < 0) //decreasing dmg
  437. {
  438. float dec = 0.025f * (-attackDefenceDifference);
  439. if(dec > 0.7f)
  440. {
  441. multBonus *= 0.3f; //1.0 - 0.7
  442. }
  443. else
  444. {
  445. multBonus *= 1.0f - dec;
  446. }
  447. }
  448. else //increasing dmg
  449. {
  450. float inc = 0.05f * attackDefenceDifference;
  451. if(inc > 4.0f)
  452. {
  453. additiveBonus += 4.0f;
  454. }
  455. else
  456. {
  457. additiveBonus += inc;
  458. }
  459. }
  460. //applying jousting bonus
  461. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  462. additiveBonus += charge * 0.05f;
  463. //handling secondary abilities and artifacts giving premies to them
  464. if(attackerHero)
  465. {
  466. if(shooting)
  467. {
  468. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  469. }
  470. else
  471. {
  472. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 22) / 100.0f;
  473. }
  474. }
  475. if(defendingHero)
  476. {
  477. multBonus *= (std::max(0, 100-defendingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 23))) / 100.0f;
  478. }
  479. //handling hate effect
  480. if( attacker->hasBonusOfType(Bonus::HATE, defender->getCreature()->idNumber) )
  481. additiveBonus += 0.5f;
  482. //luck bonus
  483. if (lucky)
  484. {
  485. additiveBonus += 1.0f;
  486. }
  487. //handling spell effects
  488. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  489. {
  490. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  491. }
  492. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  493. {
  494. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  495. }
  496. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  497. {
  498. multBonus *= 0.8f * float(VLC->spellh->spells[42]->powers[attacker->getEffect(42)->val]); //the second factor is 1 or 0
  499. }
  500. class HLP
  501. {
  502. public:
  503. static bool hasAdvancedAirShield(const CStack * stack)
  504. {
  505. BOOST_FOREACH(const Bonus *it, stack->bonuses)
  506. {
  507. if (it->source == Bonus::SPELL_EFFECT && it->id == 28 && it->val >= 2)
  508. {
  509. return true;
  510. }
  511. }
  512. return false;
  513. }
  514. };
  515. //wall / distance penalty + advanced air shield
  516. if (shooting && !NBonus::hasOfType(attackerHero, Bonus::NO_SHOTING_PENALTY) && (
  517. hasDistancePenalty(attacker->ID, defender->position) || hasWallPenalty(attacker->ID, defender->position) ||
  518. HLP::hasAdvancedAirShield(defender) )
  519. )
  520. {
  521. multBonus *= 0.5;
  522. }
  523. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  524. {
  525. multBonus *= 0.5;
  526. }
  527. minDmg *= additiveBonus * multBonus;
  528. maxDmg *= additiveBonus * multBonus;
  529. std::pair<ui32, ui32> returnedVal;
  530. if(attacker->getEffect(42)) //curse handling (rest)
  531. {
  532. minDmg -= VLC->spellh->spells[42]->powers[attacker->getEffect(42)->val];
  533. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  534. }
  535. else if(attacker->getEffect(41)) //bless handling
  536. {
  537. maxDmg += VLC->spellh->spells[41]->powers[attacker->getEffect(41)->val];
  538. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  539. }
  540. else
  541. {
  542. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  543. }
  544. //damage cannot be less than 1
  545. amax(returnedVal.first, 1);
  546. amax(returnedVal.second, 1);
  547. return returnedVal;
  548. }
  549. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  550. {
  551. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky);
  552. if(range.first != range.second)
  553. {
  554. int valuesToAverage[10];
  555. int howManyToAv = std::min<ui32>(10, attacker->count);
  556. for (int g=0; g<howManyToAv; ++g)
  557. {
  558. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  559. }
  560. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  561. }
  562. else
  563. return range.first;
  564. }
  565. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  566. {
  567. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  568. {
  569. const CStack * const st = stacks[i];
  570. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  571. amax(killed, 0);
  572. if(killed)
  573. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  574. }
  575. }
  576. std::set<CStack*> BattleInfo::getAttackedCreatures( const CSpell * s, int skillLevel, ui8 attackerOwner, int destinationTile )
  577. {
  578. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  579. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  580. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  581. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  582. {
  583. for(int it=0; it<stacks.size(); ++it)
  584. {
  585. if((s->id == 24 && !stacks[it]->getCreature()->isUndead()) //death ripple
  586. || (s->id == 25 && stacks[it]->getCreature()->isUndead()) //destroy undead
  587. || (s->id == 26) //Armageddon
  588. )
  589. {
  590. if(stacks[it]->alive())
  591. attackedCres.insert(stacks[it]);
  592. }
  593. }
  594. }
  595. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  596. {
  597. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  598. {
  599. CStack * st = getStackT(*it, onlyAlive);
  600. if(st)
  601. attackedCres.insert(st);
  602. }
  603. }
  604. else if(VLC->spellh->spells[s->id]->attributes.find("CREATURE_TARGET_1") != std::string::npos
  605. || VLC->spellh->spells[s->id]->attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  606. {
  607. if(skillLevel < 3) /*not expert */
  608. {
  609. CStack * st = getStackT(destinationTile, onlyAlive);
  610. if(st)
  611. attackedCres.insert(st);
  612. }
  613. else
  614. {
  615. for(int it=0; it<stacks.size(); ++it)
  616. {
  617. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  618. if((VLC->spellh->spells[s->id]->positiveness >= 0 && stacks[it]->owner == attackerOwner)
  619. ||(VLC->spellh->spells[s->id]->positiveness <= 0 && stacks[it]->owner != attackerOwner )
  620. )
  621. {
  622. if(!onlyAlive || stacks[it]->alive())
  623. attackedCres.insert(stacks[it]);
  624. }
  625. }
  626. } //if(caster->getSpellSchoolLevel(s) < 3)
  627. }
  628. else if(VLC->spellh->spells[s->id]->attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  629. {
  630. CStack * st = getStackT(destinationTile, onlyAlive);
  631. if(st)
  632. attackedCres.insert(st);
  633. }
  634. else //custom range from attackedHexes
  635. {
  636. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  637. {
  638. CStack * st = getStackT(*it, onlyAlive);
  639. if(st)
  640. attackedCres.insert(st);
  641. }
  642. }
  643. return attackedCres;
  644. }
  645. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower )
  646. {
  647. if(!caster) //TODO: something better
  648. return std::max(5, usedSpellPower);
  649. switch(spell->id)
  650. {
  651. case 56: //frenzy
  652. return 1;
  653. default: //other spells
  654. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  655. }
  656. }
  657. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, int position) const
  658. {
  659. int owner = attackerOwned ? side1 : side2;
  660. assert(owner >= PLAYER_LIMIT || base.armyObj && base.armyObj->tempOwner == owner);
  661. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  662. ret->position = position;
  663. return ret;
  664. }
  665. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, int stackID, bool attackerOwned, int slot, int position) const
  666. {
  667. int owner = attackerOwned ? side1 : side2;
  668. CStack * ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  669. ret->position = position;
  670. return ret;
  671. }
  672. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  673. {
  674. ui32 ret = caster->getSpellCost(sp);
  675. //checking for friendly stacks reducing cost of the spell and
  676. //enemy stacks increasing it
  677. si32 manaReduction = 0;
  678. si32 manaIncrease = 0;
  679. for(int g=0; g<stacks.size(); ++g)
  680. {
  681. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  682. {
  683. amin(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  684. }
  685. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  686. {
  687. amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  688. }
  689. }
  690. return ret + manaReduction + manaIncrease;
  691. }
  692. int BattleInfo::hexToWallPart(int hex) const
  693. {
  694. if(siege == 0) //there is no battle!
  695. return -1;
  696. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  697. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  698. 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)};
  699. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  700. {
  701. if(attackable[g].first == hex)
  702. return attackable[g].second;
  703. }
  704. return -1; //not found!
  705. }
  706. int BattleInfo::lineToWallHex( int line ) const
  707. {
  708. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  709. return lineToHex[line];
  710. }
  711. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  712. {
  713. bool ac[BFIELD_SIZE];
  714. std::set<int> occupyable;
  715. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest->ID);
  716. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  717. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  718. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  719. for(int g=0; g<BFIELD_SIZE; ++g)
  720. {
  721. const CStack * atG = getStackT(g);
  722. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  723. continue;
  724. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  725. {
  726. if(predecessor[g] == -1) //TODO: is it really the best solution?
  727. continue;
  728. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  729. }
  730. }
  731. if(stackPairs.size() > 0)
  732. {
  733. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  734. minimalPairs.push_back(stackPairs[0]);
  735. for(int b=1; b<stackPairs.size(); ++b)
  736. {
  737. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  738. {
  739. minimalPairs.clear();
  740. minimalPairs.push_back(stackPairs[b]);
  741. }
  742. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  743. {
  744. minimalPairs.push_back(stackPairs[b]);
  745. }
  746. }
  747. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  748. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  749. }
  750. return std::make_pair<const CStack * , int>(NULL, -1);
  751. }
  752. ui32 BattleInfo::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  753. {
  754. ui32 ret = baseDamage;
  755. //applying sorcery secondary skill
  756. if(caster)
  757. {
  758. ret *= (100.f + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 25)) / 100.0f; //sorcery
  759. ret *= (100.f + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0f;
  760. if(sp->air)
  761. ret *= (100.0f + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  762. else if(sp->fire) //only one type of bonus for Magic Arrow
  763. ret *= (100.0f + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  764. else if(sp->water)
  765. ret *= (100.0f + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  766. else if(sp->earth)
  767. ret *= (100.0f + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  768. if (affectedCreature) //Hero specials like Solmyr, Deemer
  769. ret *= (100.f + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->getCreature()->level)) / 100.0f;
  770. }
  771. return ret;
  772. }
  773. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  774. {
  775. ui32 ret = 0; //value to return
  776. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  777. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  778. static std::map <int, int> dmgMultipliers = boost::assign::map_list_of(15, 10)(16, 20)(17, 25)(18, 75)(20, 10)(21, 10)(22, 10)(23, 10)(24, 5)(25, 10)(26, 50)(77, 10);
  779. //check if spell really does damage - if not, return 0
  780. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  781. return 0;
  782. ret = usedSpellPower * dmgMultipliers[sp->id];
  783. ret += sp->powers[spellSchoolLevel];
  784. //affected creature-specific part
  785. if(affectedCreature)
  786. {
  787. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  788. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  789. {
  790. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  791. ret /= 100;
  792. }
  793. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  794. {
  795. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  796. ret /= 100;
  797. }
  798. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  799. {
  800. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  801. ret /= 100;
  802. }
  803. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  804. {
  805. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  806. ret /= 100;
  807. }
  808. //general spell dmg reduction
  809. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  810. {
  811. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  812. ret /= 100;
  813. }
  814. //dmg increasing
  815. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  816. {
  817. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  818. ret /= 100;
  819. }
  820. }
  821. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  822. return ret;
  823. }
  824. ui32 BattleInfo::calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack) const
  825. {
  826. int powerPerLevel;
  827. bool resurrect;
  828. switch(spell->id)
  829. {
  830. case 37: //cure
  831. {
  832. powerPerLevel = 5;
  833. resurrect = false;
  834. break;
  835. }
  836. case 38: //resurrection
  837. case 39: //animate dead
  838. {
  839. powerPerLevel = 50;
  840. resurrect = true;
  841. break;
  842. }
  843. }
  844. int healedHealth = caster->getPrimSkillLevel(2) * powerPerLevel + spell->powers[caster->getSpellSchoolLevel(spell)];
  845. healedHealth = calculateSpellBonus(healedHealth, spell, caster, stack);
  846. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (resurrect ? stack->baseAmount * stack->MaxHealth() : 0));
  847. }
  848. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  849. {
  850. //we'll split creatures with remaining movement to 4 parts
  851. 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
  852. int toMove = 0; //how many stacks still has move
  853. const CStack *active = getStack(activeStack);
  854. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  855. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  856. {
  857. out.push_back(active);
  858. if(out.size() == howMany)
  859. return;
  860. }
  861. for(unsigned int i=0; i<stacks.size(); ++i)
  862. {
  863. const CStack * const s = stacks[i];
  864. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  865. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  866. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  867. {
  868. continue;
  869. }
  870. int p = -1; //in which phase this tack will move?
  871. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  872. {
  873. if(vstd::contains(s->state, HAD_MORALE))
  874. p = 2;
  875. else
  876. p = 3;
  877. }
  878. else if(s->getCreature()->idNumber == 145 || s->getCreature()->idNumber == 149) //catapult and turrets are first
  879. {
  880. p = 0;
  881. }
  882. else
  883. {
  884. p = 1;
  885. }
  886. phase[p].push_back(s);
  887. toMove++;
  888. }
  889. for(int i = 0; i < 4; i++)
  890. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  891. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  892. out.push_back(phase[0][i]);
  893. if(out.size() == howMany)
  894. return;
  895. if(lastMoved == -1)
  896. {
  897. if(active)
  898. {
  899. if(out.size() && out.front() == active)
  900. lastMoved = active->attackerOwned;
  901. else
  902. lastMoved = active->attackerOwned;
  903. }
  904. else
  905. {
  906. lastMoved = 0;
  907. }
  908. }
  909. int pi = 1;
  910. while(out.size() < howMany)
  911. {
  912. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  913. if(!hlp)
  914. {
  915. pi++;
  916. if(pi > 3)
  917. {
  918. //if(turn != 2)
  919. getStackQueue(out, howMany, turn + 1, lastMoved);
  920. return;
  921. }
  922. }
  923. else
  924. {
  925. out.push_back(hlp);
  926. }
  927. }
  928. }
  929. si8 BattleInfo::hasDistancePenalty( int stackID, int destHex )
  930. {
  931. const CStack * stack = getStack(stackID);
  932. struct HLP
  933. {
  934. static bool lowerAnalyze(const CStack * stack, int hex)
  935. {
  936. int distance = BattleInfo::getDistance(hex, stack->position);
  937. //I hope it's approximately correct
  938. return distance > 10 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  939. }
  940. };
  941. const CStack * dstStack = getStackT(destHex, false);
  942. if (dstStack->doubleWide())
  943. return HLP::lowerAnalyze(stack, destHex) && HLP::lowerAnalyze(stack, dstStack->occupiedHex());
  944. else
  945. return HLP::lowerAnalyze(stack, destHex);
  946. }
  947. si8 BattleInfo::sameSideOfWall(int pos1, int pos2)
  948. {
  949. int wallInStackLine = lineToWallHex(pos1/BFIELD_WIDTH);
  950. int wallInDestLine = lineToWallHex(pos2/BFIELD_WIDTH);
  951. bool stackLeft = pos1 < wallInStackLine;
  952. bool destLeft = pos2 < wallInDestLine;
  953. return stackLeft != destLeft;
  954. }
  955. si8 BattleInfo::hasWallPenalty( int stackID, int destHex )
  956. {
  957. if (siege == 0)
  958. {
  959. return false;
  960. }
  961. const CStack * stack = getStack(stackID);
  962. if (stack->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  963. {
  964. return false;
  965. }
  966. return !sameSideOfWall(stack->position, destHex);
  967. }
  968. si8 BattleInfo::canTeleportTo(int stackID, int destHex, int telportLevel)
  969. {
  970. bool ac[BFIELD_SIZE];
  971. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  972. std::set<int> occupyable;
  973. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, false, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  974. if (siege && telportLevel < 2) //check for wall
  975. {
  976. return ac[destHex] && sameSideOfWall(s->position, destHex);
  977. }
  978. else
  979. {
  980. return ac[destHex];
  981. }
  982. }
  983. // void BattleInfo::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  984. // {
  985. // CBonusSystemNode::getBonuses(out, selector, root);
  986. //
  987. // const CStack *dest = dynamic_cast<const CStack*>(root);
  988. // if (!dest)
  989. // return;
  990. //
  991. // //TODO: make it in clean way
  992. // if(Selector::matchesType(selector, Bonus::MORALE) || Selector::matchesType(selector, Bonus::LUCK))
  993. // {
  994. // BOOST_FOREACH(const CStack *s, stacks)
  995. // {
  996. // if(s->owner == dest->owner)
  997. // s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ALLIED_ARMY), this);
  998. // else
  999. // s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ENEMY_ARMY), this);
  1000. // }
  1001. // }
  1002. // }
  1003. si8 BattleInfo::getDistance( THex hex1, THex hex2 )
  1004. {
  1005. int xDst = std::abs(hex1 % BFIELD_WIDTH - hex2 % BFIELD_WIDTH),
  1006. yDst = std::abs(hex1 / BFIELD_WIDTH - hex2 / BFIELD_WIDTH);
  1007. return std::max(xDst, yDst) + std::min(xDst, yDst) - (yDst + 1)/2;
  1008. }
  1009. void BattleInfo::localInit()
  1010. {
  1011. belligerents[0]->battle = belligerents[1]->battle = this;
  1012. //TODO: attach battle to belligerents
  1013. BOOST_FOREACH(CStack *s, stacks)
  1014. {
  1015. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  1016. {
  1017. s->attachTo(const_cast<CStackInstance*>(s->base));
  1018. }
  1019. else //attach directly to obj to which stack belongs and creature type
  1020. {
  1021. CArmedInstance *army = belligerents[!s->attackerOwned];
  1022. s->attachTo(army);
  1023. assert(s->type);
  1024. s->attachTo(const_cast<CCreature*>(s->type));
  1025. }
  1026. s->postInit();
  1027. }
  1028. }
  1029. namespace CGH
  1030. {
  1031. using namespace std;
  1032. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  1033. {
  1034. for(int j=0; j<7; ++j)
  1035. {
  1036. std::vector<int> pom;
  1037. for(int g=0; g<j+1; ++g)
  1038. {
  1039. int hlp; input>>hlp;
  1040. pom.push_back(hlp);
  1041. }
  1042. dest.push_back(pom);
  1043. }
  1044. }
  1045. }
  1046. BattleInfo * BattleInfo::setupBattle( int3 tile, int terrain, int terType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  1047. {
  1048. CMP_stack cmpst;
  1049. BattleInfo *curB = new BattleInfo;
  1050. curB->side1 = armies[0]->tempOwner;
  1051. curB->side2 = armies[1]->tempOwner;
  1052. if(curB->side2 == 254)
  1053. curB->side2 = 255;
  1054. std::vector<CStack*> & stacks = (curB->stacks);
  1055. curB->tile = tile;
  1056. curB->battlefieldType = terType;
  1057. curB->belligerents[0] = const_cast<CArmedInstance*>(armies[0]);
  1058. curB->belligerents[1] = const_cast<CArmedInstance*>(armies[1]);
  1059. curB->heroes[0] = const_cast<CGHeroInstance*>(heroes[0]);
  1060. curB->heroes[1] = const_cast<CGHeroInstance*>(heroes[1]);
  1061. curB->round = -2;
  1062. curB->activeStack = -1;
  1063. if(town)
  1064. {
  1065. curB->tid = town->id;
  1066. curB->siege = town->fortLevel();
  1067. }
  1068. else
  1069. {
  1070. curB->tid = -1;
  1071. curB->siege = 0;
  1072. }
  1073. //reading battleStartpos
  1074. std::ifstream positions;
  1075. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1076. if(!positions.is_open())
  1077. {
  1078. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1079. }
  1080. std::string dump;
  1081. positions>>dump; positions>>dump;
  1082. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1083. CGH::readItTo(positions, attackerLoose);
  1084. positions>>dump;
  1085. CGH::readItTo(positions, defenderLoose);
  1086. positions>>dump;
  1087. positions>>dump;
  1088. CGH::readItTo(positions, attackerTight);
  1089. positions>>dump;
  1090. CGH::readItTo(positions, defenderTight);
  1091. positions>>dump;
  1092. positions>>dump;
  1093. CGH::readItTo(positions, attackerCreBank);
  1094. positions>>dump;
  1095. CGH::readItTo(positions, defenderCreBank);
  1096. positions.close();
  1097. //battleStartpos read
  1098. int k = 0; //stack serial
  1099. for(TSlots::const_iterator i = armies[0]->Slots().begin(); i!=armies[0]->Slots().end(); i++, k++)
  1100. {
  1101. int pos;
  1102. if(creatureBank)
  1103. pos = attackerCreBank[armies[0]->stacksCount()-1][k];
  1104. else if(armies[0]->formation)
  1105. pos = attackerTight[armies[0]->stacksCount()-1][k];
  1106. else
  1107. pos = attackerLoose[armies[0]->stacksCount()-1][k];
  1108. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), true, i->first, pos);
  1109. stacks.push_back(stack);
  1110. }
  1111. k = 0;
  1112. for(TSlots::const_iterator i = armies[1]->Slots().begin(); i!=armies[1]->Slots().end(); i++, k++)
  1113. {
  1114. int pos;
  1115. if(creatureBank)
  1116. pos = defenderCreBank[armies[1]->stacksCount()-1][k];
  1117. else if(armies[1]->formation)
  1118. pos = defenderTight[armies[1]->stacksCount()-1][k];
  1119. else
  1120. pos = defenderLoose[armies[1]->stacksCount()-1][k];
  1121. CStack * stack = curB->generateNewStack(*i->second, stacks.size(), false, i->first, pos);
  1122. stacks.push_back(stack);
  1123. }
  1124. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1125. {
  1126. if((stacks[g]->position%17)==1 && stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1127. {
  1128. stacks[g]->position += 1;
  1129. }
  1130. else if((stacks[g]->position%17)==15 && stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1131. {
  1132. stacks[g]->position -= 1;
  1133. }
  1134. }
  1135. //adding war machines
  1136. if(heroes[0])
  1137. {
  1138. if(heroes[0]->getArt(13)) //ballista
  1139. {
  1140. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), true, 255, 52);
  1141. stacks.push_back(stack);
  1142. }
  1143. if(heroes[0]->getArt(14)) //ammo cart
  1144. {
  1145. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), true, 255, 18);
  1146. stacks.push_back(stack);
  1147. }
  1148. if(heroes[0]->getArt(15)) //first aid tent
  1149. {
  1150. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), true, 255, 154);
  1151. stacks.push_back(stack);
  1152. }
  1153. }
  1154. if(heroes[1])
  1155. {
  1156. //defending hero shouldn't receive ballista (bug #551)
  1157. if(heroes[1]->getArt(13) && !town) //ballista
  1158. {
  1159. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(146, 1), stacks.size(), false, 255, 66);
  1160. stacks.push_back(stack);
  1161. }
  1162. if(heroes[1]->getArt(14)) //ammo cart
  1163. {
  1164. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(148, 1), stacks.size(), false, 255, 32);
  1165. stacks.push_back(stack);
  1166. }
  1167. if(heroes[1]->getArt(15)) //first aid tent
  1168. {
  1169. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(147, 1), stacks.size(), false, 255, 168);
  1170. stacks.push_back(stack);
  1171. }
  1172. }
  1173. if(town && heroes[0] && town->hasFort()) //catapult
  1174. {
  1175. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(145, 1), stacks.size(), true, 255, 120);
  1176. stacks.push_back(stack);
  1177. }
  1178. //war machines added
  1179. switch(curB->siege) //adding towers
  1180. {
  1181. case 3: //castle
  1182. {//lower tower / upper tower
  1183. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -4);
  1184. stacks.push_back(stack);
  1185. stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -3);
  1186. stacks.push_back(stack);
  1187. }
  1188. case 2: //citadel
  1189. {//main tower
  1190. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(149, 1), stacks.size(), false, 255, -2);
  1191. stacks.push_back(stack);
  1192. }
  1193. }
  1194. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1195. //seting up siege
  1196. if(town && town->hasFort())
  1197. {
  1198. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1199. {
  1200. curB->si.wallState[b] = 1;
  1201. }
  1202. }
  1203. //randomize obstacles
  1204. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1205. {
  1206. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1207. std::vector<int> possibleObstacles;
  1208. for(int i=0; i<BFIELD_SIZE; ++i)
  1209. {
  1210. if(i%17 < 4 || i%17 > 12)
  1211. {
  1212. obAv[i] = false;
  1213. }
  1214. else
  1215. {
  1216. obAv[i] = true;
  1217. }
  1218. }
  1219. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1220. {
  1221. 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
  1222. {
  1223. possibleObstacles.push_back(g->first);
  1224. }
  1225. }
  1226. srand(time(NULL));
  1227. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1228. {
  1229. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1230. while(toBlock>0)
  1231. {
  1232. CObstacleInstance coi;
  1233. coi.uniqueID = curB->obstacles.size();
  1234. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1235. coi.pos = rand()%BFIELD_SIZE;
  1236. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1237. bool badObstacle = false;
  1238. for(int b=0; b<block.size(); ++b)
  1239. {
  1240. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1241. {
  1242. badObstacle = true;
  1243. break;
  1244. }
  1245. }
  1246. if(badObstacle) continue;
  1247. //obstacle can be placed
  1248. curB->obstacles.push_back(coi);
  1249. for(int b=0; b<block.size(); ++b)
  1250. {
  1251. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1252. obAv[block[b]] = false;
  1253. }
  1254. toBlock -= block.size();
  1255. }
  1256. }
  1257. }
  1258. // //giving building bonuses, if siege and we have harrisoned hero
  1259. // if (town)
  1260. // {
  1261. // if (heroes[1])
  1262. // {
  1263. // for (int i=0; i<4; i++)
  1264. // {
  1265. // int val = town->defenceBonus(i);
  1266. // if (val)
  1267. // {
  1268. // GiveBonus gs;
  1269. // gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::OBJECT, val, -1, "", i);
  1270. // gs.id = heroes[1]->id;
  1271. // sendAndApply(&gs);
  1272. // }
  1273. // }
  1274. // }
  1275. // else//if we don't have hero - apply separately, if hero present - will be taken from hero bonuses
  1276. // {
  1277. // if(town->subID == 0 && vstd::contains(town->builtBuildings,22)) //castle, brotherhood of sword built
  1278. // for(int g=0; g<stacks.size(); ++g)
  1279. // stacks[g]->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1280. //
  1281. // else if(vstd::contains(town->builtBuildings,5)) //tavern is built
  1282. // for(int g=0; g<stacks.size(); ++g)
  1283. // stacks[g]->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TOWN_STRUCTURE));
  1284. //
  1285. // if(town->subID == 1 && vstd::contains(town->builtBuildings,21)) //rampart, fountain of fortune is present
  1286. // for(int g=0; g<stacks.size(); ++g)
  1287. // stacks[g]->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1288. // }
  1289. // }
  1290. //giving terrain overalay premies
  1291. int bonusSubtype = -1;
  1292. switch(terType)
  1293. {
  1294. case 9: //magic plains
  1295. {
  1296. bonusSubtype = 0;
  1297. }
  1298. case 14: //fiery fields
  1299. {
  1300. if(bonusSubtype == -1) bonusSubtype = 1;
  1301. }
  1302. case 15: //rock lands
  1303. {
  1304. if(bonusSubtype == -1) bonusSubtype = 8;
  1305. }
  1306. case 16: //magic clouds
  1307. {
  1308. if(bonusSubtype == -1) bonusSubtype = 2;
  1309. }
  1310. case 17: //lucid pools
  1311. {
  1312. if(bonusSubtype == -1) bonusSubtype = 4;
  1313. }
  1314. { //common part for cases 9, 14, 15, 16, 17
  1315. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  1316. break;
  1317. }
  1318. case 18: //holy ground
  1319. {
  1320. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(GOOD)));
  1321. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EVIL)));
  1322. break;
  1323. }
  1324. case 19: //clover field
  1325. { //+2 luck bonus for neutral creatures
  1326. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureFactionLimiter(-1)));
  1327. break;
  1328. }
  1329. case 20: //evil fog
  1330. {
  1331. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(GOOD)));
  1332. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(new CreatureAlignmentLimiter(EVIL)));
  1333. break;
  1334. }
  1335. case 22: //cursed ground
  1336. {
  1337. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1338. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1339. curB->addNewBonus(makeFeature(Bonus::BLOCK_SPELLS_ABOVE_LEVEL, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1340. break;
  1341. }
  1342. }
  1343. //overlay premies given
  1344. //native terrain bonuses
  1345. if(town) //during siege always take premies for native terrain of faction
  1346. terrain = VLC->heroh->nativeTerrains[town->town->typeID];
  1347. ILimiter *nativeTerrain = new CreatureNativeTerrainLimiter(terrain);
  1348. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1349. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1350. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  1351. //////////////////////////////////////////////////////////////////////////
  1352. return curB;
  1353. }
  1354. CStack::CStack(const CStackInstance *Base, int O, int I, bool AO, int S)
  1355. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO), position(-1),
  1356. counterAttacks(1)
  1357. {
  1358. assert(base);
  1359. type = base->type;
  1360. count = baseAmount = base->count;
  1361. }
  1362. CStack::CStack()
  1363. {
  1364. init();
  1365. }
  1366. CStack::CStack(const CStackBasicDescriptor *stack, int O, int I, bool AO, int S)
  1367. : base(NULL), ID(I), owner(O), slot(S), attackerOwned(AO), position(-1), counterAttacks(1)
  1368. {
  1369. type = stack->type;
  1370. count = baseAmount = stack->count;
  1371. }
  1372. void CStack::init()
  1373. {
  1374. base = NULL;
  1375. type = NULL;
  1376. ID = -1;
  1377. count = baseAmount = -1;
  1378. firstHPleft = -1;
  1379. owner = 255;
  1380. slot = 255;
  1381. attackerOwned = false;
  1382. position = -1;
  1383. counterAttacks = -1;
  1384. }
  1385. void CStack::postInit()
  1386. {
  1387. assert(type);
  1388. assert(parents.size());
  1389. firstHPleft = valOfBonuses(Bonus::STACK_HEALTH);
  1390. shots = getCreature()->shots;
  1391. counterAttacks = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  1392. state.insert(ALIVE); //alive state indication
  1393. assert(firstHPleft > 0);
  1394. }
  1395. ui32 CStack::Speed( int turn /*= 0*/ ) const
  1396. {
  1397. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  1398. return 0;
  1399. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  1400. int percentBonus = 0;
  1401. BOOST_FOREACH(const Bonus *b, bonuses)
  1402. {
  1403. if(b->type == Bonus::STACKS_SPEED)
  1404. {
  1405. percentBonus += b->additionalInfo;
  1406. }
  1407. }
  1408. speed = ((100 + percentBonus) * speed)/100;
  1409. //bind effect check
  1410. if(getEffect(72))
  1411. {
  1412. return 0;
  1413. }
  1414. return speed;
  1415. }
  1416. const Bonus * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  1417. {
  1418. BOOST_FOREACH(Bonus *it, bonuses)
  1419. {
  1420. if(it->source == Bonus::SPELL_EFFECT && it->id == id)
  1421. {
  1422. if(!turn || it->turnsRemain > turn)
  1423. return &(*it);
  1424. }
  1425. }
  1426. return NULL;
  1427. }
  1428. void CStack::stackEffectToFeature(BonusList & sf, const Bonus & sse)
  1429. {
  1430. // si32 power = VLC->spellh->spells[sse.id]->powers[sse.val];
  1431. // Bonus * bonus = getBonus(Selector::typeSybtype(Bonus::SPECIAL_PECULIAR_ENCHANT, sse.id));
  1432. // if (bonus)
  1433. // {
  1434. // switch(bonus->additionalInfo)
  1435. // {
  1436. // case 0: //normal
  1437. // switch(type->level)
  1438. // {
  1439. // case 1: case 2:
  1440. // power += 3; //it doesn't necessarily make sense for some spells, use it wisely
  1441. // break;
  1442. // case 3: case 4:
  1443. // power += 2;
  1444. // break;
  1445. // case 5: case 6:
  1446. // power += 1;
  1447. // break;
  1448. // }
  1449. // break;
  1450. // case 1: //only Coronius as yet
  1451. // power = std::max(5 - type->level, 0);
  1452. // break;
  1453. // }
  1454. // }
  1455. //
  1456. // switch(sse.id)
  1457. // {
  1458. // case 27: //shield
  1459. // sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1460. // sf.back().id = sse.id;
  1461. // break;
  1462. // case 28: //air shield
  1463. // sf.push_back(featureGenerator(Bonus::GENERAL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1464. // sf.back().id = sse.id;
  1465. // break;
  1466. // case 29: //fire shield
  1467. // sf.push_back(featureGenerator(Bonus::FIRE_SHIELD, 0, power, sse.turnsRemain));
  1468. // sf.back().id = sse.id;
  1469. // break;
  1470. // case 30: //protection from air
  1471. // sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 0, power, sse.turnsRemain));
  1472. // sf.back().id = sse.id;
  1473. // break;
  1474. // case 31: //protection from fire
  1475. // sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 1, power, sse.turnsRemain));
  1476. // sf.back().id = sse.id;
  1477. // break;
  1478. // case 32: //protection from water
  1479. // sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 2, power, sse.turnsRemain));
  1480. // sf.back().id = sse.id;
  1481. // break;
  1482. // case 33: //protection from earth
  1483. // sf.push_back(featureGenerator(Bonus::SPELL_DAMAGE_REDUCTION, 3, power, sse.turnsRemain));
  1484. // sf.back().id = sse.id;
  1485. // break;
  1486. // case 34: //anti-magic
  1487. // sf.push_back(featureGenerator(Bonus::LEVEL_SPELL_IMMUNITY, 0, power - 1, sse.turnsRemain));
  1488. // sf.back().id = sse.id;
  1489. // break;
  1490. // case 41: //bless
  1491. // if (hasBonusOfType(Bonus::SPECIAL_BLESS_DAMAGE, 41)) //TODO: better handling of bonus percentages
  1492. // {
  1493. // int damagePercent = dynamic_cast<const CGHeroInstance*>(armyObj)->level * valOfBonuses(Bonus::SPECIAL_BLESS_DAMAGE, 41) / type->level;
  1494. // sf.push_back(featureGenerator(Bonus::CREATURE_DAMAGE, 0, damagePercent, sse.turnsRemain));
  1495. // sf.back().id = sse.id;
  1496. // sf.back().valType = Bonus::PERCENT_TO_ALL;
  1497. // }
  1498. // sf.push_back(featureGenerator(Bonus::ALWAYS_MAXIMUM_DAMAGE, -1, power, sse.turnsRemain));
  1499. // sf.back().id = sse.id;
  1500. // break;
  1501. // case 42: //curse
  1502. // sf.push_back(featureGenerator(Bonus::ALWAYS_MINIMUM_DAMAGE, -1, -1 * power, sse.turnsRemain, sse.val >= 2 ? 20 : 0));
  1503. // sf.back().id = sse.id;
  1504. // break;
  1505. // case 43: //bloodlust
  1506. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_MELEE_FIGHT));
  1507. // sf.back().id = sse.id;
  1508. // break;
  1509. // case 44: //precision
  1510. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain, 0, Bonus::ONLY_DISTANCE_FIGHT));
  1511. // sf.back().id = sse.id;
  1512. // break;
  1513. // case 45: //weakness
  1514. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, -1 * power, sse.turnsRemain));
  1515. // sf.back().id = sse.id;
  1516. // break;
  1517. // case 46: //stone skin
  1518. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1519. // sf.back().id = sse.id;
  1520. // break;
  1521. // case 47: //disrupting ray
  1522. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, -1 * power, sse.turnsRemain));
  1523. // sf.back().id = sse.id;
  1524. // break;
  1525. // case 48: //prayer
  1526. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  1527. // sf.back().id = sse.id;
  1528. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE, power, sse.turnsRemain));
  1529. // sf.back().id = sse.id;
  1530. // sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1531. // sf.back().id = sse.id;
  1532. // break;
  1533. // case 49: //mirth
  1534. // sf.push_back(featureGenerator(Bonus::MORALE, 0, power, sse.turnsRemain));
  1535. // sf.back().id = sse.id;
  1536. // break;
  1537. // case 50: //sorrow
  1538. // sf.push_back(featureGenerator(Bonus::MORALE, 0, -1 * power, sse.turnsRemain));
  1539. // sf.back().id = sse.id;
  1540. // break;
  1541. // case 51: //fortune
  1542. // sf.push_back(featureGenerator(Bonus::LUCK, 0, power, sse.turnsRemain));
  1543. // sf.back().id = sse.id;
  1544. // break;
  1545. // case 52: //misfortune
  1546. // sf.push_back(featureGenerator(Bonus::LUCK, 0, -1 * power, sse.turnsRemain));
  1547. // sf.back().id = sse.id;
  1548. // break;
  1549. // case 53: //haste
  1550. // sf.push_back(featureGenerator(Bonus::STACKS_SPEED, 0, power, sse.turnsRemain));
  1551. // sf.back().id = sse.id;
  1552. // break;
  1553. // case 54: //slow
  1554. // sf.push_back(featureGeneratorVT(Bonus::STACKS_SPEED, 0, -1 * ( 100 - power ), sse.turnsRemain, Bonus::PERCENT_TO_ALL));
  1555. // sf.back().id = sse.id;
  1556. // break;
  1557. // case 55: //slayer
  1558. // if (bonus) //Coronius
  1559. // {
  1560. // sf.push_back(featureGenerator(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK, power, sse.turnsRemain));
  1561. // sf.back().id = sse.id;
  1562. // }
  1563. // sf.push_back(featureGenerator(Bonus::SLAYER, 0, sse.val, sse.turnsRemain));
  1564. // sf.back().id = sse.id;
  1565. // break;
  1566. // case 56: //frenzy
  1567. // sf.push_back(featureGenerator(Bonus::IN_FRENZY, 0, VLC->spellh->spells[56]->powers[sse.val]/100.0, sse.turnsRemain));
  1568. // sf.back().id = sse.id;
  1569. // break;
  1570. // case 58: //counterstrike
  1571. // sf.push_back(featureGenerator(Bonus::ADDITIONAL_RETALIATION, 0, power, sse.turnsRemain));
  1572. // sf.back().id = sse.id;
  1573. // break;
  1574. // case 59: //bersek
  1575. // sf.push_back(featureGenerator(Bonus::ATTACKS_NEAREST_CREATURE, 0, sse.val, sse.turnsRemain));
  1576. // sf.back().id = sse.id;
  1577. // break;
  1578. // case 60: //hypnotize
  1579. // sf.push_back(featureGenerator(Bonus::HYPNOTIZED, 0, sse.val, sse.turnsRemain));
  1580. // sf.back().id = sse.id;
  1581. // break;
  1582. // case 61: //forgetfulness
  1583. // sf.push_back(featureGenerator(Bonus::FORGETFULL, 0, sse.val, sse.turnsRemain));
  1584. // sf.back().id = sse.id;
  1585. // break;
  1586. // case 62: //blind
  1587. // sf.push_back(makeFeature(Bonus::NOT_ACTIVE, Bonus::UNITL_BEING_ATTACKED | Bonus::N_TURNS, 0, 0, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1588. // sf.back().id = sse.id;
  1589. // sf.push_back(makeFeature(Bonus::GENERAL_ATTACK_REDUCTION, Bonus::UNTIL_ATTACK | Bonus::N_TURNS, 0, power, Bonus::SPELL_EFFECT, sse.turnsRemain));
  1590. // sf.back().id = sse.id;
  1591. // break;
  1592. // }
  1593. }
  1594. ui8 CStack::howManyEffectsSet(ui16 id) const
  1595. {
  1596. ui8 ret = 0;
  1597. BOOST_FOREACH(const Bonus *it, bonuses)
  1598. if(it->source == Bonus::SPELL_EFFECT && it->id == id) //effect found
  1599. {
  1600. ++ret;
  1601. }
  1602. return ret;
  1603. }
  1604. bool CStack::willMove(int turn /*= 0*/) const
  1605. {
  1606. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  1607. && !moved(turn)
  1608. && canMove(turn);
  1609. }
  1610. bool CStack::canMove( int turn /*= 0*/ ) const
  1611. {
  1612. return alive()
  1613. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  1614. }
  1615. bool CStack::moved( int turn /*= 0*/ ) const
  1616. {
  1617. if(!turn)
  1618. return vstd::contains(state, MOVED);
  1619. else
  1620. return false;
  1621. }
  1622. bool CStack::doubleWide() const
  1623. {
  1624. return getCreature()->doubleWide;
  1625. }
  1626. int CStack::occupiedHex() const
  1627. {
  1628. if (doubleWide())
  1629. {
  1630. if (attackerOwned)
  1631. return position - 1;
  1632. else
  1633. return position + 1;
  1634. }
  1635. else
  1636. {
  1637. return -1;
  1638. }
  1639. }
  1640. BonusList CStack::getSpellBonuses() const
  1641. {
  1642. return getBonuses(Selector::sourceTypeSel(Bonus::CASTED_SPELL));
  1643. }
  1644. std::vector<si32> CStack::activeSpells() const
  1645. {
  1646. std::vector<si32> ret;
  1647. BonusList spellEffects = getSpellBonuses();
  1648. BOOST_FOREACH(const Bonus *it, spellEffects)
  1649. {
  1650. if (!vstd::contains(ret, it->id)) //do not duplicate spells with multiple effects
  1651. ret.push_back(it->id);
  1652. }
  1653. return ret;
  1654. }
  1655. CStack::~CStack()
  1656. {
  1657. detachFromAll();
  1658. if(vstd::contains(state, SUMMONED))
  1659. delNull(base);
  1660. }
  1661. const CGHeroInstance * CStack::getMyHero() const
  1662. {
  1663. if(base)
  1664. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  1665. else //we are attached directly?
  1666. BOOST_FOREACH(const CBonusSystemNode *n, parents)
  1667. if(n->nodeType == HERO)
  1668. dynamic_cast<const CGHeroInstance *>(n);
  1669. return NULL;
  1670. }
  1671. std::string CStack::nodeName() const
  1672. {
  1673. std::ostringstream oss;
  1674. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  1675. if(type)
  1676. oss << type->namePl;
  1677. else
  1678. oss << "[UNDEFINED TYPE]";
  1679. oss << " from slot " << (int)slot;
  1680. if(base && base->armyObj)
  1681. oss << " of armyobj=" << base->armyObj->id;
  1682. return oss.str();
  1683. }
  1684. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1685. {
  1686. switch(phase)
  1687. {
  1688. case 0: //catapult moves after turrets
  1689. return a->getCreature()->idNumber < b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1690. //TODO? turrets order
  1691. case 1: //fastest first, upper slot first
  1692. {
  1693. int as = a->Speed(turn), bs = b->Speed(turn);
  1694. if(as != bs)
  1695. return as > bs;
  1696. else
  1697. return a->slot < b->slot;
  1698. }
  1699. case 2: //fastest last, upper slot first
  1700. //TODO: should be replaced with order of receiving morale!
  1701. case 3: //fastest last, upper slot first
  1702. {
  1703. int as = a->Speed(turn), bs = b->Speed(turn);
  1704. if(as != bs)
  1705. return as < bs;
  1706. else
  1707. return a->slot < b->slot;
  1708. }
  1709. default:
  1710. assert(0);
  1711. return false;
  1712. }
  1713. }
  1714. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1715. {
  1716. phase = Phase;
  1717. turn = Turn;
  1718. }