CGameState.cpp 49 KB

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