CGameState.cpp 87 KB

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