CGameState.cpp 61 KB

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