BattleState.cpp 89 KB

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