BattleState.cpp 61 KB

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