CGameState.cpp 87 KB

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