CGameState.cpp 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135
  1. #include "StdInc.h"
  2. #include "CGameState.h"
  3. #include <boost/random/linear_congruential.hpp>
  4. #include "CCampaignHandler.h"
  5. #include "CDefObjInfoHandler.h"
  6. #include "CArtHandler.h"
  7. #include "CBuildingHandler.h"
  8. #include "CGeneralTextHandler.h"
  9. #include "CTownHandler.h"
  10. #include "CSpellHandler.h"
  11. #include "CHeroHandler.h"
  12. #include "CObjectHandler.h"
  13. #include "CCreatureHandler.h"
  14. #include "CModHandler.h"
  15. #include "VCMI_Lib.h"
  16. #include "Connection.h"
  17. #include "map.h"
  18. #include "StartInfo.h"
  19. #include "NetPacks.h"
  20. #include "RegisterTypes.h"
  21. #include "CMapInfo.h"
  22. #include "BattleState.h"
  23. #include "JsonNode.h"
  24. #include "Filesystem/CResourceLoader.h"
  25. #include "GameConstants.h"
  26. DLL_LINKAGE boost::rand48 ran;
  27. class CGObjectInstance;
  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. template <typename T> class CApplyOnGS;
  54. class CBaseForGSApply
  55. {
  56. public:
  57. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  58. virtual ~CBaseForGSApply(){};
  59. template<typename U> static CBaseForGSApply *getApplier(const U * t=NULL)
  60. {
  61. return new CApplyOnGS<U>;
  62. }
  63. };
  64. template <typename T> class CApplyOnGS : public CBaseForGSApply
  65. {
  66. public:
  67. void applyOnGS(CGameState *gs, void *pack) const
  68. {
  69. T *ptr = static_cast<T*>(pack);
  70. boost::unique_lock<boost::shared_mutex> lock(*gs->mx);
  71. ptr->applyGs(gs);
  72. }
  73. };
  74. static CApplier<CBaseForGSApply> *applierGs = NULL;
  75. class IObjectCaller
  76. {
  77. public:
  78. virtual ~IObjectCaller(){};
  79. virtual void preInit()=0;
  80. virtual void postInit()=0;
  81. };
  82. template <typename T>
  83. class CObjectCaller : public IObjectCaller
  84. {
  85. public:
  86. void preInit()
  87. {
  88. //T::preInit();
  89. }
  90. void postInit()
  91. {
  92. //T::postInit();
  93. }
  94. };
  95. class CObjectCallersHandler
  96. {
  97. public:
  98. std::vector<IObjectCaller*> apps;
  99. template<typename T> void registerType(const T * t=NULL)
  100. {
  101. apps.push_back(new CObjectCaller<T>);
  102. }
  103. CObjectCallersHandler()
  104. {
  105. registerTypes1(*this);
  106. }
  107. ~CObjectCallersHandler()
  108. {
  109. for (size_t i = 0; i < apps.size(); i++)
  110. delete apps[i];
  111. }
  112. void preInit()
  113. {
  114. // for (size_t i = 0; i < apps.size(); i++)
  115. // apps[i]->preInit();
  116. }
  117. void postInit()
  118. {
  119. //for (size_t i = 0; i < apps.size(); i++)
  120. //apps[i]->postInit();
  121. }
  122. } *objCaller = NULL;
  123. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  124. {
  125. int type = txt.first, ser = txt.second;
  126. if(type == ART_NAMES)
  127. {
  128. dst = VLC->arth->artifacts[ser]->Name();
  129. }
  130. else if(type == CRE_PL_NAMES)
  131. {
  132. dst = VLC->creh->creatures[ser]->namePl;
  133. }
  134. else if(type == MINE_NAMES)
  135. {
  136. dst = VLC->generaltexth->mines[ser].first;
  137. }
  138. else if(type == MINE_EVNTS)
  139. {
  140. dst = VLC->generaltexth->mines[ser].second;
  141. }
  142. else if(type == SPELL_NAME)
  143. {
  144. dst = VLC->spellh->spells[ser]->name;
  145. }
  146. else if(type == CRE_SING_NAMES)
  147. {
  148. dst = VLC->creh->creatures[ser]->nameSing;
  149. }
  150. else if(type == ART_DESCR)
  151. {
  152. dst = VLC->arth->artifacts[ser]->Description();
  153. }
  154. else
  155. {
  156. std::vector<std::string> *vec;
  157. switch(type)
  158. {
  159. case GENERAL_TXT:
  160. vec = &VLC->generaltexth->allTexts;
  161. break;
  162. case XTRAINFO_TXT:
  163. vec = &VLC->generaltexth->xtrainfo;
  164. break;
  165. case OBJ_NAMES:
  166. vec = &VLC->generaltexth->names;
  167. break;
  168. case RES_NAMES:
  169. vec = &VLC->generaltexth->restypes;
  170. break;
  171. case ARRAY_TXT:
  172. vec = &VLC->generaltexth->arraytxt;
  173. break;
  174. case CREGENS:
  175. vec = &VLC->generaltexth->creGens;
  176. break;
  177. case CREGENS4:
  178. vec = &VLC->generaltexth->creGens4;
  179. break;
  180. case ADVOB_TXT:
  181. vec = &VLC->generaltexth->advobtxt;
  182. break;
  183. case ART_EVNTS:
  184. vec = &VLC->generaltexth->artifEvents;
  185. break;
  186. case SEC_SKILL_NAME:
  187. vec = &VLC->generaltexth->skillName;
  188. break;
  189. case COLOR:
  190. vec = &VLC->generaltexth->capColors;
  191. break;
  192. default:
  193. tlog1 << "Failed string substitution because type is " << type << std::endl;
  194. dst = "#@#";
  195. return;
  196. }
  197. if(vec->size() <= ser)
  198. {
  199. tlog1 << "Failed string substitution with type " << type << " because index " << ser << " is out of bounds!\n";
  200. dst = "#!#";
  201. }
  202. else
  203. dst = (*vec)[ser];
  204. }
  205. }
  206. DLL_LINKAGE void MetaString::toString(std::string &dst) const
  207. {
  208. size_t exSt = 0, loSt = 0, nums = 0;
  209. dst.clear();
  210. for(size_t i=0;i<message.size();++i)
  211. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  212. switch(message[i])
  213. {
  214. case TEXACT_STRING:
  215. dst += exactStrings[exSt++];
  216. break;
  217. case TLOCAL_STRING:
  218. {
  219. std::string hlp;
  220. getLocalString(localStrings[loSt++], hlp);
  221. dst += hlp;
  222. }
  223. break;
  224. case TNUMBER:
  225. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  226. break;
  227. case TREPLACE_ESTRING:
  228. boost::replace_first(dst, "%s", exactStrings[exSt++]);
  229. break;
  230. case TREPLACE_LSTRING:
  231. {
  232. std::string hlp;
  233. getLocalString(localStrings[loSt++], hlp);
  234. boost::replace_first(dst, "%s", hlp);
  235. }
  236. break;
  237. case TREPLACE_NUMBER:
  238. boost::replace_first(dst, "%d", boost::lexical_cast<std::string>(numbers[nums++]));
  239. break;
  240. case TREPLACE_PLUSNUMBER:
  241. boost::replace_first(dst, "%+d", '+' + boost::lexical_cast<std::string>(numbers[nums++]));
  242. break;
  243. default:
  244. tlog1 << "MetaString processing error!\n";
  245. break;
  246. }
  247. }
  248. }
  249. DLL_LINKAGE std::string MetaString::toString() const
  250. {
  251. std::string ret;
  252. toString(ret);
  253. return ret;
  254. }
  255. DLL_LINKAGE std::string MetaString::buildList () const
  256. ///used to handle loot from creature bank
  257. {
  258. size_t exSt = 0, loSt = 0, nums = 0;
  259. std::string lista;
  260. for (int i = 0; i < message.size(); ++i)
  261. {
  262. if (i > 0 && (message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING))
  263. {
  264. if (exSt == exactStrings.size() - 1)
  265. lista += VLC->generaltexth->allTexts[141]; //" and "
  266. else
  267. lista += ", ";
  268. }
  269. switch (message[i])
  270. {
  271. case TEXACT_STRING:
  272. lista += exactStrings[exSt++];
  273. break;
  274. case TLOCAL_STRING:
  275. {
  276. std::string hlp;
  277. getLocalString (localStrings[loSt++], hlp);
  278. lista += hlp;
  279. }
  280. break;
  281. case TNUMBER:
  282. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  283. break;
  284. case TREPLACE_ESTRING:
  285. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  286. break;
  287. case TREPLACE_LSTRING:
  288. {
  289. std::string hlp;
  290. getLocalString (localStrings[loSt++], hlp);
  291. lista.replace (lista.find("%s"), 2, hlp);
  292. }
  293. break;
  294. case TREPLACE_NUMBER:
  295. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  296. break;
  297. default:
  298. tlog1 << "MetaString processing error!\n";
  299. }
  300. }
  301. return lista;
  302. }
  303. void MetaString::addCreReplacement(TCreature id, TQuantity count) //adds sing or plural name;
  304. {
  305. if (!count)
  306. addReplacement (CRE_PL_NAMES, id); //no creatures - just empty name (eg. defeat Angels)
  307. else if (count == 1)
  308. addReplacement (CRE_SING_NAMES, id);
  309. else
  310. addReplacement (CRE_PL_NAMES, id);
  311. }
  312. void MetaString::addReplacement(const CStackBasicDescriptor &stack)
  313. {
  314. assert(stack.type); //valid type
  315. addCreReplacement(stack.type->idNumber, stack.count);
  316. }
  317. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  318. {
  319. CGObjectInstance * nobj;
  320. switch(id)
  321. {
  322. case GameConstants::HEROI_TYPE: //hero
  323. {
  324. CGHeroInstance * nobj = new CGHeroInstance();
  325. nobj->pos = pos;
  326. nobj->tempOwner = owner;
  327. nobj->subID = subid;
  328. //nobj->initHero(ran);
  329. return nobj;
  330. }
  331. case GameConstants::TOWNI_TYPE: //town
  332. nobj = new CGTownInstance;
  333. break;
  334. default: //rest of objects
  335. nobj = new CGObjectInstance;
  336. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  337. break;
  338. }
  339. nobj->ID = id;
  340. nobj->subID = subid;
  341. if(!nobj->defInfo)
  342. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  343. nobj->pos = pos;
  344. //nobj->state = NULL;//new CLuaObjectScript();
  345. nobj->tempOwner = owner;
  346. nobj->defInfo->id = id;
  347. nobj->defInfo->subid = subid;
  348. //assigning defhandler
  349. if(nobj->ID==GameConstants::HEROI_TYPE || nobj->ID==GameConstants::TOWNI_TYPE)
  350. return nobj;
  351. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  352. return nobj;
  353. }
  354. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, bmap<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass /*= NULL*/) const
  355. {
  356. CGHeroInstance *ret = NULL;
  357. if(player<0 || player>=GameConstants::PLAYER_LIMIT)
  358. {
  359. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  360. return NULL;
  361. }
  362. std::vector<CGHeroInstance *> pool;
  363. if(native)
  364. {
  365. for(bmap<ui32, ConstTransitivePtr<CGHeroInstance> >::iterator i=available.begin(); i!=available.end(); i++)
  366. {
  367. if(pavailable.find(i->first)->second & 1<<player
  368. && i->second->type->heroType/2 == town->typeID)
  369. {
  370. pool.push_back(i->second); //get all available heroes
  371. }
  372. }
  373. if(!pool.size())
  374. {
  375. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  376. return pickHeroFor(false, player, town, available);
  377. }
  378. else
  379. {
  380. ret = pool[rand()%pool.size()];
  381. }
  382. }
  383. else
  384. {
  385. int sum=0, r;
  386. for(bmap<ui32, ConstTransitivePtr<CGHeroInstance> >::iterator i=available.begin(); i!=available.end(); i++)
  387. {
  388. if ((!bannedClass && (pavailable.find(i->first)->second & (1<<player))) ||
  389. i->second->type->heroClass != bannedClass)
  390. {
  391. pool.push_back(i->second);
  392. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  393. }
  394. }
  395. if(!pool.size())
  396. {
  397. tlog1 << "There are no heroes available for player " << player<<"!\n";
  398. return NULL;
  399. }
  400. r = rand()%sum;
  401. for (ui32 i=0; i<pool.size(); i++)
  402. {
  403. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  404. if(r < 0)
  405. {
  406. ret = pool[i];
  407. break;
  408. }
  409. }
  410. if(!ret)
  411. ret = pool.back();
  412. }
  413. available.erase(ret->subID);
  414. return ret;
  415. }
  416. //void CGameState::apply(CPack * pack)
  417. //{
  418. // while(!mx->try_lock())
  419. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  420. // //applyNL(pack);
  421. // mx->unlock();
  422. //}
  423. int CGameState::pickHero(int owner)
  424. {
  425. int h=-1;
  426. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  427. if(!map->getHero(h = ps.hero,0) && h>=0) //we haven't used selected hero
  428. return h;
  429. int i=0;
  430. do //try to find free hero of our faction
  431. {
  432. i++;
  433. h = ps.castle*GameConstants::HEROES_PER_TYPE*2+(ran()%(GameConstants::HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  434. } while( map->getHero(h) && i<175);
  435. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  436. {
  437. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  438. for(int j=0; j<GameConstants::HEROES_PER_TYPE * 2 * GameConstants::F_NUMBER; j++)
  439. if(!map->getHero(j))
  440. h=j;
  441. }
  442. return h;
  443. }
  444. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  445. {
  446. switch(obj->ID)
  447. {
  448. case 65:
  449. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  450. case 66: //random treasure artifact
  451. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE));
  452. case 67: //random minor artifact
  453. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MINOR));
  454. case 68: //random major artifact
  455. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MAJOR));
  456. case 69: //random relic artifact
  457. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_RELIC));
  458. case 70: //random hero
  459. return std::pair<int,int>(GameConstants::HEROI_TYPE,pickHero(obj->tempOwner));
  460. case 71: //random monster
  461. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran)));
  462. case 72: //random monster lvl1
  463. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran), 1));
  464. case 73: //random monster lvl2
  465. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran), 2));
  466. case 74: //random monster lvl3
  467. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran), 3));
  468. case 75: //random monster lvl4
  469. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 4));
  470. case 76: //random resource
  471. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  472. case 77: //random town
  473. {
  474. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  475. f;
  476. if(align>GameConstants::PLAYER_LIMIT-1)//same as owner / random
  477. {
  478. if(obj->tempOwner > GameConstants::PLAYER_LIMIT-1)
  479. f = -1; //random
  480. else
  481. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  482. }
  483. else
  484. {
  485. f = scenarioOps->getIthPlayersSettings(align).castle;
  486. }
  487. if(f<0) f = ran()%VLC->townh->towns.size();
  488. return std::pair<int,int>(GameConstants::TOWNI_TYPE,f);
  489. }
  490. case 162: //random monster lvl5
  491. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 5));
  492. case 163: //random monster lvl6
  493. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 6));
  494. case 164: //random monster lvl7
  495. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 7));
  496. case 216: //random dwellings
  497. case 217:
  498. case 218:
  499. {
  500. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  501. int faction;
  502. //if castle alignment available
  503. if (auto info = dynamic_cast<CCreGenAsCastleInfo*>(dwl->info))
  504. {
  505. faction = ran()%GameConstants::F_NUMBER;
  506. if (info->asCastle)
  507. {
  508. for(ui32 i=0;i<map->objects.size();i++)
  509. {
  510. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  511. {
  512. randomizeObject(map->objects[i]); //we have to randomize the castle first
  513. faction = map->objects[i]->subID;
  514. break;
  515. }
  516. else if(map->objects[i]->ID==GameConstants::TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  517. {
  518. faction = map->objects[i]->subID;
  519. break;
  520. }
  521. }
  522. }
  523. else
  524. {
  525. while((!(info->castles[0]&(1<<faction))))
  526. {
  527. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  528. break;
  529. faction = ran()%GameConstants::F_NUMBER;
  530. }
  531. }
  532. }
  533. else // castle alignment fixed
  534. faction = obj->subID;
  535. int level;
  536. //if level set to range
  537. if (auto info = dynamic_cast<CCreGenLeveledInfo*>(dwl->info))
  538. level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  539. else // fixed level
  540. level = obj->subID;
  541. delete dwl->info;
  542. dwl->info = nullptr;
  543. std::pair<int,int> result(-1, -1);
  544. int cid = VLC->townh->towns[faction].creatures[level][0];
  545. //golem factory is not in list of cregens but can be placed as random object
  546. static const int factoryCreatures[] = {32, 33, 116, 117};
  547. std::vector<int> factory(factoryCreatures, factoryCreatures + ARRAY_COUNT(factoryCreatures));
  548. if (vstd::contains(factory, cid))
  549. result = std::pair<int,int>(20, 1);
  550. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  551. //check for block map equality is better but more complex solution
  552. BOOST_FOREACH(auto &iter, VLC->objh->cregens)
  553. if (iter.second == cid)
  554. result = std::pair<int,int>(17, iter.first);
  555. if (result.first == -1)
  556. tlog0 << "Error: failed to find creature for dwelling of "<< int(faction) << " of level " << int(level) << "\n";
  557. return result;
  558. }
  559. }
  560. return std::pair<int,int>(-1,-1);
  561. }
  562. void CGameState::randomizeObject(CGObjectInstance *cur)
  563. {
  564. std::pair<int,int> ran = pickObject(cur);
  565. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  566. {
  567. if(cur->ID==GameConstants::TOWNI_TYPE) //town - set def
  568. {
  569. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  570. t->town = &VLC->townh->towns[t->subID];
  571. if(t->hasCapitol())
  572. t->defInfo = capitols[t->subID];
  573. else if(t->hasFort())
  574. t->defInfo = forts[t->subID];
  575. else
  576. t->defInfo = villages[t->subID];
  577. }
  578. return;
  579. }
  580. else if(ran.first==GameConstants::HEROI_TYPE)//special code for hero
  581. {
  582. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  583. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  584. cur->ID = ran.first;
  585. h->portrait = cur->subID = ran.second;
  586. h->type = VLC->heroh->heroes[ran.second];
  587. h->randomizeArmy(h->type->heroType/2);
  588. map->heroes.push_back(h);
  589. return; //TODO: maybe we should do something with definfo?
  590. }
  591. else if(ran.first==GameConstants::TOWNI_TYPE)//special code for town
  592. {
  593. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  594. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  595. cur->ID = ran.first;
  596. cur->subID = ran.second;
  597. t->town = &VLC->townh->towns[ran.second];
  598. if(t->hasCapitol())
  599. t->defInfo = capitols[t->subID];
  600. else if(t->hasFort())
  601. t->defInfo = forts[t->subID];
  602. else
  603. t->defInfo = villages[t->subID];
  604. t->randomizeArmy(t->subID);
  605. map->towns.push_back(t);
  606. return;
  607. }
  608. //we have to replace normal random object
  609. cur->ID = ran.first;
  610. cur->subID = ran.second;
  611. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  612. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  613. if(!cur->defInfo)
  614. {
  615. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  616. return;
  617. }
  618. map->addBlockVisTiles(cur);
  619. }
  620. int CGameState::getDate(int mode) const
  621. {
  622. int temp;
  623. switch (mode)
  624. {
  625. case 0: //day number
  626. return day;
  627. break;
  628. case 1: //day of week
  629. temp = (day)%7; // 1 - Monday, 7 - Sunday
  630. if (temp)
  631. return temp;
  632. else return 7;
  633. break;
  634. case 2: //current week
  635. temp = ((day-1)/7)+1;
  636. if (!(temp%4))
  637. return 4;
  638. else
  639. return (temp%4);
  640. break;
  641. case 3: //current month
  642. return ((day-1)/28)+1;
  643. break;
  644. case 4: //day of month
  645. temp = (day)%28;
  646. if (temp)
  647. return temp;
  648. else return 28;
  649. break;
  650. }
  651. return 0;
  652. }
  653. CGameState::CGameState()
  654. {
  655. gs = this;
  656. mx = new boost::shared_mutex();
  657. applierGs = new CApplier<CBaseForGSApply>;
  658. registerTypes2(*applierGs);
  659. objCaller = new CObjectCallersHandler;
  660. globalEffects.setDescription("Global effects");
  661. }
  662. CGameState::~CGameState()
  663. {
  664. //delete mx;//TODO: crash on Linux (mutex must be unlocked before destruction)
  665. map.dellNull();
  666. curB.dellNull();
  667. //delete scenarioOps; //TODO: fix for loading ind delete
  668. //delete initialOpts;
  669. delete applierGs;
  670. delete objCaller;
  671. //TODO: delete properly that definfos
  672. villages.clear();
  673. capitols.clear();
  674. }
  675. BattleInfo * CGameState::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town)
  676. {
  677. const TerrainTile &t = map->getTile(tile);
  678. int terrain = t.tertype;
  679. if(t.isCoastal() && !t.isWater())
  680. terrain = TerrainTile::sand;
  681. int terType = battleGetBattlefieldType(tile);
  682. return BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  683. }
  684. void CGameState::init(StartInfo * si)
  685. {
  686. struct HLP
  687. {
  688. //it's assumed that given hero should receive the bonus
  689. static void giveCampaignBonusToHero(CGHeroInstance * hero, const StartInfo * si, const CScenarioTravel & st, CGameState *gs )
  690. {
  691. const CScenarioTravel::STravelBonus & curBonus = st.bonusesToChoose[si->choosenCampaignBonus];
  692. if(curBonus.isBonusForHero())
  693. {
  694. //apply bonus
  695. switch (curBonus.type)
  696. {
  697. case 0: //spell
  698. hero->spells.insert(curBonus.info2);
  699. break;
  700. case 1: //monster
  701. {
  702. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  703. {
  704. if(hero->slotEmpty(i))
  705. {
  706. hero->addToSlot(i, curBonus.info2, curBonus.info3);
  707. break;
  708. }
  709. }
  710. }
  711. break;
  712. case 3: //artifact
  713. gs->giveHeroArtifact(hero, curBonus.info2);
  714. break;
  715. case 4: //spell scroll
  716. {
  717. CArtifactInstance * scroll = CArtifactInstance::createScroll(VLC->spellh->spells[curBonus.info2]);
  718. scroll->putAt(ArtifactLocation(hero, scroll->firstAvailableSlot(hero)));
  719. }
  720. break;
  721. case 5: //prim skill
  722. {
  723. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus.info2);
  724. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  725. {
  726. int val = ptr[g];
  727. if (val == 0)
  728. {
  729. continue;
  730. }
  731. Bonus *bb = new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, si->whichMapInCampaign, g);
  732. hero->addNewBonus(bb);
  733. }
  734. }
  735. break;
  736. case 6: //sec skills
  737. hero->setSecSkillLevel(static_cast<CGHeroInstance::SecondarySkill>(curBonus.info2), curBonus.info3, true);
  738. break;
  739. }
  740. }
  741. }
  742. static std::vector<const PlayerSettings *> getHumanPlayerInfo(const StartInfo * si)
  743. {
  744. std::vector<const PlayerSettings *> ret;
  745. for(std::map<int, PlayerSettings>::const_iterator it = si->playerInfos.begin();
  746. it != si->playerInfos.end(); ++it)
  747. {
  748. if(it->second.human)
  749. ret.push_back(&it->second);
  750. }
  751. return ret;
  752. }
  753. static void replaceHero( CGameState * gs, int objId, CGHeroInstance * ghi )
  754. {
  755. ghi->id = objId;
  756. gs->map->objects[objId] = ghi;
  757. gs->map->heroes.push_back(ghi);
  758. }
  759. //sort in descending order by power
  760. static bool heroPowerSorter(const CGHeroInstance * a, const CGHeroInstance * b)
  761. {
  762. return a->getHeroStrength() > b->getHeroStrength();
  763. }
  764. };
  765. tlog0 << "\tUsing random seed: "<< si->seedToBeUsed << std::endl;
  766. ran.seed((boost::int32_t)si->seedToBeUsed);
  767. scenarioOps = new StartInfo(*si);
  768. initialOpts = new StartInfo(*si);
  769. si = NULL;
  770. switch(scenarioOps->mode)
  771. {
  772. case StartInfo::NEW_GAME:
  773. map = new Mapa(scenarioOps->mapname);
  774. break;
  775. case StartInfo::CAMPAIGN:
  776. {
  777. campaign = new CCampaignState();
  778. campaign->initNewCampaign(*scenarioOps);
  779. assert(vstd::contains(campaign->camp->mapPieces, scenarioOps->whichMapInCampaign));
  780. std::vector<ui8> &mapContent = campaign->camp->mapPieces[scenarioOps->whichMapInCampaign];
  781. map = new Mapa();
  782. map->initFromBytes((const ui8*)mapContent.data(), mapContent.size());
  783. }
  784. break;
  785. case StartInfo::DUEL:
  786. initDuel();
  787. return;
  788. default:
  789. tlog1 << "Wrong mode: " << (int)scenarioOps->mode << std::endl;
  790. return;
  791. }
  792. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  793. tlog0 << "Map loaded!" << std::endl;
  794. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  795. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  796. if(scenarioOps->mapfileChecksum)
  797. {
  798. tlog0 << "\tServer checksum for " << scenarioOps->mapname <<": "<< scenarioOps->mapfileChecksum << std::endl;
  799. if(map->checksum != scenarioOps->mapfileChecksum)
  800. {
  801. tlog1 << "Wrong map checksum!!!" << std::endl;
  802. throw std::runtime_error("Wrong checksum");
  803. }
  804. }
  805. else
  806. scenarioOps->mapfileChecksum = map->checksum;
  807. day = 0;
  808. loadTownDInfos();
  809. //pick grail location
  810. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  811. {
  812. if(!map->grailRadious) //radius not given -> anywhere on map
  813. map->grailRadious = map->width * 2;
  814. std::vector<int3> allowedPos;
  815. // add all not blocked tiles in range
  816. for (int i = 0; i < map->width ; i++)
  817. {
  818. for (int j = 0; j < map->height ; j++)
  819. {
  820. for (int k = 0; k <= map->twoLevel ; k++)
  821. {
  822. const TerrainTile &t = map->terrain[i][j][k];
  823. if(!t.blocked
  824. && !t.visitable
  825. && t.tertype != TerrainTile::water
  826. && t.tertype != TerrainTile::rock
  827. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  828. allowedPos.push_back(int3(i,j,k));
  829. }
  830. }
  831. }
  832. //remove tiles with holes
  833. for(ui32 no=0; no<map->objects.size(); ++no)
  834. if(map->objects[no]->ID == 124)
  835. allowedPos -= map->objects[no]->pos;
  836. if(allowedPos.size())
  837. map->grailPos = allowedPos[ran() % allowedPos.size()];
  838. else
  839. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  840. }
  841. //picking random factions for players
  842. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  843. it != scenarioOps->playerInfos.end(); ++it)
  844. {
  845. if(it->second.castle==-1)
  846. {
  847. int f;
  848. do
  849. {
  850. f = ran()%GameConstants::F_NUMBER;
  851. }while(!(map->players[it->first].allowedFactions & 1<<f));
  852. it->second.castle = f;
  853. }
  854. }
  855. //randomizing objects
  856. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  857. {
  858. randomizeObject(obj);
  859. obj->hoverName = VLC->generaltexth->names[obj->ID];
  860. //handle Favouring Winds - mark tiles under it
  861. if(obj->ID == 225)
  862. for (int i = 0; i < obj->getWidth() ; i++)
  863. for (int j = 0; j < obj->getHeight() ; j++)
  864. {
  865. int3 pos = obj->pos - int3(i,j,0);
  866. if(map->isInTheMap(pos))
  867. map->getTile(pos).siodmyTajemniczyBajt |= 128;
  868. }
  869. }
  870. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  871. /*********creating players entries in gs****************************************/
  872. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  873. it != scenarioOps->playerInfos.end(); ++it)
  874. {
  875. std::pair<int,PlayerState> ins(it->first,PlayerState());
  876. ins.second.color=ins.first;
  877. ins.second.human = it->second.human;
  878. ins.second.team = map->players[ins.first].team;
  879. teams[ins.second.team].id = ins.second.team;//init team
  880. teams[ins.second.team].players.insert(ins.first);//add player to team
  881. players.insert(ins);
  882. }
  883. /*********give starting hero****************************************/
  884. for(int i=0;i<GameConstants::PLAYER_LIMIT;i++)
  885. {
  886. const PlayerInfo &p = map->players[i];
  887. bool generateHero = (p.generateHeroAtMainTown && p.hasMainTown);
  888. if(generateHero && vstd::contains(scenarioOps->playerInfos, i))
  889. {
  890. int3 hpos = p.posOfMainTown;
  891. hpos.x+=1;
  892. int h = pickHero(i);
  893. if(scenarioOps->playerInfos[i].hero == -1)
  894. scenarioOps->playerInfos[i].hero = h;
  895. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(GameConstants::HEROI_TYPE,h,hpos,i));
  896. nnn->id = map->objects.size();
  897. nnn->initHero();
  898. map->heroes.push_back(nnn);
  899. map->objects.push_back(nnn);
  900. map->addBlockVisTiles(nnn);
  901. }
  902. }
  903. /*************************replace hero placeholders*****************************/
  904. if (campaign)
  905. {
  906. CScenarioTravel::STravelBonus bonus =
  907. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  908. std::vector<CGHeroInstance *> Xheroes;
  909. if (bonus.type == 8) //hero crossover
  910. {
  911. Xheroes = campaign->camp->scenarios[bonus.info2].crossoverHeroes;
  912. }
  913. //selecting heroes by type
  914. for(int g=0; g<map->objects.size(); ++g)
  915. {
  916. CGObjectInstance * obj = map->objects[g];
  917. if (obj->ID != 214) //not a placeholder
  918. {
  919. continue;
  920. }
  921. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  922. if(hp->subID != 0xFF) //select by type
  923. {
  924. bool found = false;
  925. BOOST_FOREACH(CGHeroInstance * ghi, Xheroes)
  926. {
  927. if (ghi->subID == hp->subID)
  928. {
  929. found = true;
  930. HLP::replaceHero(this, g, ghi);
  931. Xheroes -= ghi;
  932. break;
  933. }
  934. }
  935. if (!found)
  936. {
  937. //TODO: create new hero of this type
  938. }
  939. }
  940. }
  941. //selecting heroes by power
  942. std::sort(Xheroes.begin(), Xheroes.end(), HLP::heroPowerSorter);
  943. for(int g=0; g<map->objects.size(); ++g)
  944. {
  945. CGObjectInstance * obj = map->objects[g];
  946. if (obj->ID != 214) //not a placeholder
  947. {
  948. continue;
  949. }
  950. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  951. if (hp->subID == 0xFF) //select by power
  952. {
  953. if(Xheroes.size() > hp->power - 1)
  954. HLP::replaceHero(this, g, Xheroes[hp->power - 1]);
  955. else
  956. tlog2 << "Warning, to hero to replace!\n";
  957. //we don't have to remove hero from Xheroes because it would destroy the order and duplicates shouldn't happen
  958. }
  959. }
  960. }
  961. /******************RESOURCES****************************************************/
  962. TResources startresAI, startresHuman;
  963. const JsonNode config(ResourceID("config/startres.json"));
  964. const JsonVector &vector = config["difficulty"].Vector();
  965. const JsonNode &level = vector[scenarioOps->difficulty];
  966. const JsonNode &human = level["human"];
  967. const JsonNode &ai = level["ai"];
  968. startresHuman[0] = human["wood"].Float();
  969. startresHuman[1] = human["mercury"].Float();
  970. startresHuman[2] = human["ore"].Float();
  971. startresHuman[3] = human["sulfur"].Float();
  972. startresHuman[4] = human["crystal"].Float();
  973. startresHuman[5] = human["gems"].Float();
  974. startresHuman[6] = human["gold"].Float();
  975. startresHuman[7] = human["mithril"].Float();
  976. startresAI[0] = ai["wood"].Float();
  977. startresAI[1] = ai["mercury"].Float();
  978. startresAI[2] = ai["ore"].Float();
  979. startresAI[3] = ai["sulfur"].Float();
  980. startresAI[4] = ai["crystal"].Float();
  981. startresAI[5] = ai["gems"].Float();
  982. startresAI[6] = ai["gold"].Float();
  983. startresAI[7] = ai["mithril"].Float();
  984. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  985. {
  986. PlayerState &p = i->second;
  987. if (p.human)
  988. p.resources = startresHuman;
  989. else
  990. p.resources = startresAI;
  991. }
  992. //give start resource bonus in case of campaign
  993. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  994. {
  995. CScenarioTravel::STravelBonus chosenBonus =
  996. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  997. if(chosenBonus.type == 7) //resource
  998. {
  999. std::vector<const PlayerSettings *> people = HLP::getHumanPlayerInfo(scenarioOps); //players we will give resource bonus
  1000. BOOST_FOREACH(const PlayerSettings *ps, people)
  1001. {
  1002. std::vector<int> res; //resources we will give
  1003. switch (chosenBonus.info1)
  1004. {
  1005. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1006. res.push_back(chosenBonus.info1);
  1007. break;
  1008. case 0xFD: //wood+ore
  1009. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1010. break;
  1011. case 0xFE: //rare
  1012. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1013. break;
  1014. default:
  1015. assert(0);
  1016. break;
  1017. }
  1018. //increasing resource quantity
  1019. for (int n=0; n<res.size(); ++n)
  1020. {
  1021. players[ps->color].resources[res[n]] += chosenBonus.info2;
  1022. }
  1023. }
  1024. }
  1025. }
  1026. /*************************HEROES************************************************/
  1027. std::set<int> hids; //hero ids to create pool
  1028. for(ui32 i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1029. if(map->allowedHeroes[i])
  1030. hids.insert(i);
  1031. for (ui32 i=0; i<map->heroes.size();i++) //heroes instances initialization
  1032. {
  1033. if (map->heroes[i]->getOwner()<0)
  1034. {
  1035. tlog2 << "Warning - hero with uninitialized owner!\n";
  1036. continue;
  1037. }
  1038. CGHeroInstance * vhi = (map->heroes[i]);
  1039. vhi->initHero();
  1040. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1041. hids.erase(vhi->subID);
  1042. }
  1043. for (ui32 i=0; i<map->objects.size();i++) //prisons
  1044. {
  1045. if (map->objects[i]->ID == 62)
  1046. hids.erase(map->objects[i]->subID);
  1047. }
  1048. for(ui32 i=0; i<map->predefinedHeroes.size(); i++)
  1049. {
  1050. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1051. continue;
  1052. map->predefinedHeroes[i]->initHero();
  1053. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1054. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1055. hids.erase(map->predefinedHeroes[i]->subID);
  1056. }
  1057. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1058. {
  1059. CGHeroInstance * vhi = new CGHeroInstance();
  1060. vhi->initHero(hid);
  1061. hpool.heroesPool[hid] = vhi;
  1062. hpool.pavailable[hid] = 0xff;
  1063. }
  1064. for(ui32 i=0; i<map->disposedHeroes.size(); i++)
  1065. {
  1066. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1067. }
  1068. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1069. {
  1070. CScenarioTravel::STravelBonus chosenBonus =
  1071. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1072. if (chosenBonus.isBonusForHero() && chosenBonus.info1 != 0xFFFE) //exclude generated heroes
  1073. {
  1074. //find human player
  1075. int humanPlayer=GameConstants::NEUTRAL_PLAYER;
  1076. for (std::map<ui8, PlayerState>::iterator it=players.begin(); it != players.end(); ++it)
  1077. {
  1078. if(it->second.human)
  1079. {
  1080. humanPlayer = it->first;
  1081. break;
  1082. }
  1083. }
  1084. assert(humanPlayer != GameConstants::NEUTRAL_PLAYER);
  1085. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1086. if (chosenBonus.info1 == 0xFFFD) //most powerful
  1087. {
  1088. int maxB = -1;
  1089. for (int b=0; b<heroes.size(); ++b)
  1090. {
  1091. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1092. {
  1093. maxB = b;
  1094. }
  1095. }
  1096. if(maxB < 0)
  1097. tlog2 << "Warning - cannot give bonus to hero cause there are no heroes!\n";
  1098. else
  1099. HLP::giveCampaignBonusToHero(heroes[maxB], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions, this);
  1100. }
  1101. else //specific hero
  1102. {
  1103. for (int b=0; b<heroes.size(); ++b)
  1104. {
  1105. if (heroes[b]->subID == chosenBonus.info1)
  1106. {
  1107. HLP::giveCampaignBonusToHero(heroes[b], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions, this);
  1108. break;
  1109. }
  1110. }
  1111. }
  1112. }
  1113. }
  1114. /*************************FOG**OF**WAR******************************************/
  1115. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  1116. {
  1117. k->second.fogOfWarMap.resize(map->width);
  1118. for(int g=0; g<map->width; ++g)
  1119. k->second.fogOfWarMap[g].resize(map->height);
  1120. for(int g=-0; g<map->width; ++g)
  1121. for(int h=0; h<map->height; ++h)
  1122. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1123. for(int g=0; g<map->width; ++g)
  1124. for(int h=0; h<map->height; ++h)
  1125. for(int v=0; v<map->twoLevel+1; ++v)
  1126. k->second.fogOfWarMap[g][h][v] = 0;
  1127. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1128. {
  1129. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  1130. boost::unordered_set<int3, ShashInt3> tiles;
  1131. obj->getSightTiles(tiles);
  1132. BOOST_FOREACH(int3 tile, tiles)
  1133. {
  1134. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1135. }
  1136. }
  1137. }
  1138. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1139. {
  1140. //starting bonus
  1141. if(scenarioOps->playerInfos[k->first].bonus==PlayerSettings::brandom)
  1142. scenarioOps->playerInfos[k->first].bonus = ran()%3;
  1143. switch(scenarioOps->playerInfos[k->first].bonus)
  1144. {
  1145. case PlayerSettings::bgold:
  1146. k->second.resources[Res::GOLD] += 500 + (ran()%6)*100;
  1147. break;
  1148. case PlayerSettings::bresource:
  1149. {
  1150. int res = VLC->townh->towns[scenarioOps->playerInfos[k->first].castle].primaryRes;
  1151. if(res == 127)
  1152. {
  1153. k->second.resources[Res::WOOD] += 5 + ran()%6;
  1154. k->second.resources[Res::ORE] += 5 + ran()%6;
  1155. }
  1156. else
  1157. {
  1158. k->second.resources[res] += 3 + ran()%4;
  1159. }
  1160. break;
  1161. }
  1162. case PlayerSettings::bartifact:
  1163. {
  1164. if(!k->second.heroes.size())
  1165. {
  1166. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1167. break;
  1168. }
  1169. CArtifact *toGive;
  1170. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1171. CGHeroInstance *hero = k->second.heroes[0];
  1172. giveHeroArtifact(hero, toGive->id);
  1173. }
  1174. break;
  1175. }
  1176. }
  1177. /****************************TOWNS************************************************/
  1178. for ( int i=0; i<4; i++)
  1179. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1180. for (ui32 i=0;i<map->towns.size();i++)
  1181. {
  1182. CGTownInstance * vti =(map->towns[i]);
  1183. if(!vti->town)
  1184. vti->town = &VLC->townh->towns[vti->subID];
  1185. if (vti->name.length()==0) // if town hasn't name we draw it
  1186. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1187. //init buildings
  1188. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1189. {
  1190. vti->builtBuildings.erase(-50);
  1191. vti->builtBuildings.insert(10);
  1192. vti->builtBuildings.insert(5);
  1193. vti->builtBuildings.insert(30);
  1194. if(ran()%2)
  1195. vti->builtBuildings.insert(31);
  1196. }
  1197. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==2)
  1198. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  1199. //init hordes
  1200. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1201. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1202. {
  1203. vti->builtBuildings.erase(-31-i);//remove old ID
  1204. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1205. {
  1206. vti->builtBuildings.insert(18);//add it
  1207. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1208. vti->builtBuildings.insert(19);//add it as well
  1209. }
  1210. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1211. {
  1212. vti->builtBuildings.insert(24);
  1213. if (vstd::contains(vti->builtBuildings,(37+i)))
  1214. vti->builtBuildings.insert(25);
  1215. }
  1216. }
  1217. //town events
  1218. BOOST_FOREACH(CCastleEvent *ev, vti->events)
  1219. {
  1220. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1221. if (vstd::contains(ev->buildings,(-31-i))) //if we have horde for this level
  1222. {
  1223. ev->buildings.erase(-31-i);
  1224. if (vti->town->hordeLvl[0] == i)
  1225. ev->buildings.insert(18);
  1226. if (vti->town->hordeLvl[1] == i)
  1227. ev->buildings.insert(24);
  1228. }
  1229. }
  1230. //init spells
  1231. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1232. CSpell *s;
  1233. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1234. {
  1235. s = VLC->spellh->spells[vti->obligatorySpells[z]];
  1236. vti->spells[s->level-1].push_back(s->id);
  1237. vti->possibleSpells -= s->id;
  1238. }
  1239. while(vti->possibleSpells.size())
  1240. {
  1241. ui32 total=0;
  1242. int sel = -1;
  1243. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1244. total += VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1245. int r = (total)? ran()%total : -1;
  1246. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1247. {
  1248. r -= VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1249. if(r<0)
  1250. {
  1251. sel = ps;
  1252. break;
  1253. }
  1254. }
  1255. if(sel<0)
  1256. sel=0;
  1257. CSpell *s = VLC->spellh->spells[vti->possibleSpells[sel]];
  1258. vti->spells[s->level-1].push_back(s->id);
  1259. vti->possibleSpells -= s->id;
  1260. }
  1261. if(vti->getOwner() != 255)
  1262. getPlayer(vti->getOwner())->towns.push_back(vti);
  1263. }
  1264. //campaign bonuses for towns
  1265. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1266. {
  1267. CScenarioTravel::STravelBonus chosenBonus =
  1268. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1269. if (chosenBonus.type == 2)
  1270. {
  1271. for (int g=0; g<map->towns.size(); ++g)
  1272. {
  1273. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1274. if (owner)
  1275. {
  1276. PlayerInfo & pi = map->players[owner->color];
  1277. if (owner->human && //human-owned
  1278. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1279. {
  1280. map->towns[g]->builtBuildings.insert(
  1281. CBuildingHandler::campToERMU(chosenBonus.info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  1282. break;
  1283. }
  1284. }
  1285. }
  1286. }
  1287. }
  1288. objCaller->preInit();
  1289. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1290. {
  1291. obj->initObj();
  1292. if(obj->ID == 62) //prison also needs to initialize hero
  1293. static_cast<CGHeroInstance*>(obj)->initHero();
  1294. }
  1295. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1296. {
  1297. switch (obj->ID)
  1298. {
  1299. case Obj::QUEST_GUARD:
  1300. case Obj::SEER_HUT:
  1301. {
  1302. auto q = static_cast<CGSeerHut*>(obj);
  1303. assert (q);
  1304. q->setObjToKill();
  1305. }
  1306. }
  1307. }
  1308. CGTeleport::postInit(); //pairing subterranean gates
  1309. buildBonusSystemTree();
  1310. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1311. {
  1312. if(k->first==255)
  1313. continue;
  1314. //init visiting and garrisoned heroes
  1315. BOOST_FOREACH(CGHeroInstance *h, k->second.heroes)
  1316. {
  1317. BOOST_FOREACH(CGTownInstance *t, k->second.towns)
  1318. {
  1319. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1320. if(vistile == h->pos || h->pos==t->pos)
  1321. {
  1322. t->setVisitingHero(h);
  1323. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1324. {
  1325. map->removeBlockVisTiles(h);
  1326. h->pos.x -= 1;
  1327. map->addBlockVisTiles(h);
  1328. }
  1329. break;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. map->checkForObjectives(); //needs to be run when all objects are properly placed
  1335. int seedAfterInit = ran();
  1336. tlog0 << "Seed after init is " << seedAfterInit << " (before was " << scenarioOps->seedToBeUsed << ")" << std::endl;
  1337. if(scenarioOps->seedPostInit > 0)
  1338. {
  1339. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  1340. assert(scenarioOps->seedPostInit == seedAfterInit);
  1341. }
  1342. else
  1343. {
  1344. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  1345. }
  1346. }
  1347. void CGameState::initDuel()
  1348. {
  1349. DuelParameters dp;
  1350. try //CLoadFile likes throwing
  1351. {
  1352. if(boost::algorithm::ends_with(scenarioOps->mapname, ".json"))
  1353. {
  1354. tlog0 << "Loading duel settings from JSON file: " << scenarioOps->mapname << std::endl;
  1355. dp = DuelParameters::fromJSON(scenarioOps->mapname);
  1356. tlog0 << "JSON file has been successfully read!\n";
  1357. }
  1358. else
  1359. {
  1360. CLoadFile lf(scenarioOps->mapname);
  1361. lf >> dp;
  1362. }
  1363. }
  1364. catch(...)
  1365. {
  1366. tlog1 << "Cannot load duel settings from " << scenarioOps->mapname << std::endl;
  1367. throw;
  1368. }
  1369. const CArmedInstance *armies[2] = {0};
  1370. const CGHeroInstance *heroes[2] = {0};
  1371. CGTownInstance *town = NULL;
  1372. for(int i = 0; i < 2; i++)
  1373. {
  1374. CArmedInstance *obj = NULL;
  1375. if(dp.sides[i].heroId >= 0)
  1376. {
  1377. const DuelParameters::SideSettings &ss = dp.sides[i];
  1378. CGHeroInstance *h = new CGHeroInstance();
  1379. armies[i] = heroes[i] = h;
  1380. obj = h;
  1381. h->subID = ss.heroId;
  1382. for(int i = 0; i < ss.heroPrimSkills.size(); i++)
  1383. h->pushPrimSkill(i, ss.heroPrimSkills[i]);
  1384. if(ss.spells.size())
  1385. {
  1386. h->putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  1387. boost::copy(ss.spells, std::inserter(h->spells, h->spells.begin()));
  1388. }
  1389. BOOST_FOREACH(auto &parka, ss.artifacts)
  1390. {
  1391. h->putArtifact(parka.first, parka.second);
  1392. }
  1393. typedef const std::pair<si32, si8> &TSecSKill;
  1394. BOOST_FOREACH(TSecSKill secSkill, ss.heroSecSkills)
  1395. h->setSecSkillLevel((CGHeroInstance::SecondarySkill)secSkill.first, secSkill.second, 1);
  1396. h->initHero(h->subID);
  1397. obj->initObj();
  1398. }
  1399. else
  1400. {
  1401. CGCreature *c = new CGCreature();
  1402. armies[i] = obj = c;
  1403. //c->subID = 34;
  1404. }
  1405. obj->setOwner(i);
  1406. for(int j = 0; j < ARRAY_COUNT(dp.sides[i].stacks); j++)
  1407. {
  1408. TCreature cre = dp.sides[i].stacks[j].type;
  1409. TQuantity count = dp.sides[i].stacks[j].count;
  1410. if(count || obj->hasStackAtSlot(j))
  1411. obj->setCreature(j, cre, count);
  1412. }
  1413. BOOST_FOREACH(const DuelParameters::CusomCreature &cc, dp.creatures)
  1414. {
  1415. CCreature *c = VLC->creh->creatures[cc.id];
  1416. if(cc.attack >= 0)
  1417. c->getBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK))->val = cc.attack;
  1418. if(cc.defense >= 0)
  1419. c->getBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE))->val = cc.defense;
  1420. if(cc.speed >= 0)
  1421. c->getBonus(Selector::type(Bonus::STACKS_SPEED))->val = cc.speed;
  1422. if(cc.HP >= 0)
  1423. c->getBonus(Selector::type(Bonus::STACK_HEALTH))->val = cc.HP;
  1424. if(cc.dmg >= 0)
  1425. {
  1426. c->getBonus(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1))->val = cc.dmg;
  1427. c->getBonus(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2))->val = cc.dmg;
  1428. }
  1429. if(cc.shoots >= 0)
  1430. c->getBonus(Selector::type(Bonus::SHOTS))->val = cc.shoots;
  1431. }
  1432. }
  1433. curB = BattleInfo::setupBattle(int3(), dp.bfieldType, dp.terType, armies, heroes, false, town);
  1434. curB->obstacles = dp.obstacles;
  1435. curB->localInit();
  1436. return;
  1437. }
  1438. int CGameState::battleGetBattlefieldType(int3 tile) const
  1439. {
  1440. if(tile==int3() && curB)
  1441. tile = curB->tile;
  1442. else if(tile==int3() && !curB)
  1443. return -1;
  1444. const TerrainTile &t = map->getTile(tile);
  1445. //fight in mine -> subterranean
  1446. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1447. return 12;
  1448. BOOST_FOREACH(auto &obj, map->objects)
  1449. {
  1450. //look only for objects covering given tile
  1451. if( !obj || obj->pos.z != tile.z
  1452. || !obj->coveringAt(tile.x - obj->pos.x, tile.y - obj->pos.y))
  1453. continue;
  1454. switch(obj->ID)
  1455. {
  1456. case Obj::CLOVER_FIELD:
  1457. return 19;
  1458. case Obj::CURSED_GROUND1: case Obj::CURSED_GROUND2:
  1459. return 22;
  1460. case Obj::EVIL_FOG:
  1461. return 20;
  1462. case Obj::FAVORABLE_WINDS:
  1463. return 21;
  1464. case Obj::FIERY_FIELDS:
  1465. return 14;
  1466. case Obj::HOLY_GROUNDS:
  1467. return 18;
  1468. case Obj::LUCID_POOLS:
  1469. return 17;
  1470. case Obj::MAGIC_CLOUDS:
  1471. return 16;
  1472. case Obj::MAGIC_PLAINS1: case Obj::MAGIC_PLAINS2:
  1473. return 9;
  1474. case Obj::ROCKLANDS:
  1475. return 15;
  1476. }
  1477. }
  1478. if(!t.isWater() && t.isCoastal())
  1479. return 1; //sand/beach
  1480. switch(t.tertype)
  1481. {
  1482. case TerrainTile::dirt:
  1483. return rand()%3+3;
  1484. case TerrainTile::sand:
  1485. return 2; //TODO: coast support
  1486. case TerrainTile::grass:
  1487. return rand()%2+6;
  1488. case TerrainTile::snow:
  1489. return rand()%2+10;
  1490. case TerrainTile::swamp:
  1491. return 13;
  1492. case TerrainTile::rough:
  1493. return 23;
  1494. case TerrainTile::subterranean:
  1495. return 12;
  1496. case TerrainTile::lava:
  1497. return 8;
  1498. case TerrainTile::water:
  1499. return 25;
  1500. case TerrainTile::rock:
  1501. return 15;
  1502. default:
  1503. return -1;
  1504. }
  1505. }
  1506. std::set<std::pair<int, int> > costDiff(const std::vector<ui32> &a, const std::vector<ui32> &b, const int modifier = 100) //modifer %
  1507. {
  1508. std::set<std::pair<int, int> > ret;
  1509. for(int j=0;j<GameConstants::RESOURCE_QUANTITY;j++)
  1510. {
  1511. assert(a[j] >= b[j]);
  1512. if(int dif = modifier * (a[j] - b[j]) / 100)
  1513. ret.insert(std::make_pair(j,dif));
  1514. }
  1515. return ret;
  1516. }
  1517. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1518. {
  1519. UpgradeInfo ret;
  1520. const CCreature *base = stack.type;
  1521. const CGHeroInstance *h = stack.armyObj->ID == GameConstants::HEROI_TYPE ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1522. const CGTownInstance *t = NULL;
  1523. if(stack.armyObj->ID == GameConstants::TOWNI_TYPE)
  1524. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1525. else if(h)
  1526. { //hero speciality
  1527. TBonusListPtr lista = h->speciality.getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1528. BOOST_FOREACH(const Bonus *it, *lista)
  1529. {
  1530. ui16 nid = it->additionalInfo;
  1531. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1532. {
  1533. ret.newID.push_back(nid);
  1534. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1535. }
  1536. }
  1537. t = h->visitedTown;
  1538. }
  1539. if(t)
  1540. {
  1541. BOOST_FOREACH(const CGTownInstance::TCreaturesSet::value_type & dwelling, t->creatures)
  1542. {
  1543. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1544. {
  1545. BOOST_FOREACH(ui32 upgrID, dwelling.second)
  1546. {
  1547. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1548. {
  1549. ret.newID.push_back(upgrID);
  1550. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1551. }
  1552. }
  1553. }
  1554. }
  1555. }
  1556. //hero is visiting Hill Fort
  1557. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1558. {
  1559. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1560. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1561. BOOST_FOREACH(si32 nid, base->upgrades)
  1562. {
  1563. ret.newID.push_back(nid);
  1564. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1565. }
  1566. }
  1567. if(ret.newID.size())
  1568. ret.oldID = base->idNumber;
  1569. return ret;
  1570. }
  1571. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  1572. {
  1573. if ( color1 == color2 )
  1574. return 2;
  1575. if(color1 == 255 || color2 == 255) //neutral player has no friends
  1576. return 0;
  1577. const TeamState * ts = getPlayerTeam(color1);
  1578. if (ts && vstd::contains(ts->players, color2))
  1579. return 1;
  1580. return 0;
  1581. }
  1582. void CGameState::loadTownDInfos()
  1583. {
  1584. int i;
  1585. const JsonNode config(ResourceID("config/towns_defs.json"));
  1586. assert(config["town_defnames"].Vector().size() == GameConstants::F_NUMBER);
  1587. i = 0;
  1588. BOOST_FOREACH(const JsonNode &t, config["town_defnames"].Vector())
  1589. {
  1590. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1591. villages[i]->name = t["village"].String();
  1592. map->defy.push_back(villages[i]);
  1593. forts[i] = VLC->dobjinfo->castles[i];
  1594. map->defy.push_back(forts[i]);
  1595. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1596. capitols[i]->name = t["capitol"].String();
  1597. map->defy.push_back(capitols[i]);
  1598. ++i;
  1599. }
  1600. }
  1601. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1602. {
  1603. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1604. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1605. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1606. {
  1607. const int3 hlp = tile + dirs[i];
  1608. if(!map->isInTheMap(hlp))
  1609. continue;
  1610. const TerrainTile &hlpt = map->getTile(hlp);
  1611. // //we cannot visit things from blocked tiles
  1612. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1613. // {
  1614. // continue;
  1615. // }
  1616. if(srct.tertype == TerrainTile::water && limitCoastSailing && hlpt.tertype == TerrainTile::water && dirs[i].x && dirs[i].y) //diagonal move through water
  1617. {
  1618. int3 hlp1 = tile,
  1619. hlp2 = tile;
  1620. hlp1.x += dirs[i].x;
  1621. hlp2.y += dirs[i].y;
  1622. if(map->getTile(hlp1).tertype != TerrainTile::water || map->getTile(hlp2).tertype != TerrainTile::water)
  1623. continue;
  1624. }
  1625. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1626. && hlpt.tertype != TerrainTile::rock)
  1627. {
  1628. vec.push_back(hlp);
  1629. }
  1630. }
  1631. }
  1632. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1633. {
  1634. if(src == dest) //same tile
  1635. return 0;
  1636. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1637. &d = map->terrain[dest.x][dest.y][dest.z];
  1638. //get basic cost
  1639. int ret = h->getTileCost(d,s);
  1640. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1641. {
  1642. bool freeFlying = h->getBonusesCount(Selector::typeSubtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1643. if(!freeFlying)
  1644. {
  1645. ret *= 1.4; //40% penalty for movement over blocked tile
  1646. }
  1647. }
  1648. else if (d.tertype == TerrainTile::water)
  1649. {
  1650. if(h->boat && s.hasFavourableWinds() && d.hasFavourableWinds()) //Favourable Winds
  1651. ret *= 0.666;
  1652. else if (!h->boat && h->getBonusesCount(Selector::typeSubtype(Bonus::WATER_WALKING, 1)) > 0)
  1653. ret *= 1.4; //40% penalty for water walking
  1654. }
  1655. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1656. {
  1657. int old = ret;
  1658. ret *= 1.414213;
  1659. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1660. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1661. {
  1662. return remainingMovePoints;
  1663. }
  1664. }
  1665. int left = remainingMovePoints-ret;
  1666. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1667. {
  1668. std::vector<int3> vec;
  1669. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water, true);
  1670. for(size_t i=0; i < vec.size(); i++)
  1671. {
  1672. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1673. if(fcost <= left)
  1674. {
  1675. return ret;
  1676. }
  1677. }
  1678. ret = remainingMovePoints;
  1679. }
  1680. return ret;
  1681. }
  1682. void CGameState::apply(CPack *pack)
  1683. {
  1684. ui16 typ = typeList.getTypeID(pack);
  1685. applierGs->apps[typ]->applyOnGS(this,pack);
  1686. }
  1687. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1688. {
  1689. //the old pathfinder is not supported anymore!
  1690. assert(0);
  1691. return false;
  1692. }
  1693. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1694. {
  1695. CPathfinder pathfinder(out, this, hero);
  1696. pathfinder.calculatePaths(src, movement);
  1697. }
  1698. /**
  1699. * Tells if the tile is guarded by a monster as well as the position
  1700. * of the monster that will attack on it.
  1701. *
  1702. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1703. * the monster guarding the tile.
  1704. */
  1705. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1706. {
  1707. const int3 originalPos = pos;
  1708. // Give monster at position priority.
  1709. if (!map->isInTheMap(pos))
  1710. return int3(-1, -1, -1);
  1711. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  1712. if (posTile.visitable)
  1713. {
  1714. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  1715. {
  1716. if(obj->blockVisit)
  1717. {
  1718. if (obj->ID == 54) // Monster
  1719. return pos;
  1720. else
  1721. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  1722. }
  1723. }
  1724. }
  1725. // See if there are any monsters adjacent.
  1726. pos -= int3(1, 1, 0); // Start with top left.
  1727. for (int dx = 0; dx < 3; dx++)
  1728. {
  1729. for (int dy = 0; dy < 3; dy++)
  1730. {
  1731. if (map->isInTheMap(pos))
  1732. {
  1733. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  1734. if (tile.visitable && (tile.tertype == TerrainTile::water) == (posTile.tertype == TerrainTile::water))
  1735. {
  1736. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  1737. {
  1738. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1739. {
  1740. return pos;
  1741. }
  1742. }
  1743. }
  1744. }
  1745. pos.y++;
  1746. }
  1747. pos.y -= 3;
  1748. pos.x++;
  1749. }
  1750. return int3(-1, -1, -1);
  1751. }
  1752. bool CGameState::isVisible(int3 pos, int player)
  1753. {
  1754. if(player == 255) //neutral player
  1755. return false;
  1756. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  1757. }
  1758. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1759. {
  1760. if(player == -1)
  1761. return true;
  1762. if(player == 255) //neutral player -> TODO ??? needed?
  1763. return false;
  1764. //object is visible when at least one blocked tile is visible
  1765. for(int fx=0; fx<8; ++fx)
  1766. {
  1767. for(int fy=0; fy<6; ++fy)
  1768. {
  1769. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1770. if(map->isInTheMap(pos)
  1771. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1772. && isVisible(pos, player) )
  1773. return true;
  1774. }
  1775. }
  1776. return false;
  1777. }
  1778. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1779. {
  1780. const TerrainTile * pom = &map->getTile(dst);
  1781. return checkForVisitableDir(src, pom, dst);
  1782. }
  1783. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  1784. {
  1785. for(ui32 b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1786. {
  1787. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1788. continue;
  1789. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1790. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1791. {
  1792. return false;
  1793. }
  1794. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1795. {
  1796. return false;
  1797. }
  1798. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1799. {
  1800. return false;
  1801. }
  1802. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1803. {
  1804. return false;
  1805. }
  1806. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1807. {
  1808. return false;
  1809. }
  1810. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1811. {
  1812. return false;
  1813. }
  1814. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1815. {
  1816. return false;
  1817. }
  1818. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1819. {
  1820. return false;
  1821. }
  1822. }
  1823. return true;
  1824. }
  1825. int CGameState::victoryCheck( ui8 player ) const
  1826. {
  1827. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1828. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD || map->victoryCondition.allowNormalVictory
  1829. || (!p->human && !map->victoryCondition.appliesToAI)) //if the special victory condition applies only to human, AI has the standard)
  1830. {
  1831. if(player == checkForStandardWin())
  1832. return -1;
  1833. }
  1834. if (p->enteredWinningCheatCode)
  1835. { //cheater or tester, but has entered the code...
  1836. return 1;
  1837. }
  1838. if(p->human || map->victoryCondition.appliesToAI)
  1839. {
  1840. switch(map->victoryCondition.condition)
  1841. {
  1842. case EVictoryConditionType::ARTIFACT:
  1843. //check if any hero has winning artifact
  1844. for(size_t i = 0; i < p->heroes.size(); i++)
  1845. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  1846. return 1;
  1847. break;
  1848. case EVictoryConditionType::GATHERTROOP:
  1849. {
  1850. //check if in players armies there is enough creatures
  1851. int total = 0; //creature counter
  1852. for(size_t i = 0; i < map->objects.size(); i++)
  1853. {
  1854. const CArmedInstance *ai = NULL;
  1855. if(map->objects[i]
  1856. && map->objects[i]->tempOwner == player //object controlled by player
  1857. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  1858. {
  1859. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  1860. if(i->second->type->idNumber == map->victoryCondition.ID) //it's searched creature
  1861. total += i->second->count;
  1862. }
  1863. }
  1864. if(total >= map->victoryCondition.count)
  1865. return 1;
  1866. }
  1867. break;
  1868. case EVictoryConditionType::GATHERRESOURCE:
  1869. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  1870. return 1;
  1871. break;
  1872. case EVictoryConditionType::BUILDCITY:
  1873. {
  1874. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1875. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  1876. return 1;
  1877. }
  1878. break;
  1879. case EVictoryConditionType::BUILDGRAIL:
  1880. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  1881. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  1882. && t->tempOwner == player
  1883. && vstd::contains(t->builtBuildings, EBuilding::GRAIL))
  1884. return 1;
  1885. break;
  1886. case EVictoryConditionType::BEATHERO:
  1887. if(map->victoryCondition.obj->tempOwner >= GameConstants::PLAYER_LIMIT) //target hero not present on map
  1888. return 1;
  1889. break;
  1890. case EVictoryConditionType::CAPTURECITY:
  1891. {
  1892. if(map->victoryCondition.obj->tempOwner == player)
  1893. return 1;
  1894. }
  1895. break;
  1896. case EVictoryConditionType::BEATMONSTER:
  1897. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  1898. return 1;
  1899. break;
  1900. case EVictoryConditionType::TAKEDWELLINGS:
  1901. for(size_t i = 0; i < map->objects.size(); i++)
  1902. {
  1903. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1904. {
  1905. switch(map->objects[i]->ID)
  1906. {
  1907. case 17: case 18: case 19: case 20: //dwellings
  1908. case 216: case 217: case 218:
  1909. return 0; //found not flagged dwelling - player not won
  1910. }
  1911. }
  1912. }
  1913. return 1;
  1914. break;
  1915. case EVictoryConditionType::TAKEMINES:
  1916. for(size_t i = 0; i < map->objects.size(); i++)
  1917. {
  1918. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1919. {
  1920. switch(map->objects[i]->ID)
  1921. {
  1922. case 53: case 220:
  1923. return 0; //found not flagged mine - player not won
  1924. }
  1925. }
  1926. }
  1927. return 1;
  1928. break;
  1929. case EVictoryConditionType::TRANSPORTITEM:
  1930. {
  1931. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1932. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID))
  1933. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID)))
  1934. {
  1935. return 1;
  1936. }
  1937. }
  1938. break;
  1939. }
  1940. }
  1941. return 0;
  1942. }
  1943. ui8 CGameState::checkForStandardWin() const
  1944. {
  1945. //std victory condition is:
  1946. //all enemies lost
  1947. ui8 supposedWinner = 255, winnerTeam = 255;
  1948. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  1949. {
  1950. if(i->second.status == PlayerState::INGAME && i->first < GameConstants::PLAYER_LIMIT)
  1951. {
  1952. if(supposedWinner == 255)
  1953. {
  1954. //first player remaining ingame - candidate for victory
  1955. supposedWinner = i->second.color;
  1956. winnerTeam = i->second.team;
  1957. }
  1958. else if(winnerTeam != i->second.team)
  1959. {
  1960. //current candidate has enemy remaining in game -> no vicotry
  1961. return 255;
  1962. }
  1963. }
  1964. }
  1965. return supposedWinner;
  1966. }
  1967. bool CGameState::checkForStandardLoss( ui8 player ) const
  1968. {
  1969. //std loss condition is: player lost all towns and heroes
  1970. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  1971. return !p.heroes.size() && !p.towns.size();
  1972. }
  1973. struct statsHLP
  1974. {
  1975. typedef std::pair< ui8, si64 > TStat;
  1976. //converts [<player's color, value>] to vec[place] -> platers
  1977. static std::vector< std::vector< ui8 > > getRank( std::vector<TStat> stats )
  1978. {
  1979. std::sort(stats.begin(), stats.end(), statsHLP());
  1980. //put first element
  1981. std::vector< std::vector<ui8> > ret;
  1982. std::vector<ui8> tmp;
  1983. tmp.push_back( stats[0].first );
  1984. ret.push_back( tmp );
  1985. //the rest of elements
  1986. for(int g=1; g<stats.size(); ++g)
  1987. {
  1988. if(stats[g].second == stats[g-1].second)
  1989. {
  1990. (ret.end()-1)->push_back( stats[g].first );
  1991. }
  1992. else
  1993. {
  1994. //create next occupied rank
  1995. std::vector<ui8> tmp;
  1996. tmp.push_back(stats[g].first);
  1997. ret.push_back(tmp);
  1998. }
  1999. }
  2000. return ret;
  2001. }
  2002. bool operator()(const TStat & a, const TStat & b) const
  2003. {
  2004. return a.second > b.second;
  2005. }
  2006. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2007. {
  2008. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2009. if(!h.size())
  2010. return NULL;
  2011. //best hero will be that with highest exp
  2012. int best = 0;
  2013. for(int b=1; b<h.size(); ++b)
  2014. {
  2015. if(h[b]->exp > h[best]->exp)
  2016. {
  2017. best = b;
  2018. }
  2019. }
  2020. return h[best];
  2021. }
  2022. //calculates total number of artifacts that belong to given player
  2023. static int getNumberOfArts(const PlayerState * ps)
  2024. {
  2025. int ret = 0;
  2026. for(int g=0; g<ps->heroes.size(); ++g)
  2027. {
  2028. ret += ps->heroes[g]->artifactsInBackpack.size() + ps->heroes[g]->artifactsWorn.size();
  2029. }
  2030. return ret;
  2031. }
  2032. };
  2033. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2034. {
  2035. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2036. { \
  2037. std::vector< std::pair< ui8, si64 > > stats; \
  2038. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  2039. { \
  2040. if(g->second.color == 255) \
  2041. continue; \
  2042. std::pair< ui8, si64 > stat; \
  2043. stat.first = g->second.color; \
  2044. stat.second = VAL_GETTER; \
  2045. stats.push_back(stat); \
  2046. } \
  2047. tgi.FIELD = statsHLP::getRank(stats); \
  2048. }
  2049. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2050. {
  2051. if(g->second.color != 255)
  2052. tgi.playerColors.push_back(g->second.color);
  2053. }
  2054. if(level >= 1) //num of towns & num of heroes
  2055. {
  2056. //num of towns
  2057. FILL_FIELD(numOfTowns, g->second.towns.size())
  2058. //num of heroes
  2059. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2060. //best hero's portrait
  2061. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2062. {
  2063. if(g->second.color == 255)
  2064. continue;
  2065. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2066. InfoAboutHero iah;
  2067. iah.initFromHero(best, level >= 8);
  2068. iah.army.clear();
  2069. tgi.colorToBestHero[g->second.color] = iah;
  2070. }
  2071. }
  2072. if(level >= 2) //gold
  2073. {
  2074. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2075. }
  2076. if(level >= 2) //wood & ore
  2077. {
  2078. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2079. }
  2080. if(level >= 3) //mercury, sulfur, crystal, gems
  2081. {
  2082. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2083. }
  2084. if(level >= 4) //obelisks found
  2085. {
  2086. //TODO
  2087. }
  2088. if(level >= 5) //artifacts
  2089. {
  2090. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2091. }
  2092. if(level >= 6) //army strength
  2093. {
  2094. //TODO
  2095. }
  2096. if(level >= 7) //income
  2097. {
  2098. //TODO
  2099. }
  2100. if(level >= 8) //best hero's stats
  2101. {
  2102. //already set in lvl 1 handling
  2103. }
  2104. if(level >= 9) //personality
  2105. {
  2106. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2107. {
  2108. if(g->second.color == 255) //do nothing for neutral player
  2109. continue;
  2110. if(g->second.human)
  2111. {
  2112. tgi.personality[g->second.color] = -1;
  2113. }
  2114. else //AI
  2115. {
  2116. tgi.personality[g->second.color] = map->players[g->second.color].AITactic;
  2117. }
  2118. }
  2119. }
  2120. if(level >= 10) //best creature
  2121. {
  2122. //best creatures belonging to player (highest AI value)
  2123. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2124. {
  2125. if(g->second.color == 255) //do nothing for neutral player
  2126. continue;
  2127. int bestCre = -1; //best creature's ID
  2128. for(int b=0; b<g->second.heroes.size(); ++b)
  2129. {
  2130. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  2131. {
  2132. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2133. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2134. {
  2135. bestCre = toCmp;
  2136. }
  2137. }
  2138. }
  2139. tgi.bestCreature[g->second.color] = bestCre;
  2140. }
  2141. }
  2142. #undef FILL_FIELD
  2143. }
  2144. int CGameState::lossCheck( ui8 player ) const
  2145. {
  2146. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2147. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2148. if(checkForStandardLoss(player))
  2149. return -1;
  2150. if (p->enteredLosingCheatCode)
  2151. {
  2152. return 1;
  2153. }
  2154. if(p->human) //special loss condition applies only to human player
  2155. {
  2156. switch(map->lossCondition.typeOfLossCon)
  2157. {
  2158. case ELossConditionType::LOSSCASTLE:
  2159. {
  2160. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  2161. assert(t);
  2162. if(t->tempOwner != player)
  2163. return 1;
  2164. }
  2165. break;
  2166. case ELossConditionType::LOSSHERO:
  2167. {
  2168. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  2169. assert(h);
  2170. if(h->tempOwner != player)
  2171. return 1;
  2172. }
  2173. break;
  2174. case ELossConditionType::TIMEEXPIRES:
  2175. if(map->lossCondition.timeLimit < day)
  2176. return 1;
  2177. break;
  2178. }
  2179. }
  2180. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  2181. return 2;
  2182. return false;
  2183. }
  2184. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2185. {
  2186. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2187. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  2188. for(std::vector< ConstTransitivePtr<CGHeroInstance> >::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2189. if(*j)
  2190. pool.erase((**j).subID);
  2191. return pool;
  2192. }
  2193. void CGameState::buildBonusSystemTree()
  2194. {
  2195. buildGlobalTeamPlayerTree();
  2196. attachArmedObjects();
  2197. BOOST_FOREACH(CGTownInstance *t, map->towns)
  2198. {
  2199. t->deserializationFix();
  2200. }
  2201. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2202. // are provided on initializing / deserializing
  2203. }
  2204. void CGameState::deserializationFix()
  2205. {
  2206. buildGlobalTeamPlayerTree();
  2207. attachArmedObjects();
  2208. }
  2209. void CGameState::buildGlobalTeamPlayerTree()
  2210. {
  2211. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  2212. {
  2213. TeamState *t = &k->second;
  2214. t->attachTo(&globalEffects);
  2215. BOOST_FOREACH(ui8 teamMember, k->second.players)
  2216. {
  2217. PlayerState *p = getPlayer(teamMember);
  2218. assert(p);
  2219. p->attachTo(t);
  2220. }
  2221. }
  2222. }
  2223. void CGameState::attachArmedObjects()
  2224. {
  2225. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  2226. {
  2227. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2228. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2229. }
  2230. }
  2231. void CGameState::giveHeroArtifact(CGHeroInstance *h, int aid)
  2232. {
  2233. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2234. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2235. map->addNewArtifactInstance(ai);
  2236. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2237. }
  2238. int3 CPath::startPos() const
  2239. {
  2240. return nodes[nodes.size()-1].coord;
  2241. }
  2242. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2243. {
  2244. if (mode==0)
  2245. {
  2246. for (ui32 i=0;i<nodes.size();i++)
  2247. {
  2248. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2249. }
  2250. }
  2251. }
  2252. int3 CPath::endPos() const
  2253. {
  2254. return nodes[0].coord;
  2255. }
  2256. CGPathNode::CGPathNode()
  2257. :coord(-1,-1,-1)
  2258. {
  2259. accessible = 0;
  2260. land = 0;
  2261. moveRemains = 0;
  2262. turns = 255;
  2263. theNodeBefore = NULL;
  2264. }
  2265. bool CGPathNode::reachable() const
  2266. {
  2267. return turns < 255;
  2268. }
  2269. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2270. {
  2271. assert(isValid);
  2272. out.nodes.clear();
  2273. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2274. if(!curnode->theNodeBefore)
  2275. return false;
  2276. while(curnode)
  2277. {
  2278. CGPathNode cpn = *curnode;
  2279. curnode = curnode->theNodeBefore;
  2280. out.nodes.push_back(cpn);
  2281. }
  2282. return true;
  2283. }
  2284. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2285. :sizes(Sizes)
  2286. {
  2287. hero = NULL;
  2288. nodes = new CGPathNode**[sizes.x];
  2289. for(int i = 0; i < sizes.x; i++)
  2290. {
  2291. nodes[i] = new CGPathNode*[sizes.y];
  2292. for (int j = 0; j < sizes.y; j++)
  2293. {
  2294. nodes[i][j] = new CGPathNode[sizes.z];
  2295. }
  2296. }
  2297. }
  2298. CPathsInfo::~CPathsInfo()
  2299. {
  2300. for(int i = 0; i < sizes.x; i++)
  2301. {
  2302. for (int j = 0; j < sizes.y; j++)
  2303. {
  2304. delete [] nodes[i][j];
  2305. }
  2306. delete [] nodes[i];
  2307. }
  2308. delete [] nodes;
  2309. }
  2310. int3 CGPath::startPos() const
  2311. {
  2312. return nodes[nodes.size()-1].coord;
  2313. }
  2314. int3 CGPath::endPos() const
  2315. {
  2316. return nodes[0].coord;
  2317. }
  2318. void CGPath::convert( ui8 mode )
  2319. {
  2320. if(mode==0)
  2321. {
  2322. for(ui32 i=0;i<nodes.size();i++)
  2323. {
  2324. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2325. }
  2326. }
  2327. }
  2328. PlayerState::PlayerState()
  2329. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2330. enteredLosingCheatCode(0), status(INGAME), daysWithoutCastle(0)
  2331. {
  2332. setNodeType(PLAYER);
  2333. }
  2334. std::string PlayerState::nodeName() const
  2335. {
  2336. return "Player " + (color < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color] : boost::lexical_cast<std::string>(color));
  2337. }
  2338. // void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  2339. // {
  2340. // return; //no loops possible
  2341. // }
  2342. //
  2343. // void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  2344. // {
  2345. // for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); it++)
  2346. // {
  2347. // if (*it != root)
  2348. // (*it)->getBonuses(out, selector, this);
  2349. // }
  2350. // }
  2351. InfoAboutArmy::InfoAboutArmy():
  2352. owner(GameConstants::NEUTRAL_PLAYER)
  2353. {}
  2354. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2355. {
  2356. initFromArmy(Army, detailed);
  2357. }
  2358. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2359. {
  2360. army = ArmyDescriptor(Army, detailed);
  2361. owner = Army->tempOwner;
  2362. name = Army->getHoverText();
  2363. }
  2364. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2365. {
  2366. InfoAboutArmy::operator = (iah);
  2367. details = (iah.details ? new Details(*iah.details) : NULL);
  2368. hclass = iah.hclass;
  2369. portrait = iah.portrait;
  2370. }
  2371. InfoAboutHero::InfoAboutHero():
  2372. details(nullptr),
  2373. hclass(nullptr),
  2374. portrait(-1)
  2375. {}
  2376. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2377. InfoAboutArmy()
  2378. {
  2379. assign(iah);
  2380. }
  2381. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, bool detailed)
  2382. {
  2383. initFromHero(h, detailed);
  2384. }
  2385. InfoAboutHero::~InfoAboutHero()
  2386. {
  2387. delete details;
  2388. }
  2389. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2390. {
  2391. assign(iah);
  2392. return *this;
  2393. }
  2394. void InfoAboutHero::initFromHero(const CGHeroInstance *h, bool detailed)
  2395. {
  2396. if(!h)
  2397. return;
  2398. initFromArmy(h, detailed);
  2399. hclass = h->type->heroClass;
  2400. name = h->name;
  2401. portrait = h->portrait;
  2402. if(detailed)
  2403. {
  2404. //include details about hero
  2405. details = new Details;
  2406. details->luck = h->LuckVal();
  2407. details->morale = h->MoraleVal();
  2408. details->mana = h->mana;
  2409. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2410. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2411. {
  2412. details->primskills[i] = h->getPrimSkillLevel(i);
  2413. }
  2414. }
  2415. }
  2416. InfoAboutTown::InfoAboutTown():
  2417. details(nullptr),
  2418. tType(nullptr),
  2419. built(0),
  2420. fortLevel(0)
  2421. {
  2422. }
  2423. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed)
  2424. {
  2425. initFromTown(t, detailed);
  2426. }
  2427. InfoAboutTown::~InfoAboutTown()
  2428. {
  2429. delete details;
  2430. }
  2431. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2432. {
  2433. initFromArmy(t, detailed);
  2434. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2435. built = t->builded;
  2436. fortLevel = t->fortLevel();
  2437. name = t->name;
  2438. tType = t->town;
  2439. if(detailed)
  2440. {
  2441. //include details about hero
  2442. details = new Details;
  2443. details->goldIncome = t->dailyIncome();
  2444. details->customRes = vstd::contains(t->builtBuildings, 15);
  2445. details->hallLevel = t->hallLevel();
  2446. details->garrisonedHero = t->garrisonHero;
  2447. }
  2448. }
  2449. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2450. : isDetailed(detailed)
  2451. {
  2452. for(TSlots::const_iterator i = army->Slots().begin(); i != army->Slots().end(); i++)
  2453. {
  2454. if(detailed)
  2455. (*this)[i->first] = *i->second;
  2456. else
  2457. (*this)[i->first] = CStackBasicDescriptor(i->second->type, i->second->getQuantityID());
  2458. }
  2459. }
  2460. ArmyDescriptor::ArmyDescriptor()
  2461. : isDetailed(false)
  2462. {
  2463. }
  2464. int ArmyDescriptor::getStrength() const
  2465. {
  2466. ui64 ret = 0;
  2467. if(isDetailed)
  2468. {
  2469. for(const_iterator i = begin(); i != end(); i++)
  2470. ret += i->second.type->AIValue * i->second.count;
  2471. }
  2472. else
  2473. {
  2474. for(const_iterator i = begin(); i != end(); i++)
  2475. ret += i->second.type->AIValue * CCreature::estimateCreatureCount(i->second.count);
  2476. }
  2477. return ret;
  2478. }
  2479. DuelParameters::SideSettings::StackSettings::StackSettings()
  2480. : type(-1), count(0)
  2481. {
  2482. }
  2483. DuelParameters::SideSettings::StackSettings::StackSettings(si32 Type, si32 Count)
  2484. : type(Type), count(Count)
  2485. {
  2486. }
  2487. DuelParameters::SideSettings::SideSettings()
  2488. {
  2489. heroId = -1;
  2490. }
  2491. DuelParameters::DuelParameters()
  2492. {
  2493. terType = TerrainTile::dirt;
  2494. bfieldType = 15;
  2495. }
  2496. DuelParameters DuelParameters::fromJSON(const std::string &fname)
  2497. {
  2498. DuelParameters ret;
  2499. const JsonNode duelData(ResourceID(fname, EResType::TEXT));
  2500. ret.terType = duelData["terType"].Float();
  2501. ret.bfieldType = duelData["bfieldType"].Float();
  2502. BOOST_FOREACH(const JsonNode &n, duelData["sides"].Vector())
  2503. {
  2504. SideSettings &ss = ret.sides[(int)n["side"].Float()];
  2505. int i = 0;
  2506. BOOST_FOREACH(const JsonNode &stackNode, n["army"].Vector())
  2507. {
  2508. ss.stacks[i].type = stackNode.Vector()[0].Float();
  2509. ss.stacks[i].count = stackNode.Vector()[1].Float();
  2510. i++;
  2511. }
  2512. if(n["heroid"].getType() == JsonNode::DATA_FLOAT)
  2513. ss.heroId = n["heroid"].Float();
  2514. else
  2515. ss.heroId = -1;
  2516. BOOST_FOREACH(const JsonNode &n, n["heroPrimSkills"].Vector())
  2517. ss.heroPrimSkills.push_back(n.Float());
  2518. BOOST_FOREACH(const JsonNode &skillNode, n["heroSecSkills"].Vector())
  2519. {
  2520. std::pair<si32, si8> secSkill;
  2521. secSkill.first = skillNode.Vector()[0].Float();
  2522. secSkill.second = skillNode.Vector()[1].Float();
  2523. ss.heroSecSkills.push_back(secSkill);
  2524. }
  2525. assert(ss.heroPrimSkills.empty() || ss.heroPrimSkills.size() == GameConstants::PRIMARY_SKILLS);
  2526. if(ss.heroId != -1)
  2527. {
  2528. BOOST_FOREACH(const JsonNode &spell, n["spells"].Vector())
  2529. ss.spells.insert(spell.Float());
  2530. }
  2531. }
  2532. BOOST_FOREACH(const JsonNode &n, duelData["obstacles"].Vector())
  2533. {
  2534. auto oi = make_shared<CObstacleInstance>();
  2535. if(n.getType() == JsonNode::DATA_VECTOR)
  2536. {
  2537. oi->ID = n.Vector()[0].Float();
  2538. oi->pos = n.Vector()[1].Float();
  2539. }
  2540. else
  2541. {
  2542. assert(n.getType() == JsonNode::DATA_FLOAT);
  2543. oi->ID = 21;
  2544. oi->pos = n.Float();
  2545. }
  2546. oi->uniqueID = ret.obstacles.size();
  2547. ret.obstacles.push_back(oi);
  2548. }
  2549. BOOST_FOREACH(const JsonNode &n, duelData["creatures"].Vector())
  2550. {
  2551. CusomCreature cc;
  2552. cc.id = n["id"].Float();
  2553. #define retreive(name) \
  2554. if(n[ #name ].getType() == JsonNode::DATA_FLOAT)\
  2555. cc.name = n[ #name ].Float(); \
  2556. else \
  2557. cc.name = -1;
  2558. retreive(attack);
  2559. retreive(defense);
  2560. retreive(HP);
  2561. retreive(dmg);
  2562. retreive(shoots);
  2563. retreive(speed);
  2564. ret.creatures.push_back(cc);
  2565. }
  2566. return ret;
  2567. }
  2568. TeamState::TeamState()
  2569. {
  2570. setNodeType(TEAM);
  2571. }
  2572. void CPathfinder::initializeGraph()
  2573. {
  2574. CGPathNode ***graph = out.nodes;
  2575. for(size_t i=0; i < out.sizes.x; ++i)
  2576. {
  2577. for(size_t j=0; j < out.sizes.y; ++j)
  2578. {
  2579. for(size_t k=0; k < out.sizes.z; ++k)
  2580. {
  2581. curPos = int3(i,j,k);
  2582. const TerrainTile *tinfo = &gs->map->terrain[i][j][k];
  2583. CGPathNode &node = graph[i][j][k];
  2584. node.accessible = evaluateAccessibility(tinfo);
  2585. node.turns = 0xff;
  2586. node.moveRemains = 0;
  2587. node.coord.x = i;
  2588. node.coord.y = j;
  2589. node.coord.z = k;
  2590. node.land = tinfo->tertype != TerrainTile::water;
  2591. node.theNodeBefore = NULL;
  2592. }
  2593. }
  2594. }
  2595. }
  2596. void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*= -1*/)
  2597. {
  2598. assert(hero);
  2599. assert(hero == getHero(hero->id));
  2600. if(src.x < 0)
  2601. src = hero->getPosition(false);
  2602. if(movement < 0)
  2603. movement = hero->movement;
  2604. out.hero = hero;
  2605. out.hpos = src;
  2606. if(!gs->map->isInTheMap(src)/* || !gs->map->isInTheMap(dest)*/) //check input
  2607. {
  2608. tlog1 << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...\n";
  2609. return;
  2610. }
  2611. initializeGraph();
  2612. //initial tile - set cost on 0 and add to the queue
  2613. CGPathNode &initialNode = *getNode(src);
  2614. initialNode.turns = 0;
  2615. initialNode.moveRemains = movement;
  2616. mq.push_back(&initialNode);
  2617. std::vector<int3> neighbours;
  2618. neighbours.reserve(16);
  2619. while(!mq.empty())
  2620. {
  2621. cp = mq.front();
  2622. mq.pop_front();
  2623. const int3 sourceGuardPosition = guardingCreaturePosition(cp->coord);
  2624. bool guardedSource = (sourceGuardPosition != int3(-1, -1, -1) && cp->coord != src);
  2625. ct = &gs->map->getTile(cp->coord);
  2626. int movement = cp->moveRemains, turn = cp->turns;
  2627. if(!movement)
  2628. {
  2629. movement = hero->maxMovePoints(cp->land);
  2630. turn++;
  2631. }
  2632. //add accessible neighbouring nodes to the queue
  2633. neighbours.clear();
  2634. //handling subterranean gate => it's exit is the only neighbour
  2635. bool subterraneanEntry = (ct->topVisitableID() == GameConstants::SUBTERRANEAN_GATE_TYPE && useSubterraneanGates);
  2636. if(subterraneanEntry)
  2637. {
  2638. //try finding the exit gate
  2639. if(const CGObjectInstance *outGate = getObj(CGTeleport::getMatchingGate(ct->visitableObjects.back()->id), false))
  2640. {
  2641. const int3 outPos = outGate->visitablePos();
  2642. //gs->getNeighbours(*getTile(outPos), outPos, neighbours, boost::logic::indeterminate, !cp->land);
  2643. neighbours.push_back(outPos);
  2644. }
  2645. else
  2646. {
  2647. //gate with no exit (blocked) -> do nothing with this node
  2648. continue;
  2649. }
  2650. }
  2651. gs->getNeighbours(*ct, cp->coord, neighbours, boost::logic::indeterminate, !cp->land);
  2652. for(ui32 i=0; i < neighbours.size(); i++)
  2653. {
  2654. const int3 &n = neighbours[i]; //current neighbor
  2655. dp = getNode(n);
  2656. dt = &gs->map->getTile(n);
  2657. destTopVisObjID = dt->topVisitableID();
  2658. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  2659. int turnAtNextTile = turn;
  2660. const bool destIsGuardian = sourceGuardPosition == n;
  2661. if(!goodForLandSeaTransition())
  2662. continue;
  2663. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED )
  2664. continue;
  2665. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  2666. if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableID() == GameConstants::BOATI_TYPE)
  2667. guardedSource = false;
  2668. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
  2669. //special case -> moving from src Subterranean gate to dest gate -> it's free
  2670. if(subterraneanEntry && destTopVisObjID == GameConstants::SUBTERRANEAN_GATE_TYPE && cp->coord.z != dp->coord.z)
  2671. cost = 0;
  2672. int remains = movement - cost;
  2673. if(useEmbarkCost)
  2674. {
  2675. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  2676. cost = movement - remains;
  2677. }
  2678. if(remains < 0)
  2679. {
  2680. //occurs rarely, when hero with low movepoints tries to leave the road
  2681. turnAtNextTile++;
  2682. int moveAtNextTile = hero->maxMovePoints(cp->land);
  2683. cost = gs->getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2684. remains = moveAtNextTile - cost;
  2685. }
  2686. if((dp->turns==0xff //we haven't been here before
  2687. || dp->turns > turnAtNextTile
  2688. || (dp->turns >= turnAtNextTile && dp->moveRemains < remains)) //this route is faster
  2689. && (!guardedSource || destIsGuardian)) // Can step into tile of guard
  2690. {
  2691. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  2692. dp->moveRemains = remains;
  2693. dp->turns = turnAtNextTile;
  2694. dp->theNodeBefore = cp;
  2695. const bool guardedDst = guardingCreaturePosition(dp->coord) != int3(-1, -1, -1)
  2696. && dp->accessible == CGPathNode::BLOCKVIS;
  2697. if (dp->accessible == CGPathNode::ACCESSIBLE
  2698. || (useEmbarkCost && allowEmbarkAndDisembark)
  2699. || destTopVisObjID == GameConstants::SUBTERRANEAN_GATE_TYPE
  2700. || (guardedDst && !guardedSource)) // Can step into a hostile tile once.
  2701. {
  2702. mq.push_back(dp);
  2703. }
  2704. }
  2705. } //neighbours loop
  2706. } //queue loop
  2707. out.isValid = true;
  2708. }
  2709. CGPathNode *CPathfinder::getNode(const int3 &coord)
  2710. {
  2711. return &out.nodes[coord.x][coord.y][coord.z];
  2712. }
  2713. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  2714. {
  2715. return gs->checkForVisitableDir(a, b) && gs->checkForVisitableDir(b, a);
  2716. }
  2717. bool CPathfinder::canStepOntoDst() const
  2718. {
  2719. //TODO remove
  2720. assert(0);
  2721. return false;
  2722. }
  2723. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const TerrainTile *tinfo) const
  2724. {
  2725. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  2726. if(tinfo->tertype == TerrainTile::rock || !FoW[curPos.x][curPos.y][curPos.z])
  2727. return CGPathNode::BLOCKED;
  2728. if(tinfo->visitable)
  2729. {
  2730. if(tinfo->visitableObjects.front()->ID == 80 && tinfo->visitableObjects.back()->ID == GameConstants::HEROI_TYPE && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner) //non-owned hero stands on Sanctuary
  2731. {
  2732. return CGPathNode::BLOCKED;
  2733. }
  2734. else
  2735. {
  2736. BOOST_FOREACH(const CGObjectInstance *obj, tinfo->visitableObjects)
  2737. {
  2738. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  2739. {
  2740. ret = CGPathNode::ACCESSIBLE;
  2741. }
  2742. else if(obj->blockVisit)
  2743. {
  2744. return CGPathNode::BLOCKVIS;
  2745. }
  2746. else if(obj->ID != GameConstants::EVENTI_TYPE) //pathfinder should ignore placed events
  2747. {
  2748. ret = CGPathNode::VISITABLE;
  2749. }
  2750. }
  2751. }
  2752. }
  2753. else if (gs->map->isInTheMap(guardingCreaturePosition(curPos))
  2754. && !tinfo->blocked)
  2755. {
  2756. // Monster close by; blocked visit for battle.
  2757. return CGPathNode::BLOCKVIS;
  2758. }
  2759. return ret;
  2760. }
  2761. bool CPathfinder::goodForLandSeaTransition()
  2762. {
  2763. if(cp->land != dp->land) //hero can traverse land<->sea only in special circumstances
  2764. {
  2765. if(cp->land) //from land to sea -> embark or assault hero on boat
  2766. {
  2767. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  2768. return false;
  2769. if(destTopVisObjID != GameConstants::HEROI_TYPE && destTopVisObjID != GameConstants::BOATI_TYPE) //only boat or hero can be accessed from land
  2770. return false;
  2771. if(destTopVisObjID == GameConstants::BOATI_TYPE)
  2772. useEmbarkCost = 1;
  2773. }
  2774. else //disembark
  2775. {
  2776. //can disembark only on coastal tiles
  2777. if(!dt->isCoastal())
  2778. return false;
  2779. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  2780. if( (dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  2781. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  2782. return false;;
  2783. useEmbarkCost = 2;
  2784. }
  2785. }
  2786. return true;
  2787. }
  2788. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero) : CGameInfoCallback(_gs, -1), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap)
  2789. {
  2790. useSubterraneanGates = true;
  2791. allowEmbarkAndDisembark = true;
  2792. }