CGameState.cpp 84 KB

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