CGameState.cpp 62 KB

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