CGameState.cpp 64 KB

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