2
0

CGameState.cpp 62 KB

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