2
0

CGameState.cpp 93 KB

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