CGameState.cpp 63 KB

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