BattleState.cpp 76 KB

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