CGameState.cpp 63 KB

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