CGameState.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407
  1. #define VCMI_DLL
  2. #include <algorithm>
  3. #include <queue>
  4. #include <fstream>
  5. #include "CGameState.h"
  6. #include <boost/random/linear_congruential.hpp>
  7. #include "../hch/CDefObjInfoHandler.h"
  8. #include "../hch/CArtHandler.h"
  9. #include "../hch/CBuildingHandler.h"
  10. #include "../hch/CGeneralTextHandler.h"
  11. #include "../hch/CTownHandler.h"
  12. #include "../hch/CSpellHandler.h"
  13. #include "../hch/CHeroHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CCreatureHandler.h"
  16. #include "VCMI_Lib.h"
  17. #include "Connection.h"
  18. #include "map.h"
  19. #include "../StartInfo.h"
  20. #include "NetPacks.h"
  21. #include <boost/foreach.hpp>
  22. #include <boost/lexical_cast.hpp>
  23. #include <boost/thread.hpp>
  24. #include <boost/thread/shared_mutex.hpp>
  25. #include "RegisterTypes.cpp"
  26. boost::rand48 ran;
  27. #ifdef min
  28. #undef min
  29. #endif
  30. #ifdef max
  31. #undef max
  32. #endif
  33. /*
  34. * CGameState.cpp, part of VCMI engine
  35. *
  36. * Authors: listed in file AUTHORS in main folder
  37. *
  38. * License: GNU General Public License v2.0 or later
  39. * Full text of license available in license.txt file, in main folder
  40. *
  41. */
  42. void foofoofoo()
  43. {
  44. //never called function to force instantation of templates
  45. int *ccc = NULL;
  46. registerTypes((CISer<CConnection>&)*ccc);
  47. registerTypes((COSer<CConnection>&)*ccc);
  48. registerTypes((CSaveFile&)*ccc);
  49. registerTypes((CLoadFile&)*ccc);
  50. registerTypes((CTypeList&)*ccc);
  51. }
  52. class CBaseForGSApply
  53. {
  54. public:
  55. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  56. };
  57. template <typename T> class CApplyOnGS : public CBaseForGSApply
  58. {
  59. public:
  60. void applyOnGS(CGameState *gs, void *pack) const
  61. {
  62. T *ptr = static_cast<T*>(pack);
  63. while(!gs->mx->try_lock())
  64. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  65. ptr->applyGs(gs);
  66. gs->mx->unlock();
  67. }
  68. };
  69. class CGSApplier
  70. {
  71. public:
  72. std::map<ui16,CBaseForGSApply*> apps;
  73. CGSApplier()
  74. {
  75. registerTypes2(*this);
  76. }
  77. template<typename T> void registerType(const T * t=NULL)
  78. {
  79. ui16 ID = typeList.registerType(t);
  80. apps[ID] = new CApplyOnGS<T>;
  81. }
  82. } *applierGs = NULL;
  83. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  84. {
  85. int type = txt.first, ser = txt.second;
  86. if(type == ART_NAMES)
  87. {
  88. dst = VLC->arth->artifacts[ser].Name();
  89. }
  90. else if(type == CRE_PL_NAMES)
  91. {
  92. dst = VLC->creh->creatures[ser].namePl;
  93. }
  94. else if(type == MINE_NAMES)
  95. {
  96. dst = VLC->generaltexth->mines[ser].first;
  97. }
  98. else if(type == MINE_EVNTS)
  99. {
  100. dst = VLC->generaltexth->mines[ser].second;
  101. }
  102. else if(type == SPELL_NAME)
  103. {
  104. dst = VLC->spellh->spells[ser].name;
  105. }
  106. else if(type == CRE_SING_NAMES)
  107. {
  108. dst = VLC->creh->creatures[ser].nameSing;
  109. }
  110. else
  111. {
  112. std::vector<std::string> *vec;
  113. switch(type)
  114. {
  115. case GENERAL_TXT:
  116. vec = &VLC->generaltexth->allTexts;
  117. break;
  118. case XTRAINFO_TXT:
  119. vec = &VLC->generaltexth->xtrainfo;
  120. break;
  121. case OBJ_NAMES:
  122. vec = &VLC->generaltexth->names;
  123. break;
  124. case RES_NAMES:
  125. vec = &VLC->generaltexth->restypes;
  126. break;
  127. case ARRAY_TXT:
  128. vec = &VLC->generaltexth->arraytxt;
  129. break;
  130. case CREGENS:
  131. vec = &VLC->generaltexth->creGens;
  132. break;
  133. case CREGENS4:
  134. vec = &VLC->generaltexth->creGens4;
  135. break;
  136. case ADVOB_TXT:
  137. vec = &VLC->generaltexth->advobtxt;
  138. break;
  139. case ART_EVNTS:
  140. vec = &VLC->generaltexth->artifEvents;
  141. break;
  142. case SEC_SKILL_NAME:
  143. vec = &VLC->generaltexth->skillName;
  144. break;
  145. }
  146. dst = (*vec)[ser];
  147. }
  148. }
  149. DLL_EXPORT void MetaString::toString(std::string &dst) const
  150. {
  151. size_t exSt = 0, loSt = 0, nums = 0;
  152. dst.clear();
  153. for(size_t i=0;i<message.size();++i)
  154. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  155. switch(message[i])
  156. {
  157. case TEXACT_STRING:
  158. dst += exactStrings[exSt++];
  159. break;
  160. case TLOCAL_STRING:
  161. {
  162. std::string hlp;
  163. getLocalString(localStrings[loSt++], hlp);
  164. dst += hlp;
  165. }
  166. break;
  167. case TNUMBER:
  168. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  169. break;
  170. case TREPLACE_ESTRING:
  171. dst.replace(dst.find("%s"), 2, exactStrings[exSt++]);
  172. break;
  173. case TREPLACE_LSTRING:
  174. {
  175. std::string hlp;
  176. getLocalString(localStrings[loSt++], hlp);
  177. dst.replace(dst.find("%s"), 2, hlp);
  178. }
  179. break;
  180. case TREPLACE_NUMBER:
  181. dst.replace(dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  182. break;
  183. default:
  184. tlog1 << "MetaString processing error!\n";
  185. break;
  186. }
  187. }
  188. }
  189. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  190. {
  191. CGObjectInstance * nobj;
  192. switch(id)
  193. {
  194. case HEROI_TYPE: //hero
  195. {
  196. CGHeroInstance * nobj = new CGHeroInstance();
  197. nobj->pos = pos;
  198. nobj->tempOwner = owner;
  199. nobj->subID = subid;
  200. //nobj->initHero(ran);
  201. return nobj;
  202. }
  203. case TOWNI_TYPE: //town
  204. nobj = new CGTownInstance;
  205. break;
  206. default: //rest of objects
  207. nobj = new CGObjectInstance;
  208. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  209. break;
  210. }
  211. nobj->ID = id;
  212. nobj->subID = subid;
  213. if(!nobj->defInfo)
  214. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  215. nobj->pos = pos;
  216. //nobj->state = NULL;//new CLuaObjectScript();
  217. nobj->tempOwner = owner;
  218. nobj->info = NULL;
  219. nobj->defInfo->id = id;
  220. nobj->defInfo->subid = subid;
  221. //assigning defhandler
  222. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  223. return nobj;
  224. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  225. return nobj;
  226. }
  227. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  228. {
  229. for(unsigned int g=0; g<stacks.size(); ++g)
  230. {
  231. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  232. return stacks[g];
  233. }
  234. return NULL;
  235. }
  236. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  237. {
  238. for(unsigned int g=0; g<stacks.size(); ++g)
  239. {
  240. if(stacks[g]->position == tileID
  241. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  242. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  243. {
  244. if(!onlyAlive || stacks[g]->alive())
  245. {
  246. return stacks[g];
  247. }
  248. }
  249. }
  250. return NULL;
  251. }
  252. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit)
  253. {
  254. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  255. //removing accessibility for side columns of hexes
  256. for(int v = 0; v < BFIELD_SIZE; ++v)
  257. {
  258. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  259. accessibility[v] = false;
  260. }
  261. for(unsigned int g=0; g<stacks.size(); ++g)
  262. {
  263. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit) //we don't want to lock position of this stack
  264. continue;
  265. accessibility[stacks[g]->position] = false;
  266. if(stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)) //if it's a double hex creature
  267. {
  268. if(stacks[g]->attackerOwned)
  269. accessibility[stacks[g]->position-1] = false;
  270. else
  271. accessibility[stacks[g]->position+1] = false;
  272. }
  273. }
  274. //obstacles
  275. for(unsigned int b=0; b<obstacles.size(); ++b)
  276. {
  277. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  278. for(unsigned int c=0; c<blocked.size(); ++c)
  279. {
  280. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  281. accessibility[blocked[c]] = false;
  282. }
  283. }
  284. if(addOccupiable && twoHex)
  285. {
  286. std::set<int> rem; //tiles to unlock
  287. for(int h=0; h<BFIELD_HEIGHT; ++h)
  288. {
  289. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  290. {
  291. int hex = h * BFIELD_WIDTH + w;
  292. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  293. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  294. )
  295. rem.insert(hex);
  296. }
  297. }
  298. occupyable = rem;
  299. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  300. {
  301. accessibility[*it] = true;
  302. }*/
  303. }
  304. }
  305. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  306. {
  307. if(flying && !lastPos)
  308. return true;
  309. if(twoHex)
  310. {
  311. //if given hex is accessible and appropriate adjacent one is free too
  312. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  313. }
  314. else
  315. {
  316. return accessibility[hex];
  317. }
  318. }
  319. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying) //both pointers must point to the at least 187-elements int arrays
  320. {
  321. //inits
  322. for(int b=0; b<BFIELD_SIZE; ++b)
  323. predecessor[b] = -1;
  324. for(int g=0; g<BFIELD_SIZE; ++g)
  325. dists[g] = 100000000;
  326. std::queue<int> hexq; //bfs queue
  327. hexq.push(start);
  328. dists[hexq.front()] = 0;
  329. int curNext = -1; //for bfs loop only (helper var)
  330. while(!hexq.empty()) //bfs loop
  331. {
  332. int curHex = hexq.front();
  333. std::vector<int> neighbours = neighbouringTiles(curHex);
  334. hexq.pop();
  335. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  336. {
  337. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  338. if(!isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex]+1 == dists[curNext]) || (dists[curHex]+1)>=dists[curNext])
  339. continue;
  340. hexq.push(curNext);
  341. dists[curNext] = dists[curHex] + 1;
  342. predecessor[curNext] = curHex;
  343. }
  344. }
  345. };
  346. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable)
  347. {
  348. std::vector<int> ret;
  349. bool ac[BFIELD_SIZE];
  350. CStack *s = getStack(stackID);
  351. std::set<int> occupyable;
  352. getAccessibilityMap(ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, addOccupiable, occupyable, s->hasFeatureOfType(StackFeature::FLYING), stackID);
  353. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  354. makeBFS(s->position, ac, pr, dist, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING));
  355. if(s->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  356. {
  357. if(!addOccupiable)
  358. {
  359. std::vector<int> rem;
  360. for(int b=0; b<BFIELD_SIZE; ++b)
  361. {
  362. //don't take into account most left and most right columns of hexes
  363. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  364. continue;
  365. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  366. {
  367. rem.push_back(b);
  368. }
  369. }
  370. for(unsigned int g=0; g<rem.size(); ++g)
  371. {
  372. ac[rem[g]] = false;
  373. }
  374. //removing accessibility for side hexes
  375. for(int v=0; v<BFIELD_SIZE; ++v)
  376. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  377. ac[v] = false;
  378. }
  379. }
  380. for (int i=0; i < BFIELD_SIZE ; ++i) {
  381. if(
  382. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), true) ) )//we can reach it
  383. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  384. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  385. )
  386. {
  387. ret.push_back(i);
  388. }
  389. }
  390. return ret;
  391. }
  392. bool BattleInfo::isStackBlocked(int ID)
  393. {
  394. CStack *our = getStack(ID);
  395. if(our->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //siege weapons cannot be blocked
  396. return true;
  397. for(unsigned int i=0; i<stacks.size();i++)
  398. {
  399. if( !stacks[i]->alive()
  400. || stacks[i]->owner==our->owner
  401. )
  402. continue; //we omit dead and allied stacks
  403. if(stacks[i]->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  404. {
  405. if( mutualPosition(stacks[i]->position, our->position) >= 0
  406. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  407. return true;
  408. }
  409. else
  410. {
  411. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  412. return true;
  413. }
  414. }
  415. return false;
  416. }
  417. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  418. {
  419. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  420. return 0;
  421. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  422. return 1;
  423. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  424. return 5;
  425. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  426. return 2;
  427. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  428. return 4;
  429. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  430. return 3;
  431. return -1;
  432. }
  433. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  434. {
  435. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  436. std::vector<int> ret;
  437. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  438. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  439. CHECK_AND_PUSH(hex - 1);
  440. CHECK_AND_PUSH(hex + 1);
  441. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  442. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  443. #undef CHECK_AND_PUSH
  444. return ret;
  445. }
  446. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  447. {
  448. int predecessor[BFIELD_SIZE]; //for getting the Path
  449. int dist[BFIELD_SIZE]; //calculated distances
  450. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature);
  451. if(predecessor[dest] == -1) //cannot reach destination
  452. {
  453. return std::make_pair(std::vector<int>(), 0);
  454. }
  455. //making the Path
  456. std::vector<int> path;
  457. int curElem = dest;
  458. while(curElem != start)
  459. {
  460. path.push_back(curElem);
  461. curElem = predecessor[curElem];
  462. }
  463. return std::make_pair(path, dist[dest]);
  464. }
  465. int CStack::valOfFeatures(StackFeature::ECombatFeatures type, int subtype) const
  466. {
  467. int ret = 0;
  468. if(subtype == -1024) //any subtype
  469. {
  470. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  471. if(i->type == type)
  472. ret += i->value;
  473. }
  474. else //given subtype
  475. {
  476. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  477. if(i->type == type && i->subtype == subtype)
  478. ret += i->value;
  479. }
  480. return ret;
  481. }
  482. bool CStack::hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype) const
  483. {
  484. if(subtype == -1024) //any subtype
  485. {
  486. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  487. if(i->type == type)
  488. return true;
  489. }
  490. else //given subtype
  491. {
  492. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  493. if(i->type == type && i->subtype == subtype)
  494. return true;
  495. }
  496. return false;
  497. }
  498. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  499. :ID(I), creature(C), amount(A), baseAmount(A), firstHPleft(C->hitPoints), owner(O), slot(S), attackerOwned(AO), position(-1),
  500. counterAttacks(1), shots(C->shots), features(C->abilities)
  501. {
  502. //additional retaliations
  503. for(int h=0; h<C->abilities.size(); ++h)
  504. {
  505. if(C->abilities[h].type == StackFeature::ADDITIONAL_RETALIATION)
  506. {
  507. counterAttacks += C->abilities[h].value;
  508. }
  509. }
  510. //alive state indication
  511. state.insert(ALIVE);
  512. }
  513. ui32 CStack::Speed() const
  514. {
  515. if(hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //war machnes cannot move
  516. return 0;
  517. int speed = creature->speed;
  518. speed += valOfFeatures(StackFeature::SPEED_BONUS);
  519. int percentBonus = 0;
  520. for(int g=0; g<features.size(); ++g)
  521. {
  522. if(features[g].type == StackFeature::SPEED_BONUS)
  523. {
  524. percentBonus += features[g].additionalInfo;
  525. }
  526. }
  527. if(percentBonus < 0)
  528. {
  529. speed = (abs(percentBonus) * speed)/100;
  530. }
  531. else
  532. {
  533. speed = ((100 + percentBonus) * speed)/100;
  534. }
  535. //bind effect check
  536. if(getEffect(72))
  537. {
  538. return 0;
  539. }
  540. return speed;
  541. }
  542. const CStack::StackEffect * CStack::getEffect(ui16 id) const
  543. {
  544. for (unsigned int i=0; i< effects.size(); i++)
  545. if(effects[i].id == id)
  546. return &effects[i];
  547. return NULL;
  548. }
  549. ui8 CStack::howManyEffectsSet(ui16 id) const
  550. {
  551. ui8 ret = 0;
  552. for (unsigned int i=0; i< effects.size(); i++)
  553. if(effects[i].id == id) //effect found
  554. {
  555. ++ret;
  556. }
  557. return ret;
  558. }
  559. si8 CStack::Morale() const
  560. {
  561. si8 ret = morale;
  562. if(hasFeatureOfType(StackFeature::NON_LIVING) || hasFeatureOfType(StackFeature::UNDEAD) || hasFeatureOfType(StackFeature::NO_MORALE))
  563. return 0;
  564. ret += valOfFeatures(StackFeature::MORALE_BONUS); //mirth & sorrow & other
  565. if(hasFeatureOfType(StackFeature::SELF_MORALE)) //eg. minotaur
  566. {
  567. ret = std::max<si8>(ret, +1);
  568. }
  569. if(ret > 3) ret = 3;
  570. if(ret < -3) ret = -3;
  571. return ret;
  572. }
  573. si8 CStack::Luck() const
  574. {
  575. si8 ret = luck;
  576. if(hasFeatureOfType(StackFeature::NO_LUCK))
  577. return 0;
  578. ret += valOfFeatures(StackFeature::LUCK_BONUS); //fortune & misfortune & other
  579. if(hasFeatureOfType(StackFeature::SELF_LUCK)) //eg. halfling
  580. {
  581. ret = std::max<si8>(ret, +1);
  582. }
  583. if(ret > 3) ret = 3;
  584. if(ret < -3) ret = -3;
  585. return ret;
  586. }
  587. si32 CStack::Attack() const
  588. {
  589. si32 ret = creature->attack; //value to be returned
  590. if(hasFeatureOfType(StackFeature::IN_FRENZY)) //frenzy for attacker
  591. {
  592. ret += (VLC->spellh->spells[56].powers[getEffect(56)->level]/100.0) * Defense(false);
  593. }
  594. ret += valOfFeatures(StackFeature::ATTACK_BONUS);
  595. return ret;
  596. }
  597. si32 CStack::Defense(bool withFrenzy /*= true*/) const
  598. {
  599. si32 ret = creature->defence;
  600. if(withFrenzy && getEffect(56)) //frenzy for defender
  601. {
  602. return 0;
  603. }
  604. ret += valOfFeatures(StackFeature::DEFENCE_BONUS);
  605. return ret;
  606. }
  607. ui16 CStack::MaxHealth() const
  608. {
  609. return creature->hitPoints + valOfFeatures(StackFeature::HP_BONUS);
  610. }
  611. bool CStack::willMove()
  612. {
  613. return !vstd::contains(state, DEFENDING)
  614. && !vstd::contains(state, MOVED)
  615. && alive()
  616. && ! hasFeatureOfType(StackFeature::NOT_ACTIVE); //eg. Ammo Cart
  617. }
  618. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const
  619. {
  620. CGHeroInstance *ret = NULL;
  621. if(player<0 || player>=PLAYER_LIMIT)
  622. {
  623. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  624. return NULL;
  625. }
  626. std::vector<CGHeroInstance *> pool;
  627. if(native)
  628. {
  629. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  630. {
  631. if(pavailable.find(i->first)->second & 1<<player
  632. && i->second->type->heroType/2 == town->typeID)
  633. {
  634. pool.push_back(i->second);
  635. }
  636. }
  637. if(!pool.size())
  638. {
  639. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  640. return pickHeroFor(false, player, town, available);
  641. }
  642. else
  643. {
  644. ret = pool[rand()%pool.size()];
  645. }
  646. }
  647. else
  648. {
  649. int sum=0, r;
  650. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  651. {
  652. if(pavailable.find(i->first)->second & 1<<player)
  653. {
  654. pool.push_back(i->second);
  655. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  656. }
  657. }
  658. if(!pool.size())
  659. {
  660. tlog1 << "There are no heroes available for player " << player<<"!\n";
  661. return NULL;
  662. }
  663. r = rand()%sum;
  664. for(unsigned int i=0; i<pool.size(); i++)
  665. {
  666. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  667. if(r<0)
  668. ret = pool[i];
  669. }
  670. if(!ret)
  671. ret = pool.back();
  672. }
  673. available.erase(ret->subID);
  674. return ret;
  675. }
  676. //void CGameState::apply(CPack * pack)
  677. //{
  678. // while(!mx->try_lock())
  679. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  680. // //applyNL(pack);
  681. // mx->unlock();
  682. //}
  683. int CGameState::pickHero(int owner)
  684. {
  685. int h=-1;
  686. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  687. return h;
  688. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  689. int i=0;
  690. do //try to find free hero of our faction
  691. {
  692. i++;
  693. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  694. } while( map->getHero(h) && i<175);
  695. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  696. {
  697. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  698. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  699. if(!map->getHero(j))
  700. h=j;
  701. }
  702. return h;
  703. }
  704. CGHeroInstance *CGameState::getHero(int objid)
  705. {
  706. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  707. return NULL;
  708. return static_cast<CGHeroInstance *>(map->objects[objid]);
  709. }
  710. CGTownInstance *CGameState::getTown(int objid)
  711. {
  712. if(objid<0 || objid>=map->objects.size())
  713. return NULL;
  714. return static_cast<CGTownInstance *>(map->objects[objid]);
  715. }
  716. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  717. {
  718. switch(obj->ID)
  719. {
  720. case 65: //random artifact
  721. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  722. case 66: //random treasure artifact
  723. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  724. case 67: //random minor artifact
  725. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  726. case 68: //random major artifact
  727. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  728. case 69: //random relic artifact
  729. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  730. case 70: //random hero
  731. {
  732. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  733. }
  734. case 71: //random monster
  735. {
  736. int r;
  737. do
  738. {
  739. r = ran()%197;
  740. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  741. return std::pair<int,int>(54,r);
  742. }
  743. case 72: //random monster lvl1
  744. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  745. case 73: //random monster lvl2
  746. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  747. case 74: //random monster lvl3
  748. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  749. case 75: //random monster lvl4
  750. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  751. case 76: //random resource
  752. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  753. case 77: //random town
  754. {
  755. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  756. f;
  757. if(align>PLAYER_LIMIT-1)//same as owner / random
  758. {
  759. if(obj->tempOwner > PLAYER_LIMIT-1)
  760. f = -1; //random
  761. else
  762. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  763. }
  764. else
  765. {
  766. f = scenarioOps->getIthPlayersSettings(align).castle;
  767. }
  768. if(f<0) f = ran()%VLC->townh->towns.size();
  769. return std::pair<int,int>(TOWNI_TYPE,f);
  770. }
  771. case 162: //random monster lvl5
  772. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  773. case 163: //random monster lvl6
  774. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  775. case 164: //random monster lvl7
  776. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  777. case 216: //random dwelling
  778. {
  779. int faction = ran()%F_NUMBER;
  780. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(obj->info);
  781. if (info->asCastle)
  782. {
  783. for(unsigned int i=0;i<map->objects.size();i++)
  784. {
  785. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  786. {
  787. randomizeObject(map->objects[i]); //we have to randomize the castle first
  788. faction = map->objects[i]->subID;
  789. break;
  790. }
  791. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  792. {
  793. faction = map->objects[i]->subID;
  794. break;
  795. }
  796. }
  797. }
  798. else
  799. {
  800. while((!(info->castles[0]&(1<<faction))))
  801. {
  802. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  803. break;
  804. faction = ran()%F_NUMBER;
  805. }
  806. }
  807. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  808. int cid = VLC->townh->towns[faction].basicCreatures[level];
  809. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  810. if(VLC->objh->cregens[i]==cid)
  811. return std::pair<int,int>(17,i);
  812. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  813. return std::pair<int,int>(17,0);
  814. }
  815. case 217:
  816. {
  817. int faction = ran()%F_NUMBER;
  818. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(obj->info);
  819. if (info->asCastle)
  820. {
  821. for(unsigned int i=0;i<map->objects.size();i++)
  822. {
  823. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  824. {
  825. randomizeObject(map->objects[i]); //we have to randomize the castle first
  826. faction = map->objects[i]->subID;
  827. break;
  828. }
  829. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  830. {
  831. faction = map->objects[i]->subID;
  832. break;
  833. }
  834. }
  835. }
  836. else
  837. {
  838. while((!(info->castles[0]&(1<<faction))))
  839. {
  840. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  841. break;
  842. faction = ran()%F_NUMBER;
  843. }
  844. }
  845. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  846. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  847. if(VLC->objh->cregens[i]==cid)
  848. return std::pair<int,int>(17,i);
  849. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  850. return std::pair<int,int>(17,0);
  851. }
  852. case 218:
  853. {
  854. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(obj->info);
  855. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  856. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  857. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  858. if(VLC->objh->cregens[i]==cid)
  859. return std::pair<int,int>(17,i);
  860. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  861. return std::pair<int,int>(17,0);
  862. }
  863. }
  864. return std::pair<int,int>(-1,-1);
  865. }
  866. void CGameState::randomizeObject(CGObjectInstance *cur)
  867. {
  868. std::pair<int,int> ran = pickObject(cur);
  869. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  870. {
  871. if(cur->ID==TOWNI_TYPE) //town - set def
  872. {
  873. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  874. if(t->hasCapitol())
  875. t->defInfo = capitols[t->subID];
  876. else if(t->hasFort())
  877. t->defInfo = forts[t->subID];
  878. else
  879. t->defInfo = villages[t->subID];
  880. }
  881. return;
  882. }
  883. else if(ran.first==HEROI_TYPE)//special code for hero
  884. {
  885. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  886. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  887. cur->ID = ran.first;
  888. h->portrait = cur->subID = ran.second;
  889. h->type = VLC->heroh->heroes[ran.second];
  890. map->heroes.push_back(h);
  891. return; //TODO: maybe we should do something with definfo?
  892. }
  893. else if(ran.first==TOWNI_TYPE)//special code for town
  894. {
  895. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  896. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  897. cur->ID = ran.first;
  898. cur->subID = ran.second;
  899. t->town = &VLC->townh->towns[ran.second];
  900. if(t->hasCapitol())
  901. t->defInfo = capitols[t->subID];
  902. else if(t->hasFort())
  903. t->defInfo = forts[t->subID];
  904. else
  905. t->defInfo = villages[t->subID];
  906. map->towns.push_back(t);
  907. return;
  908. }
  909. //we have to replace normal random object
  910. cur->ID = ran.first;
  911. cur->subID = ran.second;
  912. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  913. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  914. if(!cur->defInfo)
  915. {
  916. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  917. return;
  918. }
  919. map->addBlockVisTiles(cur);
  920. }
  921. int CGameState::getDate(int mode) const
  922. {
  923. int temp;
  924. switch (mode)
  925. {
  926. case 0:
  927. return day;
  928. break;
  929. case 1:
  930. temp = (day)%7;
  931. if (temp)
  932. return temp;
  933. else return 7;
  934. break;
  935. case 2:
  936. temp = ((day-1)/7)+1;
  937. if (!(temp%4))
  938. return 4;
  939. else
  940. return (temp%4);
  941. break;
  942. case 3:
  943. return ((day-1)/28)+1;
  944. break;
  945. }
  946. return 0;
  947. }
  948. CGameState::CGameState()
  949. {
  950. mx = new boost::shared_mutex();
  951. map = NULL;
  952. curB = NULL;
  953. scenarioOps = NULL;
  954. applierGs = new CGSApplier;
  955. }
  956. CGameState::~CGameState()
  957. {
  958. delete mx;
  959. delete map;
  960. delete curB;
  961. delete scenarioOps;
  962. delete applierGs;
  963. }
  964. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  965. {
  966. day = 0;
  967. seed = Seed;
  968. ran.seed((boost::int32_t)seed);
  969. scenarioOps = si;
  970. this->map = map;
  971. loadTownDInfos();
  972. //picking random factions for players
  973. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  974. {
  975. if(scenarioOps->playerInfos[i].castle==-1)
  976. {
  977. int f;
  978. do
  979. {
  980. f = ran()%F_NUMBER;
  981. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  982. scenarioOps->playerInfos[i].castle = f;
  983. }
  984. }
  985. //randomizing objects
  986. for(unsigned int no=0; no<map->objects.size(); ++no)
  987. {
  988. randomizeObject(map->objects[no]);
  989. if(map->objects[no]->ID==26)
  990. {
  991. map->objects[no]->defInfo->handler=NULL;
  992. }
  993. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  994. }
  995. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  996. /*********give starting hero****************************************/
  997. for(int i=0;i<PLAYER_LIMIT;i++)
  998. {
  999. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1000. {
  1001. int3 hpos = map->players[i].posOfMainTown;
  1002. hpos.x+=1;// hpos.y+=1;
  1003. int j;
  1004. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1005. if(scenarioOps->playerInfos[j].color == i)
  1006. break;
  1007. if(j == scenarioOps->playerInfos.size())
  1008. continue;
  1009. int h=pickHero(i);
  1010. if(scenarioOps->playerInfos[j].hero == -1)
  1011. scenarioOps->playerInfos[j].hero = h;
  1012. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1013. nnn->id = map->objects.size();
  1014. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1015. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1016. {
  1017. if(map->towns[o]->pos == hpos)
  1018. {
  1019. map->towns[o]->visitingHero = nnn;
  1020. nnn->visitedTown = map->towns[o];
  1021. nnn->inTownGarrison = false;
  1022. break;
  1023. }
  1024. }
  1025. nnn->initHero();
  1026. map->heroes.push_back(nnn);
  1027. map->objects.push_back(nnn);
  1028. map->addBlockVisTiles(nnn);
  1029. }
  1030. }
  1031. /*********creating players entries in gs****************************************/
  1032. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1033. {
  1034. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1035. ins.second.color=ins.first;
  1036. ins.second.serial=i;
  1037. ins.second.human = scenarioOps->playerInfos[i].human;
  1038. players.insert(ins);
  1039. }
  1040. /******************RESOURCES****************************************************/
  1041. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1042. std::vector<int> startres;
  1043. std::ifstream tis("config/startres.txt");
  1044. int k;
  1045. for (int j=0;j<scenarioOps->difficulty;j++)
  1046. {
  1047. tis >> k;
  1048. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1049. tis>>k;
  1050. }
  1051. tis >> k;
  1052. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1053. {
  1054. tis >> k;
  1055. startres.push_back(k);
  1056. }
  1057. tis.close();
  1058. tis.clear();
  1059. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1060. {
  1061. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1062. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1063. (*i).second.resources[x] = startres[x];
  1064. }
  1065. tis.open("config/resources.txt");
  1066. tis >> k;
  1067. int pom;
  1068. for(int i=0;i<k;i++)
  1069. {
  1070. tis >> pom;
  1071. resVals.push_back(pom);
  1072. }
  1073. /*************************HEROES************************************************/
  1074. std::set<int> hids;
  1075. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1076. if(map->allowedHeroes[i])
  1077. hids.insert(i);
  1078. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1079. {
  1080. if (map->heroes[i]->getOwner()<0)
  1081. {
  1082. tlog2 << "Warning - hero with uninitialized owner!\n";
  1083. continue;
  1084. }
  1085. CGHeroInstance * vhi = (map->heroes[i]);
  1086. vhi->initHero();
  1087. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1088. hids.erase(vhi->subID);
  1089. }
  1090. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1091. {
  1092. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1093. continue;
  1094. map->predefinedHeroes[i]->initHero();
  1095. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1096. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1097. hids.erase(map->predefinedHeroes[i]->subID);
  1098. }
  1099. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1100. {
  1101. CGHeroInstance * vhi = new CGHeroInstance();
  1102. vhi->initHero(hid);
  1103. hpool.heroesPool[hid] = vhi;
  1104. hpool.pavailable[hid] = 0xff;
  1105. }
  1106. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1107. {
  1108. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1109. }
  1110. /*************************FOG**OF**WAR******************************************/
  1111. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1112. {
  1113. k->second.fogOfWarMap.resize(map->width);
  1114. for(int g=0; g<map->width; ++g)
  1115. k->second.fogOfWarMap[g].resize(map->height);
  1116. for(int g=-0; g<map->width; ++g)
  1117. for(int h=0; h<map->height; ++h)
  1118. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1119. for(int g=0; g<map->width; ++g)
  1120. for(int h=0; h<map->height; ++h)
  1121. for(int v=0; v<map->twoLevel+1; ++v)
  1122. k->second.fogOfWarMap[g][h][v] = 0;
  1123. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1124. {
  1125. if(obj->tempOwner != k->first) continue; //not a flagged object
  1126. int3 objCenter = obj->getSightCenter();
  1127. int radious = obj->getSightRadious();
  1128. for (int xd = std::max<int>(objCenter.x - radious , 0); xd <= std::min<int>(objCenter.x + radious, map->width - 1); xd++)
  1129. {
  1130. for (int yd = std::max<int>(objCenter.y - radious, 0); yd <= std::min<int>(objCenter.y + radious, map->height - 1); yd++)
  1131. {
  1132. double distance = objCenter.dist2d(int3(xd,yd,objCenter.z)) - 0.5;
  1133. if(distance <= radious)
  1134. k->second.fogOfWarMap[xd][yd][objCenter.z] = 1;
  1135. }
  1136. }
  1137. }
  1138. //for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1139. //{
  1140. // for(int yd=0; yd<map->height; ++yd)
  1141. // {
  1142. // for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1143. // {
  1144. // int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1145. // int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1146. // if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1147. // k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1148. // }
  1149. // }
  1150. //}
  1151. //starting bonus
  1152. if(si->playerInfos[k->second.serial].bonus==brandom)
  1153. si->playerInfos[k->second.serial].bonus = ran()%3;
  1154. switch(si->playerInfos[k->second.serial].bonus)
  1155. {
  1156. case bgold:
  1157. k->second.resources[6] += 500 + (ran()%6)*100;
  1158. break;
  1159. case bresource:
  1160. {
  1161. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1162. if(res == 127)
  1163. {
  1164. k->second.resources[0] += 5 + ran()%6;
  1165. k->second.resources[2] += 5 + ran()%6;
  1166. }
  1167. else
  1168. {
  1169. k->second.resources[res] += 3 + ran()%4;
  1170. }
  1171. break;
  1172. }
  1173. case bartifact:
  1174. {
  1175. if(!k->second.heroes.size())
  1176. {
  1177. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1178. break;
  1179. }
  1180. CArtifact *toGive;
  1181. do
  1182. {
  1183. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1184. } while (!map->allowedArtifact[toGive->id]);
  1185. CGHeroInstance *hero = k->second.heroes[0];
  1186. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1187. if(slot!=toGive->possibleSlots.end())
  1188. {
  1189. hero->artifWorn[*slot] = toGive->id;
  1190. hero->recreateArtBonuses();
  1191. }
  1192. else
  1193. hero->artifacts.push_back(toGive->id);
  1194. }
  1195. }
  1196. }
  1197. /****************************TOWNS************************************************/
  1198. for (unsigned int i=0;i<map->towns.size();i++)
  1199. {
  1200. CGTownInstance * vti =(map->towns[i]);
  1201. if(!vti->town)
  1202. vti->town = &VLC->townh->towns[vti->subID];
  1203. if (vti->name.length()==0) // if town hasn't name we draw it
  1204. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1205. //init buildings
  1206. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1207. {
  1208. vti->builtBuildings.erase(-50);
  1209. vti->builtBuildings.insert(10);
  1210. vti->builtBuildings.insert(5);
  1211. vti->builtBuildings.insert(30);
  1212. if(ran()%2)
  1213. vti->builtBuildings.insert(31);
  1214. }
  1215. //init spells
  1216. vti->spells.resize(SPELL_LEVELS);
  1217. CSpell *s;
  1218. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1219. {
  1220. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1221. vti->spells[s->level-1].push_back(s->id);
  1222. vti->possibleSpells -= s->id;
  1223. }
  1224. while(vti->possibleSpells.size())
  1225. {
  1226. ui32 total=0, sel=-1;
  1227. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1228. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1229. int r = (total)? ran()%total : -1;
  1230. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1231. {
  1232. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1233. if(r<0)
  1234. {
  1235. sel = ps;
  1236. break;
  1237. }
  1238. }
  1239. if(sel<0)
  1240. sel=0;
  1241. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1242. vti->spells[s->level-1].push_back(s->id);
  1243. vti->possibleSpells -= s->id;
  1244. }
  1245. //init garrisons
  1246. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1247. {
  1248. if(j->second.first > 196 && j->second.first < 211)
  1249. {
  1250. if(j->second.first%2)
  1251. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1252. else
  1253. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1254. }
  1255. }
  1256. if(vti->getOwner() != 255)
  1257. getPlayer(vti->getOwner())->towns.push_back(vti);
  1258. }
  1259. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1260. {
  1261. if(k->first==-1 || k->first==255)
  1262. continue;
  1263. //init visiting and garrisoned heroes
  1264. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1265. {
  1266. for(unsigned int m=0; m<k->second.towns.size();m++)
  1267. {
  1268. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1269. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1270. {
  1271. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1272. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1273. k->second.heroes[l]->inTownGarrison = false;
  1274. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1275. k->second.heroes[l]->pos.x -= 1;
  1276. break;
  1277. }
  1278. }
  1279. }
  1280. }
  1281. for(unsigned int i=0; i<map->defy.size(); i++)
  1282. {
  1283. map->defy[i]->serial = i;
  1284. }
  1285. for(unsigned int i=0; i<map->objects.size(); i++)
  1286. {
  1287. map->objects[i]->initObj();
  1288. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1289. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1290. }
  1291. }
  1292. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1293. {
  1294. return true;
  1295. }
  1296. bool CGameState::battleCanFlee(int player)
  1297. {
  1298. if(!curB) //there is no battle
  1299. return false;
  1300. const CGHeroInstance *h1 = getHero(curB->hero1);
  1301. const CGHeroInstance *h2 = getHero(curB->hero2);
  1302. if(h1 && h1->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1303. || h2 && h2->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE))
  1304. return false;
  1305. return true;
  1306. }
  1307. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1308. {
  1309. if(!curB)
  1310. return -1;
  1311. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1312. {
  1313. if((curB->stacks[g]->position == pos
  1314. || (curB->stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  1315. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1316. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1317. ))
  1318. && (!onlyAlive || curB->stacks[g]->alive())
  1319. )
  1320. return curB->stacks[g]->ID;
  1321. }
  1322. return -1;
  1323. }
  1324. int CGameState::battleGetBattlefieldType(int3 tile)
  1325. {
  1326. if(tile==int3() && curB)
  1327. tile = curB->tile;
  1328. else if(tile==int3() && !curB)
  1329. return -1;
  1330. const std::vector <CGObjectInstance*> & objs = map->objects;
  1331. for(int g=0; g<objs.size(); ++g)
  1332. {
  1333. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1334. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1335. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1336. ) //look only for objects covering given tile
  1337. continue;
  1338. switch(objs[g]->ID)
  1339. {
  1340. case 222: //clover field
  1341. return 19;
  1342. case 21: case 223: //cursed ground
  1343. return 22;
  1344. case 224: //evil fog
  1345. return 20;
  1346. case 225: //favourable winds
  1347. return 21;
  1348. case 226: //fiery fields
  1349. return 14;
  1350. case 227: //holy ground
  1351. return 18;
  1352. case 228: //lucid pools
  1353. return 17;
  1354. case 229: //magic clouds
  1355. return 16;
  1356. case 46: case 230: //magic plains
  1357. return 9;
  1358. case 231: //rocklands
  1359. return 15;
  1360. }
  1361. }
  1362. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1363. {
  1364. case TerrainTile::dirt:
  1365. return rand()%3+3;
  1366. case TerrainTile::sand:
  1367. return 2; //TODO: coast support
  1368. case TerrainTile::grass:
  1369. return rand()%2+6;
  1370. case TerrainTile::snow:
  1371. return rand()%2+10;
  1372. case TerrainTile::swamp:
  1373. return 13;
  1374. case TerrainTile::rough:
  1375. return 23;
  1376. case TerrainTile::subterranean:
  1377. return 12;
  1378. case TerrainTile::lava:
  1379. return 8;
  1380. case TerrainTile::water:
  1381. return 25;
  1382. case TerrainTile::rock:
  1383. return 15;
  1384. default:
  1385. return -1;
  1386. }
  1387. }
  1388. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1389. {
  1390. UpgradeInfo ret;
  1391. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1392. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1393. {
  1394. CGTownInstance * t;
  1395. if(obj->ID == TOWNI_TYPE)
  1396. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1397. else
  1398. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1399. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1400. {
  1401. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1402. {
  1403. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1404. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1405. {
  1406. ret.newID.push_back(nid);
  1407. ret.cost.push_back(std::set<std::pair<int,int> >());
  1408. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1409. {
  1410. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1411. if(dif)
  1412. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1413. }
  1414. }
  1415. }
  1416. }//end for
  1417. }
  1418. //TODO: check if hero ability makes some upgrades possible
  1419. if(ret.newID.size())
  1420. ret.oldID = base->idNumber;
  1421. return ret;
  1422. }
  1423. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1424. {
  1425. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1426. if(mode) return -1; //todo - support other modes
  1427. int mcount = 0;
  1428. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1429. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1430. mcount++;
  1431. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1432. return ret;
  1433. }
  1434. void CGameState::loadTownDInfos()
  1435. {
  1436. for(int i=0;i<F_NUMBER;i++)
  1437. {
  1438. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1439. forts[i] = VLC->dobjinfo->castles[i];
  1440. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1441. }
  1442. }
  1443. void CGameState::getNeighbours(int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand)
  1444. {
  1445. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1446. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1447. vec.clear();
  1448. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1449. {
  1450. int3 hlp = tile + dirs[i];
  1451. if(!map->isInTheMap(hlp))
  1452. continue;
  1453. if((indeterminate(onLand) || onLand == (map->getTile(hlp).tertype!=8) )
  1454. && map->getTile(hlp).tertype!=9)
  1455. {
  1456. vec.push_back(hlp);
  1457. }
  1458. }
  1459. }
  1460. int CGameState::getMovementCost(const CGHeroInstance *h, int3 src, int3 dest, int remainingMovePoints, bool checkLast)
  1461. {
  1462. if(src == dest) //same tile
  1463. return 0;
  1464. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1465. &d = map->terrain[dest.x][dest.y][dest.z];
  1466. //get basic cost
  1467. int ret = h->getTileCost(d,s);
  1468. if(src.x!=dest.x && src.y!=dest.y) //it's diagonal move
  1469. {
  1470. int old = ret;
  1471. ret *= 1.414;
  1472. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1473. if(ret > remainingMovePoints && remainingMovePoints > old)
  1474. {
  1475. return remainingMovePoints;
  1476. }
  1477. }
  1478. int left = remainingMovePoints-ret;
  1479. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1480. {
  1481. std::vector<int3> vec;
  1482. getNeighbours(dest, vec, s.tertype != TerrainTile::water);
  1483. for(size_t i=0; i < vec.size(); i++)
  1484. {
  1485. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1486. if(fcost <= left)
  1487. {
  1488. return ret;
  1489. }
  1490. }
  1491. ret = remainingMovePoints;
  1492. }
  1493. return ret;
  1494. }
  1495. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1496. {
  1497. int ret = 7; //allowed by default
  1498. //checking resources
  1499. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1500. if(!pom)return 8;
  1501. if(pom->Name().size()==0||pom->resources.size()==0)return 2;//TODO: why does this happen?
  1502. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1503. {
  1504. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1505. ret = 6; //lack of res
  1506. }
  1507. //checking for requirements
  1508. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][ID].begin();
  1509. ri != VLC->townh->requirements[t->subID][ID].end();
  1510. ri++ )
  1511. {
  1512. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1513. ret = 8; //lack of requirements - cannot build
  1514. }
  1515. //can we build it?
  1516. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1517. ret = 2; //forbidden
  1518. else if(t->builded >= MAX_BUILDING_PER_TURN)
  1519. ret = 5; //building limit
  1520. if(ID == 13) //capitol
  1521. {
  1522. for(unsigned int in = 0; in < map->towns.size(); in++)
  1523. {
  1524. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1525. {
  1526. ret = 0; //no more than one capitol
  1527. break;
  1528. }
  1529. }
  1530. }
  1531. else if(ID == 6) //shipyard
  1532. {
  1533. int3 t1(t->pos + int3(-1,3,0)),
  1534. t2(t->pos + int3(-3,3,0));
  1535. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1536. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1537. ret = 1; //lack of water
  1538. }
  1539. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1540. ret = 4;
  1541. return ret;
  1542. }
  1543. void CGameState::apply(CPack *pack)
  1544. {
  1545. ui16 typ = typeList.getTypeID(pack);
  1546. assert(typ >= 0);
  1547. applierGs->apps[typ]->applyOnGS(this,pack);
  1548. }
  1549. PlayerState * CGameState::getPlayer( ui8 color )
  1550. {
  1551. if(vstd::contains(players,color))
  1552. {
  1553. return &players[color];
  1554. }
  1555. else
  1556. {
  1557. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1558. return NULL;
  1559. }
  1560. }
  1561. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1562. {
  1563. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1564. return false;
  1565. int3 hpos = hero->getPosition(false);
  1566. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1567. if (!hero->canWalkOnSea())
  1568. blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1569. else
  1570. blockLandSea = boost::logic::indeterminate;
  1571. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1572. //graph initialization
  1573. std::vector< std::vector<CPathNode> > graph;
  1574. graph.resize(map->width);
  1575. for(size_t i=0; i<graph.size(); ++i)
  1576. {
  1577. graph[i].resize(map->height);
  1578. for(size_t j=0; j<graph[i].size(); ++j)
  1579. {
  1580. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1581. CPathNode &node = graph[i][j];
  1582. node.accesible = !tinfo->blocked;
  1583. node.dist = -1;
  1584. node.theNodeBefore = NULL;
  1585. node.visited = false;
  1586. node.coord.x = i;
  1587. node.coord.y = j;
  1588. node.coord.z = dest.z;
  1589. if ((tinfo->tertype == TerrainTile::rock) //it's rock
  1590. || ((blockLandSea) && (tinfo->tertype == TerrainTile::water)) //it's sea and we cannot walk on sea
  1591. || ((!blockLandSea) && (tinfo->tertype != TerrainTile::water)) //it's land and we cannot walk on land
  1592. || !FoW[i][j][src.z] //tile is covered by the FoW
  1593. )
  1594. {
  1595. node.accesible = false;
  1596. }
  1597. }
  1598. }
  1599. //Special rules for the destination tile
  1600. {
  1601. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1602. CPathNode &d = graph[dest.x][dest.y];
  1603. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1604. if(t->visitable)
  1605. {
  1606. d.accesible = true; //for allowing visiting objects
  1607. }
  1608. if(blockLandSea && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1609. {
  1610. size_t i = 0;
  1611. for(; i < t->visitableObjects.size(); i++)
  1612. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1613. break;
  1614. d.accesible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1615. }
  1616. else if(!blockLandSea && t->tertype != TerrainTile::water) //hero is moving by water
  1617. {
  1618. d.accesible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1619. }
  1620. }
  1621. //graph initialized
  1622. //initial tile - set cost on 0 and add to the queue
  1623. graph[src.x][src.y].dist = 0;
  1624. std::queue<CPathNode> mq;
  1625. mq.push(graph[src.x][src.y]);
  1626. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1627. std::vector<int3> neighbours;
  1628. neighbours.reserve(8);
  1629. while(!mq.empty())
  1630. {
  1631. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1632. mq.pop();
  1633. if (cp.coord == dest) //it's destination tile
  1634. {
  1635. if (cp.dist < curDist) //that path is better than previous one
  1636. curDist = cp.dist;
  1637. continue;
  1638. }
  1639. else
  1640. {
  1641. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1642. continue;
  1643. }
  1644. //add accessible neighbouring nodes to the queue
  1645. getNeighbours(cp.coord, neighbours, boost::logic::indeterminate);
  1646. for(unsigned int i=0; i < neighbours.size(); i++)
  1647. {
  1648. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1649. if(dp.accesible)
  1650. {
  1651. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1652. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accesible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1653. {
  1654. dp.dist = cp.dist + cost;
  1655. dp.theNodeBefore = &cp;
  1656. mq.push(dp);
  1657. }
  1658. }
  1659. }
  1660. }
  1661. CPathNode *curNode = &graph[dest.x][dest.y];
  1662. if(!curNode->theNodeBefore) //destination is not accessible
  1663. return false;
  1664. //fill ret with found path
  1665. ret.nodes.clear();
  1666. while(curNode->coord != graph[src.x][src.y].coord)
  1667. {
  1668. ret.nodes.push_back(*curNode);
  1669. curNode = curNode->theNodeBefore;
  1670. }
  1671. ret.nodes.push_back(graph[src.x][src.y]);
  1672. return true;
  1673. }
  1674. bool CGameState::isVisible(int3 pos, int player)
  1675. {
  1676. if(player == 255) //neutral player
  1677. return false;
  1678. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  1679. }
  1680. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1681. {
  1682. if(player == 255) //neutral player
  1683. return false;
  1684. //object is visible when at least one blocked tile is visible
  1685. for(int fx=0; fx<8; ++fx)
  1686. {
  1687. for(int fy=0; fy<6; ++fy)
  1688. {
  1689. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1690. if(map->isInTheMap(pos)
  1691. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1692. && isVisible(pos, player) )
  1693. return true;
  1694. }
  1695. }
  1696. return false;
  1697. }
  1698. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1699. {
  1700. const TerrainTile * pom = &map->getTile(dst);
  1701. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1702. {
  1703. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1704. continue;
  1705. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1706. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1707. {
  1708. return false;
  1709. }
  1710. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1711. {
  1712. return false;
  1713. }
  1714. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1715. {
  1716. return false;
  1717. }
  1718. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1719. {
  1720. return false;
  1721. }
  1722. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1723. {
  1724. return false;
  1725. }
  1726. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1727. {
  1728. return false;
  1729. }
  1730. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1731. {
  1732. return false;
  1733. }
  1734. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1735. {
  1736. return false;
  1737. }
  1738. }
  1739. return true;
  1740. }
  1741. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  1742. {
  1743. int attackDefenseBonus,
  1744. minDmg = attacker->creature->damageMin * attacker->amount,
  1745. maxDmg = attacker->creature->damageMax * attacker->amount;
  1746. if(attacker->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //any siege weapon, but only ballista can attack
  1747. { //minDmg and maxDmg are multiplied by hero attack + 1
  1748. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  1749. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  1750. }
  1751. if(attacker->hasFeatureOfType(StackFeature::GENERAL_ATTACK_REDUCTION))
  1752. {
  1753. attackDefenseBonus = attacker->Attack() * (attacker->valOfFeatures(StackFeature::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f) - defender->Defense();
  1754. }
  1755. else
  1756. {
  1757. attackDefenseBonus = attacker->Attack() - defender->Defense();
  1758. }
  1759. //calculating total attack/defense skills modifier
  1760. if(!shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 0)) //bloodlust handling (etc.)
  1761. {
  1762. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 0);
  1763. }
  1764. if(shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 1)) //precision handling (etc.)
  1765. {
  1766. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 1);
  1767. }
  1768. if(attacker->getEffect(55)) //slayer handling
  1769. {
  1770. std::vector<int> affectedIds;
  1771. switch(attacker->getEffect(55)->level)
  1772. {
  1773. case 3: //expert
  1774. {
  1775. affectedIds.push_back(40); //giant
  1776. affectedIds.push_back(41); //titan
  1777. affectedIds.push_back(152); //lord of thunder
  1778. } //continue adding ...
  1779. case 2: //advanced
  1780. {
  1781. affectedIds.push_back(12); //angel
  1782. affectedIds.push_back(13); //archangel
  1783. affectedIds.push_back(54); //devil
  1784. affectedIds.push_back(55); //arch devil
  1785. affectedIds.push_back(150); //supreme archangel
  1786. affectedIds.push_back(153); //antichrist
  1787. } //continue adding ...
  1788. case 0: case 1: //none and basic
  1789. {
  1790. affectedIds.push_back(26); //green dragon
  1791. affectedIds.push_back(27); //gold dragon
  1792. affectedIds.push_back(82); //red dragon
  1793. affectedIds.push_back(83); //black dragon
  1794. affectedIds.push_back(96); //behemot
  1795. affectedIds.push_back(97); //ancient behemot
  1796. affectedIds.push_back(110); //hydra
  1797. affectedIds.push_back(111); //chaos hydra
  1798. affectedIds.push_back(132); //azure dragon
  1799. affectedIds.push_back(133); //crystal dragon
  1800. affectedIds.push_back(134); //faerie dragon
  1801. affectedIds.push_back(135); //rust dragon
  1802. affectedIds.push_back(151); //diamond dragon
  1803. affectedIds.push_back(154); //blood dragon
  1804. affectedIds.push_back(155); //darkness dragon
  1805. affectedIds.push_back(156); //ghost behemot
  1806. affectedIds.push_back(157); //hell hydra
  1807. break;
  1808. }
  1809. }
  1810. for(unsigned int g=0; g<affectedIds.size(); ++g)
  1811. {
  1812. if(defender->creature->idNumber == affectedIds[g])
  1813. {
  1814. attackDefenseBonus += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  1815. break;
  1816. }
  1817. }
  1818. }
  1819. float dmgBonusMultiplier = 1.0f;
  1820. //applying jousting bonus
  1821. if( attacker->hasFeatureOfType(StackFeature::JOUSTING) && !defender->hasFeatureOfType(StackFeature::CHARGE_IMMUNITY) )
  1822. dmgBonusMultiplier += charge * 0.05f;
  1823. //bonus from attack/defense skills
  1824. if(attackDefenseBonus < 0) //decreasing dmg
  1825. {
  1826. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1827. {
  1828. dmgBonusMultiplier += -0.3f;
  1829. }
  1830. else
  1831. {
  1832. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1833. }
  1834. }
  1835. else //increasing dmg
  1836. {
  1837. if(0.05f * attackDefenseBonus > 4.0f)
  1838. {
  1839. dmgBonusMultiplier += 4.0f;
  1840. }
  1841. else
  1842. {
  1843. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1844. }
  1845. }
  1846. //handling secondary abilities and artifacts giving premies to them
  1847. if(attackerHero)
  1848. {
  1849. if(shooting)
  1850. {
  1851. switch(attackerHero->getSecSkillLevel(1)) //archery
  1852. {
  1853. case 1: //basic
  1854. dmgBonusMultiplier += 0.1f;
  1855. break;
  1856. case 2: //advanced
  1857. dmgBonusMultiplier += 0.25f;
  1858. break;
  1859. case 3: //expert
  1860. dmgBonusMultiplier += 0.5f;
  1861. break;
  1862. }
  1863. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  1864. {
  1865. //apply artifact premy to archery
  1866. dmgBonusMultiplier += attackerHero->valOfBonuses(HeroBonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  1867. }
  1868. }
  1869. else
  1870. {
  1871. switch(attackerHero->getSecSkillLevel(22)) //offense
  1872. {
  1873. case 1: //basic
  1874. dmgBonusMultiplier += 0.1f;
  1875. break;
  1876. case 2: //advanced
  1877. dmgBonusMultiplier += 0.2f;
  1878. break;
  1879. case 3: //expert
  1880. dmgBonusMultiplier += 0.3f;
  1881. break;
  1882. }
  1883. }
  1884. }
  1885. if(defendingHero)
  1886. {
  1887. switch(defendingHero->getSecSkillLevel(23)) //armorer
  1888. {
  1889. case 1: //basic
  1890. dmgBonusMultiplier *= 0.95f;
  1891. break;
  1892. case 2: //advanced
  1893. dmgBonusMultiplier *= 0.9f;
  1894. break;
  1895. case 3: //expert
  1896. dmgBonusMultiplier *= 0.85f;
  1897. break;
  1898. }
  1899. }
  1900. //handling hate effect
  1901. if( attacker->hasFeatureOfType(StackFeature::HATE, defender->creature->idNumber) )
  1902. dmgBonusMultiplier += 0.5f;
  1903. //handling spell effects
  1904. if(!shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  1905. {
  1906. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  1907. }
  1908. else if(shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  1909. {
  1910. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  1911. }
  1912. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  1913. {
  1914. dmgBonusMultiplier *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  1915. }
  1916. minDmg *= dmgBonusMultiplier;
  1917. maxDmg *= dmgBonusMultiplier;
  1918. if(attacker->getEffect(42)) //curse handling (rest)
  1919. {
  1920. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  1921. return minDmg;
  1922. }
  1923. else if(attacker->getEffect(41)) //bless handling
  1924. {
  1925. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  1926. return maxDmg;
  1927. }
  1928. else
  1929. {
  1930. if(minDmg != maxDmg)
  1931. return minDmg + rand() % (maxDmg - minDmg + 1);
  1932. else
  1933. return minDmg;
  1934. }
  1935. tlog1 << "We are too far in calculateDmg...\n";
  1936. return -1;
  1937. }
  1938. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1939. {
  1940. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  1941. {
  1942. if(!stacks[i]->alive())
  1943. {
  1944. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1945. }
  1946. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1947. {
  1948. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1949. }
  1950. }
  1951. }
  1952. si8 CGameState::battleMaxSpellLevel()
  1953. {
  1954. if(!curB) //there is not battle
  1955. {
  1956. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  1957. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  1958. }
  1959. si8 levelLimit = SPELL_LEVELS;
  1960. const CGHeroInstance *h1 = getHero(curB->hero1);
  1961. if(h1)
  1962. {
  1963. for(std::list<HeroBonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  1964. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  1965. amin(levelLimit, i->val);
  1966. }
  1967. const CGHeroInstance *h2 = getHero(curB->hero2);
  1968. if(h2)
  1969. {
  1970. for(std::list<HeroBonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  1971. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  1972. amin(levelLimit, i->val);
  1973. }
  1974. return levelLimit;
  1975. }
  1976. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile)
  1977. {
  1978. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, caster->getSpellSchoolLevel(s));
  1979. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurences of two hex creatures*/
  1980. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  1981. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and armageddon
  1982. {
  1983. for(int it=0; it<stacks.size(); ++it)
  1984. {
  1985. if((s->id == 24 && !stacks[it]->creature->isUndead()) //death ripple
  1986. || (s->id == 25 && stacks[it]->creature->isUndead()) //destroy undead
  1987. || (s->id == 26) //armageddon
  1988. )
  1989. {
  1990. attackedCres.insert(stacks[it]);
  1991. }
  1992. }
  1993. }
  1994. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  1995. || VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  1996. {
  1997. if(caster->getSpellSchoolLevel(s) < 3) /*not expert */
  1998. {
  1999. CStack * st = getStackT(destinationTile, onlyAlive);
  2000. if(st)
  2001. attackedCres.insert(st);
  2002. }
  2003. else
  2004. {
  2005. for(int it=0; it<stacks.size(); ++it)
  2006. {
  2007. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2008. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == caster->tempOwner)
  2009. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != caster->tempOwner )
  2010. )
  2011. {
  2012. if(!onlyAlive || stacks[it]->alive())
  2013. attackedCres.insert(stacks[it]);
  2014. }
  2015. }
  2016. } //if(caster->getSpellSchoolLevel(s) < 3)
  2017. }
  2018. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2019. {
  2020. CStack * st = getStackT(destinationTile, onlyAlive);
  2021. if(st)
  2022. attackedCres.insert(st);
  2023. }
  2024. else //custom range from attackedHexes
  2025. {
  2026. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2027. {
  2028. CStack * st = getStackT(*it, onlyAlive);
  2029. if(st)
  2030. attackedCres.insert(st);
  2031. }
  2032. }
  2033. return attackedCres;
  2034. }
  2035. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  2036. {
  2037. switch(spell->id)
  2038. {
  2039. case 56: //frenzy
  2040. return 1;
  2041. default: //other spells
  2042. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(HeroBonus::SPELL_DURATION);
  2043. }
  2044. }
  2045. CStack * BattleInfo::generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position)
  2046. {
  2047. CStack * ret = new CStack(&VLC->creh->creatures[creatureID], amount, owner ? owner->tempOwner : 255, stackID, attackerOwned, slot);
  2048. if(owner)
  2049. {
  2050. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACKS_SPEED), StackFeature::BONUS_FROM_HERO));
  2051. //base luck/morale calculations
  2052. ret->morale = owner->getCurrentMorale(slot, false);
  2053. ret->luck = owner->getCurrentLuck(slot, false);
  2054. //other bonuses
  2055. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(0), StackFeature::BONUS_FROM_HERO));
  2056. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(1), StackFeature::BONUS_FROM_HERO));
  2057. if ( owner->hasBonusOfType(HeroBonus::STACK_HEALTH_PERCENT) ) // e.g. Elixir of Life
  2058. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0,
  2059. (ret->creature->hitPoints * owner->valOfBonuses(HeroBonus::STACK_HEALTH_PERCENT)) / 100,
  2060. StackFeature::BONUS_FROM_HERO));
  2061. if (owner->hasBonusOfType(HeroBonus::HP_REGENERATION)) // e.g. Elixir of Life
  2062. ret->features.push_back(makeFeature(StackFeature::HP_REGENERATION, StackFeature::WHOLE_BATTLE, 0,
  2063. owner->valOfBonuses(HeroBonus::HP_REGENERATION), StackFeature::BONUS_FROM_HERO));
  2064. if (owner->hasBonusOfType(HeroBonus::LEVEL_SPELL_IMMUNITY)) // e.g. Power of the Dragon Father
  2065. ret->features.push_back(makeFeature(StackFeature::LEVEL_SPELL_IMMUNITY, StackFeature::WHOLE_BATTLE, 0,
  2066. owner->valOfBonuses(HeroBonus::LEVEL_SPELL_IMMUNITY), StackFeature::BONUS_FROM_HERO));
  2067. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACK_HEALTH), StackFeature::BONUS_FROM_HERO));
  2068. ret->firstHPleft = ret->MaxHealth();
  2069. }
  2070. else
  2071. {
  2072. ret->morale = 0;
  2073. ret->luck = 0;
  2074. }
  2075. //native terrain bonuses
  2076. int faction = ret->creature->faction;
  2077. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2078. {
  2079. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2080. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2081. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2082. }
  2083. ret->position = position;
  2084. return ret;
  2085. }
  2086. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster)
  2087. {
  2088. ui32 ret = VLC->spellh->spells[sp->id].costs[caster->getSpellSchoolLevel(sp)];
  2089. //checking for friendly stacks reducing cost of the spell
  2090. si32 manaReduction = 0;
  2091. for(int g=0; g<stacks.size(); ++g)
  2092. {
  2093. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasFeatureOfType(StackFeature::CHANGES_SPELL_COST_FOR_ALLY) )
  2094. {
  2095. amin(manaReduction, stacks[g]->valOfFeatures(StackFeature::CHANGES_SPELL_COST_FOR_ALLY));
  2096. }
  2097. }
  2098. return ret + manaReduction;
  2099. }
  2100. CStack * BattleInfo::getNextStack()
  2101. {
  2102. CStack *current = getStack(activeStack);
  2103. for (unsigned int i = 0; i < stacks.size(); i++) //find fastest not moved/waited stack (stacks vector is sorted by speed)
  2104. {
  2105. if(stacks[i]->willMove() && !vstd::contains(stacks[i]->state,WAITING))
  2106. return stacks[i];
  2107. }
  2108. for (int i = stacks.size() - 1; i >= 0 ; i--) //find slowest waiting stack
  2109. {
  2110. if(stacks[i]->willMove())
  2111. return stacks[i];
  2112. }
  2113. return NULL; //all stacks moved or defending!
  2114. }
  2115. std::vector<CStack> BattleInfo::getStackQueue()
  2116. {
  2117. std::vector<CStack> ret;
  2118. std::vector<int> taken; //if non-zero value, corresponding stack has been placed in ret
  2119. taken.resize(stacks.size());
  2120. for(unsigned int g=0; g<taken.size(); ++g)
  2121. {
  2122. taken[g] = 0;
  2123. }
  2124. for(int moved=0; moved<2; ++moved) //in first cycle we add stacks that can act in current turn, in second one the rest of them
  2125. {
  2126. for(unsigned int gc=0; gc<stacks.size(); ++gc)
  2127. {
  2128. int id = -1, speed = -1;
  2129. for(unsigned int i=0; i<stacks.size(); ++i) //find not waited stacks only
  2130. {
  2131. if((moved == 1 ||!vstd::contains(stacks[i]->state, DEFENDING))
  2132. && stacks[i]->alive()
  2133. && (moved == 1 || !vstd::contains(stacks[i]->state, MOVED))
  2134. && !vstd::contains(stacks[i]->state,WAITING)
  2135. && taken[i]==0
  2136. && !stacks[i]->hasFeatureOfType(StackFeature::NOT_ACTIVE)) //eg. Ammo Cart
  2137. {
  2138. if(speed == -1 || stacks[i]->Speed() > speed)
  2139. {
  2140. id = i;
  2141. speed = stacks[i]->Speed();
  2142. }
  2143. }
  2144. }
  2145. if(id != -1)
  2146. {
  2147. ret.push_back(*stacks[id]);
  2148. taken[id] = 1;
  2149. }
  2150. else //choose something from not moved stacks
  2151. {
  2152. int id = -1, speed = 10000; //infinite speed
  2153. for(unsigned int i=0; i<stacks.size(); ++i) //find waited stacks only
  2154. {
  2155. if((moved == 1 ||!vstd::contains(stacks[i]->state, DEFENDING))
  2156. && stacks[i]->alive()
  2157. && (moved == 1 || !vstd::contains(stacks[i]->state, MOVED))
  2158. && vstd::contains(stacks[i]->state,WAITING)
  2159. && taken[i]==0
  2160. && !stacks[i]->hasFeatureOfType(StackFeature::NOT_ACTIVE)) //eg. Ammo Cart
  2161. {
  2162. if(stacks[i]->Speed() < speed) //slowest one
  2163. {
  2164. id = i;
  2165. speed = stacks[i]->Speed();
  2166. }
  2167. }
  2168. }
  2169. if(id != -1)
  2170. {
  2171. ret.push_back(*stacks[id]);
  2172. taken[id] = 1;
  2173. }
  2174. else
  2175. {
  2176. break; //no stacks have been found, so none of them will be found in next iterations
  2177. }
  2178. }
  2179. }
  2180. }
  2181. return ret;
  2182. }
  2183. int3 CPath::startPos() const
  2184. {
  2185. return nodes[nodes.size()-1].coord;
  2186. }
  2187. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2188. {
  2189. if (mode==0)
  2190. {
  2191. for (unsigned int i=0;i<nodes.size();i++)
  2192. {
  2193. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2194. }
  2195. }
  2196. }
  2197. int3 CPath::endPos() const
  2198. {
  2199. return nodes[0].coord;
  2200. }