CGameState.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  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 "lib/VCMI_Lib.h"
  17. #include "lib/Connection.h"
  18. #include "map.h"
  19. #include "StartInfo.h"
  20. #include "lib/NetPacks.h"
  21. #include <boost/foreach.hpp>
  22. #include <boost/thread.hpp>
  23. #include <boost/thread/shared_mutex.hpp>
  24. #include "lib/RegisterTypes.h"
  25. boost::rand48 ran;
  26. #ifdef min
  27. #undef min
  28. #endif
  29. #ifdef max
  30. #undef max
  31. #endif
  32. class CBaseForGSApply
  33. {
  34. public:
  35. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  36. };
  37. template <typename T> class CApplyOnGS : public CBaseForGSApply
  38. {
  39. public:
  40. void applyOnGS(CGameState *gs, void *pack) const
  41. {
  42. T *ptr = static_cast<T*>(pack);
  43. ptr->applyGs(gs);
  44. }
  45. };
  46. class CGSApplier
  47. {
  48. public:
  49. std::map<ui16,CBaseForGSApply*> apps;
  50. CGSApplier()
  51. {
  52. registerTypes2(*this);
  53. }
  54. template<typename T> void registerType(const T * t=NULL)
  55. {
  56. ui16 ID = typeList.registerType(t);
  57. apps[ID] = new CApplyOnGS<T>;
  58. }
  59. } *applier = NULL;
  60. std::string DLL_EXPORT toString(MetaString &ms)
  61. {
  62. std::string ret;
  63. for(size_t i=0;i<ms.message.size();++i)
  64. {
  65. if(ms.message[i]>0)
  66. {
  67. ret += ms.strings[ms.message[i]-1];
  68. }
  69. else
  70. {
  71. std::vector<std::string> *vec;
  72. int type = ms.texts[-ms.message[i]-1].first,
  73. ser = ms.texts[-ms.message[i]-1].second;
  74. if(type == 5)
  75. {
  76. ret += VLC->arth->artifacts[ser].Name();
  77. continue;
  78. }
  79. else if(type == 7)
  80. {
  81. ret += VLC->creh->creatures[ser].namePl;
  82. continue;
  83. }
  84. else if(type == 9)
  85. {
  86. ret += VLC->generaltexth->mines[ser].first;
  87. continue;
  88. }
  89. else if(type == 10)
  90. {
  91. ret += VLC->generaltexth->mines[ser].second;
  92. continue;
  93. }
  94. else if(type == MetaString::SPELL_NAME)
  95. {
  96. ret += VLC->spellh->spells[ser].name;
  97. continue;
  98. }
  99. else
  100. {
  101. switch(type)
  102. {
  103. case 1:
  104. vec = &VLC->generaltexth->allTexts;
  105. break;
  106. case 2:
  107. vec = &VLC->generaltexth->xtrainfo;
  108. break;
  109. case 3:
  110. vec = &VLC->generaltexth->names;
  111. break;
  112. case 4:
  113. vec = &VLC->generaltexth->restypes;
  114. break;
  115. case 6:
  116. vec = &VLC->generaltexth->arraytxt;
  117. break;
  118. case 8:
  119. vec = &VLC->generaltexth->creGens;
  120. break;
  121. case 11:
  122. vec = &VLC->generaltexth->advobtxt;
  123. break;
  124. case 12:
  125. vec = &VLC->generaltexth->artifEvents;
  126. break;
  127. }
  128. ret += (*vec)[ser];
  129. }
  130. }
  131. }
  132. for(size_t i=0; i < ms.replacements.size(); ++i)
  133. {
  134. ret.replace(ret.find("%s"),2,ms.replacements[i]);
  135. }
  136. return ret;
  137. }
  138. CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  139. {
  140. CGObjectInstance * nobj;
  141. switch(id)
  142. {
  143. case HEROI_TYPE: //hero
  144. {
  145. CGHeroInstance * nobj = new CGHeroInstance();
  146. nobj->pos = pos;
  147. nobj->tempOwner = owner;
  148. nobj->subID = subid;
  149. //nobj->initHero(ran);
  150. return nobj;
  151. }
  152. case TOWNI_TYPE: //town
  153. nobj = new CGTownInstance;
  154. break;
  155. default: //rest of objects
  156. nobj = new CGObjectInstance;
  157. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  158. break;
  159. }
  160. nobj->ID = id;
  161. nobj->subID = subid;
  162. if(!nobj->defInfo)
  163. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  164. nobj->pos = pos;
  165. //nobj->state = NULL;//new CLuaObjectScript();
  166. nobj->tempOwner = owner;
  167. nobj->info = NULL;
  168. nobj->defInfo->id = id;
  169. nobj->defInfo->subid = subid;
  170. //assigning defhandler
  171. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  172. return nobj;
  173. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  174. return nobj;
  175. }
  176. CStack * BattleInfo::getStack(int stackID)
  177. {
  178. for(int g=0; g<stacks.size(); ++g)
  179. {
  180. if(stacks[g]->ID == stackID)
  181. return stacks[g];
  182. }
  183. return NULL;
  184. }
  185. CStack * BattleInfo::getStackT(int tileID)
  186. {
  187. for(int g=0; g<stacks.size(); ++g)
  188. {
  189. if(stacks[g]->position == tileID
  190. || (stacks[g]->creature->isDoubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  191. || (stacks[g]->creature->isDoubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  192. {
  193. if(stacks[g]->alive())
  194. {
  195. return stacks[g];
  196. }
  197. }
  198. }
  199. return NULL;
  200. }
  201. void BattleInfo::getAccessibilityMap(bool *accessibility, int stackToOmmit)
  202. {
  203. memset(accessibility,1,BFIELD_SIZE); //initialize array with trues
  204. for(int g=0; g<stacks.size(); ++g)
  205. {
  206. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit) //we don't want to lock position of this stack
  207. continue;
  208. accessibility[stacks[g]->position] = false;
  209. if(stacks[g]->creature->isDoubleWide()) //if it's a double hex creature
  210. {
  211. if(stacks[g]->attackerOwned)
  212. accessibility[stacks[g]->position-1] = false;
  213. else
  214. accessibility[stacks[g]->position+1] = false;
  215. }
  216. }
  217. //obstacles
  218. for(int b=0; b<obstacles.size(); ++b)
  219. {
  220. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  221. for(int c=0; c<blocked.size(); ++c)
  222. {
  223. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  224. accessibility[blocked[c]] = false;
  225. }
  226. }
  227. }
  228. void BattleInfo::getAccessibilityMapForTwoHex(bool *accessibility, bool atackerSide, int stackToOmmit, bool addOccupiable) //send pointer to at least 187 allocated bytes
  229. {
  230. bool mac[BFIELD_SIZE];
  231. getAccessibilityMap(mac,stackToOmmit);
  232. memcpy(accessibility,mac,BFIELD_SIZE);
  233. }
  234. void BattleInfo::makeBFS(int start, bool*accessibility, int *predecessor, int *dists) //both pointers must point to the at least 187-elements int arrays
  235. {
  236. //inits
  237. for(int b=0; b<BFIELD_SIZE; ++b)
  238. predecessor[b] = -1;
  239. for(int g=0; g<BFIELD_SIZE; ++g)
  240. dists[g] = 100000000;
  241. std::queue<int> hexq; //bfs queue
  242. hexq.push(start);
  243. dists[hexq.front()] = 0;
  244. int curNext = -1; //for bfs loop only (helper var)
  245. while(!hexq.empty()) //bfs loop
  246. {
  247. int curHex = hexq.front();
  248. std::vector<int> neighbours = neighbouringTiles(curHex);
  249. hexq.pop();
  250. for(int nr=0; nr<neighbours.size(); nr++)
  251. {
  252. curNext = neighbours[nr];
  253. if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  254. continue;
  255. hexq.push(curNext);
  256. dists[curNext] = dists[curHex] + 1;
  257. predecessor[curNext] = curHex;
  258. }
  259. }
  260. };
  261. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable)
  262. {
  263. std::vector<int> ret;
  264. bool ac[BFIELD_SIZE];
  265. CStack *s = getStack(stackID);
  266. if(s->creature->isDoubleWide())
  267. getAccessibilityMapForTwoHex(ac,s->attackerOwned,stackID,addOccupiable);
  268. else
  269. getAccessibilityMap(ac,stackID);
  270. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  271. makeBFS(s->position,ac,pr,dist);
  272. if(s->creature->isDoubleWide())
  273. {
  274. if(!addOccupiable)
  275. {
  276. std::vector<int> rem;
  277. for(int b=0; b<BFIELD_SIZE; ++b)
  278. {
  279. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]))
  280. {
  281. rem.push_back(b);
  282. }
  283. }
  284. for(int g=0; g<rem.size(); ++g)
  285. {
  286. ac[rem[g]] = false;
  287. }
  288. //removing accessibility for side hexes
  289. for(int v=0; v<BFIELD_SIZE; ++v)
  290. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  291. ac[v] = false;
  292. }
  293. else
  294. {
  295. std::vector<int> rem;
  296. for(int b=0; b<BFIELD_SIZE; ++b)
  297. {
  298. 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))
  299. {
  300. rem.push_back(b);
  301. }
  302. }
  303. for(int g=0; g<rem.size(); ++g)
  304. {
  305. ac[rem[g]] = false;
  306. }
  307. }
  308. }
  309. for(int i=0;i<BFIELD_SIZE;i++)
  310. if(dist[i] <= s->speed() && ac[i])
  311. {
  312. ret.push_back(i);
  313. }
  314. return ret;
  315. }
  316. bool BattleInfo::isStackBlocked(int ID)
  317. {
  318. CStack *our = getStack(ID);
  319. for(int i=0; i<stacks.size();i++)
  320. {
  321. if( !stacks[i]->alive()
  322. || stacks[i]->owner==our->owner
  323. )
  324. continue; //we omit dead and allied stacks
  325. if(stacks[i]->creature->isDoubleWide())
  326. {
  327. if( mutualPosition(stacks[i]->position, our->position) >= 0
  328. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  329. return true;
  330. }
  331. else
  332. {
  333. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  334. return true;
  335. }
  336. }
  337. return false;
  338. }
  339. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  340. {
  341. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  342. return 0;
  343. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  344. return 1;
  345. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  346. return 5;
  347. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  348. return 2;
  349. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  350. return 4;
  351. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  352. return 3;
  353. return -1;
  354. }
  355. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  356. {
  357. #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);}
  358. std::vector<int> ret;
  359. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  360. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  361. CHECK_AND_PUSH(hex - 1);
  362. CHECK_AND_PUSH(hex + 1);
  363. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  364. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  365. #undef CHECK_AND_PUSH
  366. return ret;
  367. }
  368. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature)
  369. {
  370. int predecessor[BFIELD_SIZE]; //for getting the Path
  371. int dist[BFIELD_SIZE]; //calculated distances
  372. if(flyingCreature)
  373. {
  374. bool acc[BFIELD_SIZE]; //full accessibility table
  375. for(int b=0; b<BFIELD_SIZE; ++b) //initialization of acc
  376. {
  377. acc[b] = true;
  378. }
  379. makeBFS(start, acc, predecessor, dist);
  380. }
  381. else
  382. {
  383. makeBFS(start, accessibility, predecessor, dist);
  384. }
  385. //making the Path
  386. std::vector<int> path;
  387. int curElem = dest;
  388. while(curElem != start)
  389. {
  390. path.push_back(curElem);
  391. curElem = predecessor[curElem];
  392. }
  393. return std::make_pair(path, dist[dest]);
  394. }
  395. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  396. :creature(C),amount(A), baseAmount(A), owner(O), position(-1), ID(I), attackerOwned(AO), firstHPleft(C->hitPoints),
  397. shots(C->shots), slot(S), counterAttacks(1), effects(), state()
  398. {
  399. abilities = C->abilities;
  400. state.insert(ALIVE);
  401. }
  402. ui32 CStack::speed() const
  403. {
  404. int premy=0;
  405. const StackEffect *effect = 0;
  406. //haste effect check
  407. effect = getEffect(53);
  408. if(effect)
  409. premy += VLC->spellh->spells[effect->id].powers[effect->level];
  410. //slow effect check
  411. effect = getEffect(54);
  412. if(effect)
  413. premy -= (creature->speed * VLC->spellh->spells[effect->id].powers[effect->level])/100;
  414. //prayer effect check
  415. effect = getEffect(48);
  416. if(effect)
  417. premy += VLC->spellh->spells[effect->id].powers[effect->level];
  418. //bind effect check
  419. effect = getEffect(72);
  420. if(effect)
  421. {
  422. premy = creature->speed; //don't use '- creature->speed' - speed is unsigned!
  423. premy = -premy;
  424. }
  425. return creature->speed + premy;
  426. }
  427. const CStack::StackEffect * CStack::getEffect(ui16 id) const
  428. {
  429. for (int i=0; i< effects.size(); i++)
  430. if(effects[i].id == id)
  431. return &effects[i];
  432. return NULL;
  433. }
  434. si8 CStack::Morale() const
  435. {
  436. si8 ret = morale;
  437. if(getEffect(49)) //mirth
  438. {
  439. ret += VLC->spellh->spells[49].powers[getEffect(49)->level];
  440. }
  441. if(getEffect(50)) //sorrow
  442. {
  443. ret -= VLC->spellh->spells[50].powers[getEffect(50)->level];
  444. }
  445. if(ret > 3) ret = 3;
  446. if(ret < -3) ret = -3;
  447. return ret;
  448. }
  449. si8 CStack::Luck() const
  450. {
  451. si8 ret = luck;
  452. if(getEffect(51)) //fortune
  453. {
  454. ret += VLC->spellh->spells[51].powers[getEffect(51)->level];
  455. }
  456. if(getEffect(52)) //misfortune
  457. {
  458. ret -= VLC->spellh->spells[52].powers[getEffect(52)->level];
  459. }
  460. if(ret > 3) ret = 3;
  461. if(ret < -3) ret = -3;
  462. return ret;
  463. }
  464. CGHeroInstance* CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, int notThatOne)
  465. {
  466. if(player<0 || player>=PLAYER_LIMIT)
  467. {
  468. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  469. return NULL;
  470. }
  471. std::vector<CGHeroInstance *> pool;
  472. int sum=0, r;
  473. if(native)
  474. {
  475. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  476. {
  477. if(pavailable[i->first] & 1<<player
  478. && i->second->type->heroType/2 == town->typeID
  479. && i->second->subID != notThatOne
  480. )
  481. {
  482. pool.push_back(i->second);
  483. }
  484. }
  485. if(!pool.size())
  486. return pickHeroFor(false,player,town,notThatOne);
  487. else
  488. return pool[rand()%pool.size()];
  489. }
  490. else
  491. {
  492. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  493. {
  494. if(pavailable[i->first] & 1<<player
  495. && i->second->subID != notThatOne
  496. )
  497. {
  498. pool.push_back(i->second);
  499. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  500. }
  501. }
  502. if(!pool.size())
  503. {
  504. tlog1 << "There are no heroes available for player " << player<<"!\n";
  505. return NULL;
  506. }
  507. r = rand()%sum;
  508. for(int i=0; i<pool.size(); i++)
  509. {
  510. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  511. if(r<0)
  512. return pool[i];
  513. }
  514. return pool[pool.size()-1];
  515. }
  516. }
  517. //void CGameState::apply(CPack * pack)
  518. //{
  519. // while(!mx->try_lock())
  520. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  521. // //applyNL(pack);
  522. // mx->unlock();
  523. //}
  524. int CGameState::pickHero(int owner)
  525. {
  526. int h=-1;
  527. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  528. return h;
  529. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  530. int i=0;
  531. do //try to find free hero of our faction
  532. {
  533. i++;
  534. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  535. } while( map->getHero(h) && i<175);
  536. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  537. {
  538. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  539. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  540. if(!map->getHero(j))
  541. h=j;
  542. }
  543. return h;
  544. }
  545. CGHeroInstance *CGameState::getHero(int objid)
  546. {
  547. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=34)
  548. return NULL;
  549. return static_cast<CGHeroInstance *>(map->objects[objid]);
  550. }
  551. CGTownInstance *CGameState::getTown(int objid)
  552. {
  553. if(objid<0 || objid>=map->objects.size())
  554. return NULL;
  555. return static_cast<CGTownInstance *>(map->objects[objid]);
  556. }
  557. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  558. {
  559. switch(obj->ID)
  560. {
  561. case 65: //random artifact
  562. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  563. case 66: //random treasure artifact
  564. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  565. case 67: //random minor artifact
  566. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  567. case 68: //random major artifact
  568. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  569. case 69: //random relic artifact
  570. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  571. case 70: //random hero
  572. {
  573. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  574. }
  575. case 71: //random monster
  576. {
  577. int r;
  578. do
  579. {
  580. r = ran()%197;
  581. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  582. return std::pair<int,int>(54,r);
  583. }
  584. case 72: //random monster lvl1
  585. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  586. case 73: //random monster lvl2
  587. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  588. case 74: //random monster lvl3
  589. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  590. case 75: //random monster lvl4
  591. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  592. case 76: //random resource
  593. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  594. case 77: //random town
  595. {
  596. int align = ((CGTownInstance*)obj)->alignment,
  597. f;
  598. if(align>PLAYER_LIMIT-1)//same as owner / random
  599. {
  600. if(obj->tempOwner > PLAYER_LIMIT-1)
  601. f = -1; //random
  602. else
  603. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  604. }
  605. else
  606. {
  607. f = scenarioOps->getIthPlayersSettings(align).castle;
  608. }
  609. if(f<0) f = ran()%VLC->townh->towns.size();
  610. return std::pair<int,int>(TOWNI_TYPE,f);
  611. }
  612. case 162: //random monster lvl5
  613. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  614. case 163: //random monster lvl6
  615. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  616. case 164: //random monster lvl7
  617. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  618. case 216: //random dwelling
  619. {
  620. int faction = ran()%F_NUMBER;
  621. CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info;
  622. if (info->asCastle)
  623. {
  624. for(int i=0;i<map->objects.size();i++)
  625. {
  626. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  627. {
  628. randomizeObject(map->objects[i]); //we have to randomize the castle first
  629. faction = map->objects[i]->subID;
  630. break;
  631. }
  632. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  633. {
  634. faction = map->objects[i]->subID;
  635. break;
  636. }
  637. }
  638. }
  639. else
  640. {
  641. while((!(info->castles[0]&(1<<faction))))
  642. {
  643. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  644. break;
  645. faction = ran()%F_NUMBER;
  646. }
  647. }
  648. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  649. int cid = VLC->townh->towns[faction].basicCreatures[level];
  650. for(int i=0;i<VLC->objh->cregens.size();i++)
  651. if(VLC->objh->cregens[i]==cid)
  652. return std::pair<int,int>(17,i);
  653. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  654. return std::pair<int,int>(17,0);
  655. }
  656. case 217:
  657. {
  658. int faction = ran()%F_NUMBER;
  659. CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info;
  660. if (info->asCastle)
  661. {
  662. for(int i=0;i<map->objects.size();i++)
  663. {
  664. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  665. {
  666. randomizeObject(map->objects[i]); //we have to randomize the castle first
  667. faction = map->objects[i]->subID;
  668. break;
  669. }
  670. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  671. {
  672. faction = map->objects[i]->subID;
  673. break;
  674. }
  675. }
  676. }
  677. else
  678. {
  679. while((!(info->castles[0]&(1<<faction))))
  680. {
  681. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  682. break;
  683. faction = ran()%F_NUMBER;
  684. }
  685. }
  686. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  687. for(int i=0;i<VLC->objh->cregens.size();i++)
  688. if(VLC->objh->cregens[i]==cid)
  689. return std::pair<int,int>(17,i);
  690. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  691. return std::pair<int,int>(17,0);
  692. }
  693. case 218:
  694. {
  695. CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info;
  696. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  697. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  698. for(int i=0;i<VLC->objh->cregens.size();i++)
  699. if(VLC->objh->cregens[i]==cid)
  700. return std::pair<int,int>(17,i);
  701. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  702. return std::pair<int,int>(17,0);
  703. }
  704. }
  705. return std::pair<int,int>(-1,-1);
  706. }
  707. void CGameState::randomizeObject(CGObjectInstance *cur)
  708. {
  709. std::pair<int,int> ran = pickObject(cur);
  710. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  711. {
  712. if(cur->ID==TOWNI_TYPE) //town - set def
  713. {
  714. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  715. if(t->hasCapitol())
  716. t->defInfo = capitols[t->subID];
  717. else if(t->hasFort())
  718. t->defInfo = forts[t->subID];
  719. else
  720. t->defInfo = villages[t->subID];
  721. }
  722. return;
  723. }
  724. else if(ran.first==HEROI_TYPE)//special code for hero
  725. {
  726. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  727. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  728. cur->ID = ran.first;
  729. h->portrait = cur->subID = ran.second;
  730. h->type = VLC->heroh->heroes[ran.second];
  731. map->heroes.push_back(h);
  732. return; //TODO: maybe we should do something with definfo?
  733. }
  734. else if(ran.first==TOWNI_TYPE)//special code for town
  735. {
  736. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  737. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  738. cur->ID = ran.first;
  739. cur->subID = ran.second;
  740. t->town = &VLC->townh->towns[ran.second];
  741. if(t->hasCapitol())
  742. t->defInfo = capitols[t->subID];
  743. else if(t->hasFort())
  744. t->defInfo = forts[t->subID];
  745. else
  746. t->defInfo = villages[t->subID];
  747. map->towns.push_back(t);
  748. return;
  749. }
  750. //we have to replace normal random object
  751. cur->ID = ran.first;
  752. cur->subID = ran.second;
  753. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  754. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  755. if(!cur->defInfo)
  756. {
  757. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  758. return;
  759. }
  760. map->addBlockVisTiles(cur);
  761. }
  762. int CGameState::getDate(int mode) const
  763. {
  764. int temp;
  765. switch (mode)
  766. {
  767. case 0:
  768. return day;
  769. break;
  770. case 1:
  771. temp = (day)%7;
  772. if (temp)
  773. return temp;
  774. else return 7;
  775. break;
  776. case 2:
  777. temp = ((day-1)/7)+1;
  778. if (!(temp%4))
  779. return 4;
  780. else
  781. return (temp%4);
  782. break;
  783. case 3:
  784. return ((day-1)/28)+1;
  785. break;
  786. }
  787. return 0;
  788. }
  789. CGameState::CGameState()
  790. {
  791. mx = new boost::shared_mutex();
  792. map = NULL;
  793. curB = NULL;
  794. scenarioOps = NULL;
  795. applier = new CGSApplier;
  796. }
  797. CGameState::~CGameState()
  798. {
  799. delete mx;
  800. delete map;
  801. delete curB;
  802. delete scenarioOps;
  803. delete applier;
  804. }
  805. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  806. {
  807. day = 0;
  808. seed = Seed;
  809. ran.seed((boost::int32_t)seed);
  810. scenarioOps = si;
  811. this->map = map;
  812. loadTownDInfos();
  813. //picking random factions for players
  814. for(int i=0;i<scenarioOps->playerInfos.size();i++)
  815. {
  816. if(scenarioOps->playerInfos[i].castle==-1)
  817. {
  818. int f;
  819. do
  820. {
  821. f = ran()%F_NUMBER;
  822. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  823. scenarioOps->playerInfos[i].castle = f;
  824. }
  825. }
  826. //randomizing objects
  827. for(int no=0; no<map->objects.size(); ++no)
  828. {
  829. randomizeObject(map->objects[no]);
  830. if(map->objects[no]->ID==26)
  831. {
  832. map->objects[no]->defInfo->handler=NULL;
  833. map->removeBlockVisTiles(map->objects[no]);
  834. map->objects[no]->defInfo->blockMap[5] = 255;
  835. map->addBlockVisTiles(map->objects[no]);
  836. }
  837. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  838. }
  839. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  840. /*********give starting hero****************************************/
  841. for(int i=0;i<PLAYER_LIMIT;i++)
  842. {
  843. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==RoE))
  844. {
  845. int3 hpos = map->players[i].posOfMainTown;
  846. hpos.x+=1;// hpos.y+=1;
  847. int j;
  848. for(j=0; j<scenarioOps->playerInfos.size(); j++)
  849. if(scenarioOps->playerInfos[j].color == i)
  850. break;
  851. if(j == scenarioOps->playerInfos.size())
  852. continue;
  853. int h=pickHero(i);
  854. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  855. nnn->id = map->objects.size();
  856. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  857. for(int o=0;o<map->towns.size();o++) //find main town
  858. {
  859. if(map->towns[o]->pos == hpos)
  860. {
  861. map->towns[o]->visitingHero = nnn;
  862. nnn->visitedTown = map->towns[o];
  863. nnn->inTownGarrison = false;
  864. break;
  865. }
  866. }
  867. nnn->initHero();
  868. map->heroes.push_back(nnn);
  869. map->objects.push_back(nnn);
  870. map->addBlockVisTiles(nnn);
  871. }
  872. }
  873. /*********creating players entries in gs****************************************/
  874. for (int i=0; i<scenarioOps->playerInfos.size();i++)
  875. {
  876. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  877. ins.second.color=ins.first;
  878. ins.second.serial=i;
  879. ins.second.human = scenarioOps->playerInfos[i].human;
  880. players.insert(ins);
  881. }
  882. /******************RESOURCES****************************************************/
  883. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  884. std::vector<int> startres;
  885. std::ifstream tis("config/startres.txt");
  886. int k;
  887. for (int j=0;j<scenarioOps->difficulty;j++)
  888. {
  889. tis >> k;
  890. for (int z=0;z<RESOURCE_QUANTITY;z++)
  891. tis>>k;
  892. }
  893. tis >> k;
  894. for (int i=0;i<RESOURCE_QUANTITY;i++)
  895. {
  896. tis >> k;
  897. startres.push_back(k);
  898. }
  899. tis.close();
  900. tis.clear();
  901. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  902. {
  903. (*i).second.resources.resize(RESOURCE_QUANTITY);
  904. for (int x=0;x<RESOURCE_QUANTITY;x++)
  905. (*i).second.resources[x] = startres[x];
  906. }
  907. tis.open("config/resources.txt");
  908. tis >> k;
  909. int pom;
  910. for(int i=0;i<k;i++)
  911. {
  912. tis >> pom;
  913. resVals.push_back(pom);
  914. }
  915. /*************************HEROES************************************************/
  916. std::set<int> hids;
  917. for(int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  918. if(map->allowedHeroes[i])
  919. hids.insert(i);
  920. for (int i=0; i<map->heroes.size();i++) //heroes instances initialization
  921. {
  922. if (map->heroes[i]->getOwner()<0)
  923. {
  924. tlog2 << "Warning - hero with uninitialized owner!\n";
  925. continue;
  926. }
  927. CGHeroInstance * vhi = (map->heroes[i]);
  928. vhi->initHero();
  929. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  930. hids.erase(vhi->subID);
  931. }
  932. for(int i=0; i<map->predefinedHeroes.size(); i++)
  933. {
  934. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  935. continue;
  936. map->predefinedHeroes[i]->initHero();
  937. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  938. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  939. hids.erase(map->predefinedHeroes[i]->subID);
  940. }
  941. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  942. {
  943. CGHeroInstance * vhi = new CGHeroInstance();
  944. vhi->initHero(hid);
  945. hpool.heroesPool[hid] = vhi;
  946. hpool.pavailable[hid] = 0xff;
  947. }
  948. for(int i=0; i<map->disposedHeroes.size(); i++)
  949. {
  950. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  951. }
  952. /*************************FOG**OF**WAR******************************************/
  953. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  954. {
  955. k->second.fogOfWarMap.resize(map->width);
  956. for(int g=0; g<map->width; ++g)
  957. k->second.fogOfWarMap[g].resize(map->height);
  958. for(int g=-0; g<map->width; ++g)
  959. for(int h=0; h<map->height; ++h)
  960. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  961. for(int g=0; g<map->width; ++g)
  962. for(int h=0; h<map->height; ++h)
  963. for(int v=0; v<map->twoLevel+1; ++v)
  964. k->second.fogOfWarMap[g][h][v] = 0;
  965. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  966. {
  967. if(obj->tempOwner != k->first) continue; //not a flagged object
  968. int3 objCenter = obj->getSightCenter();
  969. int radious = obj->getSightRadious();
  970. for (int xd = std::max<int>(objCenter.x - radious , 0); xd <= std::min<int>(objCenter.x + radious, map->width - 1); xd++)
  971. {
  972. for (int yd = std::max<int>(objCenter.y - radious, 0); yd <= std::min<int>(objCenter.y + radious, map->height - 1); yd++)
  973. {
  974. double distance = objCenter.dist2d(int3(xd,yd,objCenter.z)) - 0.5;
  975. if(distance <= radious)
  976. k->second.fogOfWarMap[xd][yd][objCenter.z] = 1;
  977. }
  978. }
  979. }
  980. //for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  981. //{
  982. // for(int yd=0; yd<map->height; ++yd)
  983. // {
  984. // for(int ch=0; ch<k->second.heroes.size(); ++ch)
  985. // {
  986. // int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  987. // int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  988. // if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  989. // k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  990. // }
  991. // }
  992. //}
  993. //starting bonus
  994. if(si->playerInfos[k->second.serial].bonus==brandom)
  995. si->playerInfos[k->second.serial].bonus = ran()%3;
  996. switch(si->playerInfos[k->second.serial].bonus)
  997. {
  998. case bgold:
  999. k->second.resources[6] += 500 + (ran()%6)*100;
  1000. break;
  1001. case bresource:
  1002. {
  1003. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1004. if(res == 127)
  1005. {
  1006. k->second.resources[0] += 5 + ran()%6;
  1007. k->second.resources[2] += 5 + ran()%6;
  1008. }
  1009. else
  1010. {
  1011. k->second.resources[res] += 3 + ran()%4;
  1012. }
  1013. break;
  1014. }
  1015. case bartifact:
  1016. {
  1017. if(!k->second.heroes.size())
  1018. {
  1019. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1020. break;
  1021. }
  1022. CArtifact *toGive;
  1023. do
  1024. {
  1025. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1026. } while (!map->allowedArtifact[toGive->id]);
  1027. CGHeroInstance *hero = k->second.heroes[0];
  1028. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1029. if(slot!=toGive->possibleSlots.end())
  1030. hero->artifWorn[*slot] = toGive->id;
  1031. else
  1032. hero->artifacts.push_back(toGive->id);
  1033. }
  1034. }
  1035. }
  1036. /****************************TOWNS************************************************/
  1037. for (int i=0;i<map->towns.size();i++)
  1038. {
  1039. CGTownInstance * vti =(map->towns[i]);
  1040. if(!vti->town)
  1041. vti->town = &VLC->townh->towns[vti->subID];
  1042. if (vti->name.length()==0) // if town hasn't name we draw it
  1043. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1044. //init buildings
  1045. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1046. {
  1047. vti->builtBuildings.erase(-50);
  1048. vti->builtBuildings.insert(10);
  1049. vti->builtBuildings.insert(5);
  1050. vti->builtBuildings.insert(30);
  1051. if(ran()%2)
  1052. vti->builtBuildings.insert(31);
  1053. }
  1054. //init spells
  1055. vti->spells.resize(SPELL_LEVELS);
  1056. CSpell *s;
  1057. for(int z=0; z<vti->obligatorySpells.size();z++)
  1058. {
  1059. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1060. vti->spells[s->level-1].push_back(s->id);
  1061. vti->possibleSpells -= s->id;
  1062. }
  1063. while(vti->possibleSpells.size())
  1064. {
  1065. ui32 total=0, sel=-1;
  1066. for(int ps=0;ps<vti->possibleSpells.size();ps++)
  1067. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1068. int r = (total)? ran()%total : -1;
  1069. for(int ps=0; ps<vti->possibleSpells.size();ps++)
  1070. {
  1071. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1072. if(r<0)
  1073. {
  1074. sel = ps;
  1075. break;
  1076. }
  1077. }
  1078. if(sel<0)
  1079. sel=0;
  1080. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1081. vti->spells[s->level-1].push_back(s->id);
  1082. vti->possibleSpells -= s->id;
  1083. }
  1084. //init garrisons
  1085. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1086. {
  1087. if(j->second.first > 196 && j->second.first < 211)
  1088. {
  1089. if(j->second.first%2)
  1090. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1091. else
  1092. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1093. }
  1094. }
  1095. if(vti->getOwner() != 255)
  1096. getPlayer(vti->getOwner())->towns.push_back(vti);
  1097. }
  1098. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1099. {
  1100. if(k->first==-1 || k->first==255)
  1101. continue;
  1102. // for(int xd=0; xd<map->width; ++xd) //revealing part of map around towns
  1103. // {
  1104. // for(int yd=0; yd<map->height; ++yd)
  1105. // {
  1106. // for(int ch=0; ch<k->second.towns.size(); ++ch)
  1107. // {
  1108. // int deltaX = (k->second.towns[ch]->pos.x-xd)*(k->second.towns[ch]->pos.x-xd);
  1109. // int deltaY = (k->second.towns[ch]->pos.y-yd)*(k->second.towns[ch]->pos.y-yd);
  1110. // if(deltaX+deltaY<k->second.towns[ch]->getSightDistance()*k->second.towns[ch]->getSightDistance())
  1111. // k->second.fogOfWarMap[xd][yd][k->second.towns[ch]->pos.z] = 1;
  1112. // }
  1113. // }
  1114. // }
  1115. //init visiting and garrisoned heroes
  1116. for(int l=0; l<k->second.heroes.size();l++)
  1117. {
  1118. for(int m=0; m<k->second.towns.size();m++)
  1119. {
  1120. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1121. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1122. {
  1123. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1124. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1125. k->second.heroes[l]->inTownGarrison = false;
  1126. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1127. k->second.heroes[l]->pos.x -= 1;
  1128. break;
  1129. }
  1130. }
  1131. }
  1132. }
  1133. for(int i=0; i<map->defy.size(); i++)
  1134. {
  1135. map->defy[i]->serial = i;
  1136. }
  1137. for(int i=0; i<map->objects.size(); i++)
  1138. {
  1139. map->objects[i]->initObj();
  1140. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1141. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1142. }
  1143. }
  1144. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1145. {
  1146. return true;
  1147. }
  1148. int CGameState::battleGetStack(int pos)
  1149. {
  1150. if(!curB)
  1151. return -1;
  1152. for(int g=0; g<curB->stacks.size(); ++g)
  1153. {
  1154. if((curB->stacks[g]->position == pos
  1155. || (curB->stacks[g]->creature->isDoubleWide()
  1156. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1157. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1158. ))
  1159. && curB->stacks[g]->alive()
  1160. )
  1161. return curB->stacks[g]->ID;
  1162. }
  1163. return -1;
  1164. }
  1165. int CGameState::battleGetBattlefieldType(int3 tile)
  1166. {
  1167. if(tile==int3() && curB)
  1168. tile = curB->tile;
  1169. else if(tile==int3() && !curB)
  1170. return -1;
  1171. //std::vector < std::pair<const CGObjectInstance*,SDL_Rect> > & objs = CGI->mh->ttiles[tile.x][tile.y][tile.z].objects;
  1172. //for(int g=0; g<objs.size(); ++g)
  1173. //{
  1174. // switch(objs[g].first->ID)
  1175. // {
  1176. // case 222: //clover field
  1177. // return 19;
  1178. // case 223: //cursed ground
  1179. // return 22;
  1180. // case 224: //evil fog
  1181. // return 20;
  1182. // case 225: //favourable winds
  1183. // return 21;
  1184. // case 226: //fiery fields
  1185. // return 14;
  1186. // case 227: //holy ground
  1187. // return 18;
  1188. // case 228: //lucid pools
  1189. // return 17;
  1190. // case 229: //magic clouds
  1191. // return 16;
  1192. // case 230: //magic plains
  1193. // return 9;
  1194. // case 231: //rocklands
  1195. // return 15;
  1196. // }
  1197. //}
  1198. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1199. {
  1200. case dirt:
  1201. return rand()%3+3;
  1202. case sand:
  1203. return 2; //TODO: coast support
  1204. case grass:
  1205. return rand()%2+6;
  1206. case snow:
  1207. return rand()%2+10;
  1208. case swamp:
  1209. return 13;
  1210. case rough:
  1211. return 23;
  1212. case subterranean:
  1213. return 12;
  1214. case lava:
  1215. return 8;
  1216. case water:
  1217. return 25;
  1218. case rock:
  1219. return 15;
  1220. default:
  1221. return -1;
  1222. }
  1223. }
  1224. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1225. {
  1226. UpgradeInfo ret;
  1227. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1228. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1229. {
  1230. CGTownInstance * t;
  1231. if(obj->ID == TOWNI_TYPE)
  1232. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1233. else
  1234. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1235. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1236. {
  1237. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1238. {
  1239. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1240. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1241. {
  1242. ret.newID.push_back(nid);
  1243. ret.cost.push_back(std::set<std::pair<int,int> >());
  1244. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1245. {
  1246. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1247. if(dif)
  1248. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1249. }
  1250. }
  1251. }
  1252. }//end for
  1253. }
  1254. //TODO: check if hero ability makes some upgrades possible
  1255. if(ret.newID.size())
  1256. ret.oldID = base->idNumber;
  1257. return ret;
  1258. }
  1259. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1260. {
  1261. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1262. if(mode) return -1; //todo - support other modes
  1263. int mcount = 0;
  1264. for(int i=0;i<getPlayer(player)->towns.size();i++)
  1265. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1266. mcount++;
  1267. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1268. return ret;
  1269. }
  1270. void CGameState::loadTownDInfos()
  1271. {
  1272. for(int i=0;i<F_NUMBER;i++)
  1273. {
  1274. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1275. forts[i] = VLC->dobjinfo->castles[i];
  1276. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1277. }
  1278. }
  1279. void CGameState::getNeighbours(int3 tile, std::vector<int3> &vec, bool onLand)
  1280. {
  1281. vec.clear();
  1282. int3 hlp;
  1283. bool weAreOnLand = (map->getTile(tile).tertype != 8);
  1284. if(tile.x > 0)
  1285. {
  1286. hlp = int3(tile.x-1,tile.y,tile.z);
  1287. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1288. vec.push_back(hlp);
  1289. }
  1290. if(tile.y > 0)
  1291. {
  1292. hlp = int3(tile.x,tile.y-1,tile.z);
  1293. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1294. vec.push_back(hlp);
  1295. }
  1296. if(tile.x > 0 && tile.y > 0)
  1297. {
  1298. hlp = int3(tile.x-1,tile.y-1,tile.z);
  1299. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1300. vec.push_back(hlp);
  1301. }
  1302. if(tile.x > 0 && tile.y < map->height-1)
  1303. {
  1304. hlp = int3(tile.x-1,tile.y+1,tile.z);
  1305. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1306. vec.push_back(hlp);
  1307. }
  1308. if(tile.y < map->height-1)
  1309. {
  1310. hlp = int3(tile.x,tile.y+1,tile.z);
  1311. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1312. vec.push_back(hlp);
  1313. }
  1314. if(tile.x < map->width-1)
  1315. {
  1316. hlp = int3(tile.x+1,tile.y,tile.z);
  1317. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1318. vec.push_back(hlp);
  1319. }
  1320. if(tile.x < map->width-1 && tile.y > 0)
  1321. {
  1322. hlp = int3(tile.x+1,tile.y-1,tile.z);
  1323. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1324. vec.push_back(hlp);
  1325. }
  1326. if(tile.x < map->width-1 && tile.y < map->height-1)
  1327. {
  1328. hlp = int3(tile.x+1,tile.y+1,tile.z);
  1329. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1330. vec.push_back(hlp);
  1331. }
  1332. }
  1333. int CGameState::getMovementCost(const CGHeroInstance *h, int3 src, int3 dest, int remainingMovePoints, bool checkLast)
  1334. {
  1335. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1336. &d = map->terrain[dest.x][dest.y][dest.z];
  1337. //get basic cost
  1338. int ret = h->getTileCost(d,s);
  1339. if(src.x!=dest.x && src.y!=dest.y) //diagonal move costs too much but normal move is possible
  1340. {
  1341. int old = ret;
  1342. ret *= 1.414;
  1343. if(ret > remainingMovePoints && remainingMovePoints > old)
  1344. {
  1345. return remainingMovePoints;
  1346. }
  1347. }
  1348. int left = remainingMovePoints-ret;
  1349. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1350. {
  1351. std::vector<int3> vec;
  1352. getNeighbours(dest,vec,true);
  1353. for(size_t i=0; i < vec.size(); i++)
  1354. {
  1355. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1356. if(fcost <= left)
  1357. {
  1358. return ret;
  1359. }
  1360. }
  1361. ret = remainingMovePoints;
  1362. }
  1363. return ret;
  1364. }
  1365. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1366. {
  1367. int ret = 7; //allowed by default
  1368. //can we build it?
  1369. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1370. ret = 2; //forbidden
  1371. else if(t->builded >= MAX_BUILDING_PER_TURN)
  1372. ret = 5; //building limit
  1373. //checking resources
  1374. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1375. for(int res=0;res<7;res++) //TODO: support custom amount of resources
  1376. {
  1377. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1378. ret = 6; //lack of res
  1379. }
  1380. //checking for requirements
  1381. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][ID].begin();
  1382. ri != VLC->townh->requirements[t->subID][ID].end();
  1383. ri++ )
  1384. {
  1385. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1386. ret = 8; //lack of requirements - cannot build
  1387. }
  1388. if(ID == 13) //capitol
  1389. {
  1390. for(int in = 0; in < map->towns.size(); in++)
  1391. {
  1392. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1393. {
  1394. ret = 0; //no more than one capitol
  1395. break;
  1396. }
  1397. }
  1398. }
  1399. else if(ID == 6) //shipyard
  1400. {
  1401. if(map->getTile(t->pos + int3(-1,3,0)).tertype != water && map->getTile(t->pos + int3(-3,3,0)).tertype != water)
  1402. ret = 1; //lack of water
  1403. }
  1404. return ret;
  1405. }
  1406. void CGameState::apply(CPack *pack)
  1407. {
  1408. applier->apps[typeList.getTypeID(pack)]->applyOnGS(this,pack);
  1409. }
  1410. PlayerState * CGameState::getPlayer( ui8 color )
  1411. {
  1412. if(vstd::contains(players,color))
  1413. {
  1414. return &players[color];
  1415. }
  1416. else
  1417. {
  1418. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1419. return NULL;
  1420. }
  1421. }
  1422. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting)
  1423. {
  1424. int attackerAttackBonus = attacker->creature->attack + (attackerHero ? attackerHero->getPrimSkillLevel(0) : 0);
  1425. if(attacker->getEffect(56)) //frenzy for attacker
  1426. {
  1427. attackerAttackBonus += (VLC->spellh->spells[attacker->getEffect(56)->id].powers[attacker->getEffect(56)->level]/100.0) *(attacker->creature->defence + (attackerHero ? attackerHero->getPrimSkillLevel(1) : 0));
  1428. }
  1429. int defenderDefenseBonus = defender->creature->defence + (defendingHero ? defendingHero->getPrimSkillLevel(1) : 0);
  1430. if(defender->getEffect(56)) //frenzy for defender
  1431. {
  1432. defenderDefenseBonus = 0;
  1433. }
  1434. int attackDefenseBonus = attackerAttackBonus - defenderDefenseBonus;
  1435. if(defender->getEffect(48)) //defender's prayer handling
  1436. {
  1437. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(48)->id].powers[defender->getEffect(48)->level];
  1438. }
  1439. if(attacker->getEffect(48)) //attacker's prayer handling
  1440. {
  1441. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(48)->id].powers[attacker->getEffect(48)->level];
  1442. }
  1443. if(defender->getEffect(46)) //stone skin handling
  1444. {
  1445. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(46)->id].powers[defender->getEffect(46)->level];
  1446. }
  1447. if(attacker->getEffect(45)) //weakness handling
  1448. {
  1449. attackDefenseBonus -= VLC->spellh->spells[attacker->getEffect(45)->id].powers[attacker->getEffect(45)->level];
  1450. }
  1451. if(!shooting && attacker->getEffect(43)) //bloodlust handling
  1452. {
  1453. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(43)->id].powers[attacker->getEffect(43)->level];
  1454. }
  1455. int damageBase = 0;
  1456. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  1457. {
  1458. damageBase = attacker->creature->damageMin;
  1459. damageBase -= VLC->spellh->spells[attacker->getEffect(42)->id].powers[attacker->getEffect(42)->level];
  1460. }
  1461. else if(attacker->getEffect(41)) //bless handling
  1462. {
  1463. damageBase = attacker->creature->damageMax;
  1464. damageBase += VLC->spellh->spells[attacker->getEffect(41)->id].powers[attacker->getEffect(41)->level];
  1465. }
  1466. else if(attacker->creature->damageMax == attacker->creature->damageMin) //constant damage
  1467. {
  1468. damageBase = attacker->creature->damageMin;
  1469. }
  1470. else
  1471. {
  1472. damageBase = rand()%(attacker->creature->damageMax - attacker->creature->damageMin) + attacker->creature->damageMin + 1;
  1473. }
  1474. float dmgBonusMultiplier = 1.0f;
  1475. if(attackDefenseBonus < 0) //decreasing dmg
  1476. {
  1477. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1478. {
  1479. dmgBonusMultiplier += -0.3f;
  1480. }
  1481. else
  1482. {
  1483. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1484. }
  1485. }
  1486. else //increasing dmg
  1487. {
  1488. if(0.05f * attackDefenseBonus > 4.0f)
  1489. {
  1490. dmgBonusMultiplier += 4.0f;
  1491. }
  1492. else
  1493. {
  1494. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1495. }
  1496. }
  1497. //handling secondary abilities
  1498. if(attackerHero)
  1499. {
  1500. if(shooting)
  1501. {
  1502. switch(attackerHero->getSecSkillLevel(1)) //archery
  1503. {
  1504. case 1: //basic
  1505. dmgBonusMultiplier *= 1.1f;
  1506. break;
  1507. case 2: //advanced
  1508. dmgBonusMultiplier *= 1.25f;
  1509. break;
  1510. case 3: //expert
  1511. dmgBonusMultiplier *= 1.5f;
  1512. break;
  1513. }
  1514. }
  1515. else
  1516. {
  1517. switch(attackerHero->getSecSkillLevel(22)) //offence
  1518. {
  1519. case 1: //basic
  1520. dmgBonusMultiplier *= 1.1f;
  1521. break;
  1522. case 2: //advanced
  1523. dmgBonusMultiplier *= 1.2f;
  1524. break;
  1525. case 3: //expert
  1526. dmgBonusMultiplier *= 1.3f;
  1527. break;
  1528. }
  1529. }
  1530. }
  1531. if(defendingHero)
  1532. {
  1533. switch(defendingHero->getSecSkillLevel(23)) //armourer
  1534. {
  1535. case 1: //basic
  1536. dmgBonusMultiplier *= 0.95f;
  1537. break;
  1538. case 2: //advanced
  1539. dmgBonusMultiplier *= 0.9f;
  1540. break;
  1541. case 3: //expert
  1542. dmgBonusMultiplier *= 0.85f;
  1543. break;
  1544. }
  1545. }
  1546. //handling spell effects
  1547. if(!shooting && defender->getEffect(27)) //shield
  1548. {
  1549. if(defender->getEffect(27)->level<=1) //none or basic
  1550. dmgBonusMultiplier *= 0.85f;
  1551. else //adv or expert
  1552. dmgBonusMultiplier *= 0.7f;
  1553. }
  1554. if(shooting && defender->getEffect(28)) //air shield
  1555. {
  1556. if(defender->getEffect(28)->level<=1) //none or basic
  1557. dmgBonusMultiplier *= 0.75f;
  1558. else //adv or expert
  1559. dmgBonusMultiplier *= 0.5f;
  1560. }
  1561. if(attacker->getEffect(42)) //curse, second part of handling
  1562. {
  1563. if(attacker->getEffect(42)->level>=2) //adv or expert
  1564. dmgBonusMultiplier *= 0.8f;
  1565. }
  1566. return int( (float)damageBase * (float)attacker->amount * dmgBonusMultiplier );
  1567. }
  1568. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1569. {
  1570. for(int i=0; i<stacks.size();i++)//setting casualties
  1571. {
  1572. if(!stacks[i]->alive())
  1573. {
  1574. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1575. }
  1576. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1577. {
  1578. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1579. }
  1580. }
  1581. }
  1582. CStack * BattleInfo::getNextStack()
  1583. {
  1584. CStack *current = getStack(activeStack);
  1585. for (int i = 0; i < stacks.size(); i++) //find fastest not moved/waited stack (stacks vector is sorted by speed)
  1586. {
  1587. if(vstd::contains(stacks[i]->state,DEFENDING)
  1588. ||vstd::contains(stacks[i]->state,WAITING)
  1589. ||vstd::contains(stacks[i]->state,MOVED)
  1590. ||!stacks[i]->alive()
  1591. )
  1592. continue;
  1593. return stacks[i];
  1594. }
  1595. for (int i = stacks.size() - 1; i >= 0 ; i--) //find slowest waiting stack
  1596. {
  1597. if(vstd::contains(stacks[i]->state,DEFENDING)
  1598. ||vstd::contains(stacks[i]->state,MOVED)
  1599. ||!stacks[i]->alive()
  1600. )
  1601. continue;
  1602. return stacks[i];
  1603. }
  1604. return NULL; //all stacks moved or defending!
  1605. }
  1606. std::vector<CStack> BattleInfo::getStackQueue()
  1607. {
  1608. std::vector<CStack> ret;
  1609. std::vector<int> taken; //if non-zero value, corresponding stack has been placed in ret
  1610. taken.resize(stacks.size());
  1611. for(int g=0; g<taken.size(); ++g)
  1612. {
  1613. taken[g] = 0;
  1614. }
  1615. 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
  1616. {
  1617. for(int gc=0; gc<stacks.size(); ++gc)
  1618. {
  1619. int id = -1, speed = -1;
  1620. for(int i=0; i<stacks.size(); ++i) //find not waited stacks only
  1621. {
  1622. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1623. && stacks[i]->alive()
  1624. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1625. && !vstd::contains(stacks[i]->state,WAITING)
  1626. && taken[i]==0)
  1627. {
  1628. if(speed == -1 || stacks[i]->speed() > speed)
  1629. {
  1630. id = i;
  1631. speed = stacks[i]->speed();
  1632. }
  1633. }
  1634. }
  1635. if(id != -1)
  1636. {
  1637. ret.push_back(*stacks[id]);
  1638. taken[id] = 1;
  1639. }
  1640. else //choose something from not moved stacks
  1641. {
  1642. int id = -1, speed = 10000; //infinite speed
  1643. for(int i=0; i<stacks.size(); ++i) //find waited stacks only
  1644. {
  1645. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1646. && stacks[i]->alive()
  1647. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1648. && vstd::contains(stacks[i]->state,WAITING)
  1649. && taken[i]==0)
  1650. {
  1651. if(stacks[i]->speed() < speed) //slowest one
  1652. {
  1653. id = i;
  1654. speed = stacks[i]->speed();
  1655. }
  1656. }
  1657. }
  1658. if(id != -1)
  1659. {
  1660. ret.push_back(*stacks[id]);
  1661. taken[id] = 1;
  1662. }
  1663. else
  1664. {
  1665. break; //no stacks have been found, so none of them will be found in next iterations
  1666. }
  1667. }
  1668. }
  1669. }
  1670. return ret;
  1671. }