CGameState.cpp 96 KB

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