CGameState.cpp 92 KB

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