BattleState.cpp 59 KB

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