CGameState.cpp 92 KB

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