CGameState.cpp 85 KB

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