BattleState.cpp 77 KB

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