CGameState.cpp 93 KB

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