CGameState.cpp 67 KB

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