CGameState.cpp 88 KB

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