CGameState.cpp 87 KB

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