2
0

CGameState.cpp 81 KB

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