BattleState.cpp 80 KB

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