CGameState.cpp 92 KB

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