CGameState.cpp 61 KB

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