BattleState.cpp 92 KB

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