CGameState.cpp 90 KB

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