CGameState.cpp 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534
  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. {
  318. auto nobj = new CGHeroInstance();
  319. nobj->pos = pos;
  320. nobj->tempOwner = owner;
  321. nobj->subID = subid;
  322. //nobj->initHero(ran);
  323. return nobj;
  324. }
  325. case Obj::TOWN:
  326. nobj = new CGTownInstance;
  327. break;
  328. default: //rest of objects
  329. nobj = new CGObjectInstance;
  330. nobj->defInfo = id.toDefObjInfo()[subid];
  331. break;
  332. }
  333. nobj->ID = id;
  334. nobj->subID = subid;
  335. if(!nobj->defInfo)
  336. logGlobal->warnStream() <<"No def declaration for " <<id <<" "<<subid;
  337. nobj->pos = pos;
  338. //nobj->state = nullptr;//new CLuaObjectScript();
  339. nobj->tempOwner = owner;
  340. nobj->defInfo->id = id;
  341. nobj->defInfo->subid = subid;
  342. //assigning defhandler
  343. if(nobj->ID==Obj::HERO || nobj->ID==Obj::TOWN)
  344. return nobj;
  345. nobj->defInfo = id.toDefObjInfo()[subid];
  346. return nobj;
  347. }
  348. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, PlayerColor player, const CTown *town, std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass /*= nullptr*/) const
  349. {
  350. CGHeroInstance *ret = nullptr;
  351. if(player>=PlayerColor::PLAYER_LIMIT)
  352. {
  353. logGlobal->errorStream() << "Cannot pick hero for " << town->faction->index << ". Wrong owner!";
  354. return nullptr;
  355. }
  356. std::vector<CGHeroInstance *> pool;
  357. if(native)
  358. {
  359. for(auto & elem : available)
  360. {
  361. if(pavailable.find(elem.first)->second & 1<<player.getNum()
  362. && elem.second->type->heroClass->faction == town->faction->index)
  363. {
  364. pool.push_back(elem.second); //get all available heroes
  365. }
  366. }
  367. if(!pool.size())
  368. {
  369. logGlobal->errorStream() << "Cannot pick native hero for " << player << ". Picking any...";
  370. return pickHeroFor(false, player, town, available);
  371. }
  372. else
  373. {
  374. ret = pool[rand()%pool.size()];
  375. }
  376. }
  377. else
  378. {
  379. int sum=0, r;
  380. for(auto & elem : available)
  381. {
  382. if (pavailable.find(elem.first)->second & (1<<player.getNum()) && // hero is available
  383. ( !bannedClass || elem.second->type->heroClass != bannedClass) ) // and his class is not same as other hero
  384. {
  385. pool.push_back(elem.second);
  386. sum += elem.second->type->heroClass->selectionProbability[town->faction->index]; //total weight
  387. }
  388. }
  389. if(!pool.size() || sum == 0)
  390. {
  391. logGlobal->errorStream() << "There are no heroes available for player " << player<<"!";
  392. return nullptr;
  393. }
  394. r = rand()%sum;
  395. for (auto & elem : pool)
  396. {
  397. r -= elem->type->heroClass->selectionProbability[town->faction->index];
  398. if(r < 0)
  399. {
  400. ret = elem;
  401. break;
  402. }
  403. }
  404. if(!ret)
  405. ret = pool.back();
  406. }
  407. available.erase(ret->subID);
  408. return ret;
  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. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  588. t->town = VLC->townh->factions[t->subID]->town;
  589. if(t->hasCapitol())
  590. t->defInfo = VLC->dobjinfo->capitols[t->subID];
  591. else if(t->hasFort())
  592. t->defInfo = VLC->dobjinfo->gobjs[Obj::TOWN][t->subID];
  593. else
  594. t->defInfo = VLC->dobjinfo->villages[t->subID];
  595. }
  596. return;
  597. }
  598. else if(ran.first==Obj::HERO)//special code for hero
  599. {
  600. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  601. if(!h) {logGlobal->warnStream()<<"Wrong random hero at "<<cur->pos; return;}
  602. cur->ID = ran.first;
  603. cur->subID = ran.second;
  604. h->type = VLC->heroh->heroes[ran.second];
  605. h->portrait = h->type->imageIndex;
  606. h->randomizeArmy(h->type->heroClass->faction);
  607. map->heroesOnMap.push_back(h);
  608. return; //TODO: maybe we should do something with definfo?
  609. }
  610. else if(ran.first==Obj::TOWN)//special code for town
  611. {
  612. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  613. if(!t) {logGlobal->warnStream()<<"Wrong random town at "<<cur->pos; return;}
  614. cur->ID = ran.first;
  615. cur->subID = ran.second;
  616. //FIXME: copy-pasted from above
  617. t->town = VLC->townh->factions[t->subID]->town;
  618. if(t->hasCapitol())
  619. t->defInfo = VLC->dobjinfo->capitols[t->subID];
  620. else if(t->hasFort())
  621. t->defInfo = VLC->dobjinfo->gobjs[Obj::TOWN][t->subID];
  622. else
  623. t->defInfo = VLC->dobjinfo->villages[t->subID];
  624. t->randomizeArmy(t->subID);
  625. map->towns.push_back(t);
  626. return;
  627. }
  628. //we have to replace normal random object
  629. cur->ID = ran.first;
  630. cur->subID = ran.second;
  631. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  632. map->customDefs.push_back(cur->defInfo = ran.first.toDefObjInfo()[ran.second]);
  633. if(!cur->defInfo)
  634. {
  635. logGlobal->errorStream()<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID;
  636. return;
  637. }
  638. map->addBlockVisTiles(cur);
  639. }
  640. int CGameState::getDate(Date::EDateType mode) const
  641. {
  642. int temp;
  643. switch (mode)
  644. {
  645. case Date::DAY:
  646. return day;
  647. case Date::DAY_OF_WEEK: //day of week
  648. temp = (day)%7; // 1 - Monday, 7 - Sunday
  649. return temp ? temp : 7;
  650. case Date::WEEK: //current week
  651. temp = ((day-1)/7)+1;
  652. if (!(temp%4))
  653. return 4;
  654. else
  655. return (temp%4);
  656. case Date::MONTH: //current month
  657. return ((day-1)/28)+1;
  658. case Date::DAY_OF_MONTH: //day of month
  659. temp = (day)%28;
  660. if (temp)
  661. return temp;
  662. else return 28;
  663. }
  664. return 0;
  665. }
  666. CGameState::CGameState()
  667. {
  668. gs = this;
  669. mx = new boost::shared_mutex();
  670. applierGs = new CApplier<CBaseForGSApply>;
  671. registerTypes2(*applierGs);
  672. objCaller = new CObjectCallersHandler;
  673. globalEffects.setDescription("Global effects");
  674. }
  675. CGameState::~CGameState()
  676. {
  677. //delete mx;//TODO: crash on Linux (mutex must be unlocked before destruction)
  678. map.dellNull();
  679. curB.dellNull();
  680. //delete scenarioOps; //TODO: fix for loading ind delete
  681. //delete initialOpts;
  682. delete applierGs;
  683. delete objCaller;
  684. for(auto ptr : hpool.heroesPool) // clean hero pool
  685. ptr.second.dellNull();
  686. }
  687. BattleInfo * CGameState::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town)
  688. {
  689. const TerrainTile &t = map->getTile(tile);
  690. ETerrainType terrain = t.terType;
  691. if(t.isCoastal() && !t.isWater())
  692. terrain = ETerrainType::SAND;
  693. BFieldType terType = battleGetBattlefieldType(tile);
  694. return BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  695. }
  696. void CGameState::init(StartInfo * si)
  697. {
  698. logGlobal->infoStream() << "\tUsing random seed: "<< si->seedToBeUsed;
  699. ran.seed((boost::int32_t)si->seedToBeUsed);
  700. scenarioOps = new StartInfo(*si);
  701. initialOpts = new StartInfo(*si);
  702. si = nullptr;
  703. switch(scenarioOps->mode)
  704. {
  705. case StartInfo::NEW_GAME:
  706. initNewGame();
  707. break;
  708. case StartInfo::CAMPAIGN:
  709. initCampaign();
  710. break;
  711. case StartInfo::DUEL:
  712. initDuel();
  713. return;
  714. default:
  715. logGlobal->errorStream() << "Wrong mode: " << (int)scenarioOps->mode;
  716. return;
  717. }
  718. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  719. logGlobal->infoStream() << "Map loaded!";
  720. checkMapChecksum();
  721. day = 0;
  722. logGlobal->debugStream() << "Initialization:";
  723. initPlayerStates();
  724. placeCampaignHeroes();
  725. initGrailPosition();
  726. initRandomFactionsForPlayers();
  727. randomizeMapObjects();
  728. placeStartingHeroes();
  729. initStartingResources();
  730. initHeroes();
  731. initFogOfWar();
  732. initStartingBonus();
  733. initTowns();
  734. initMapObjects();
  735. buildBonusSystemTree();
  736. initVisitingAndGarrisonedHeroes();
  737. logGlobal->debugStream() << "\tChecking objectives";
  738. map->checkForObjectives(); //needs to be run when all objects are properly placed
  739. int seedAfterInit = ran();
  740. logGlobal->infoStream() << "Seed after init is " << seedAfterInit << " (before was " << scenarioOps->seedToBeUsed << ")";
  741. if(scenarioOps->seedPostInit > 0)
  742. {
  743. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  744. assert(scenarioOps->seedPostInit == seedAfterInit);
  745. }
  746. else
  747. {
  748. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  749. }
  750. }
  751. void CGameState::initNewGame()
  752. {
  753. if(scenarioOps->createRandomMap())
  754. {
  755. logGlobal->infoStream() << "Create random map.";
  756. CStopWatch sw;
  757. // Gen map
  758. CMapGenerator mapGenerator;
  759. map = mapGenerator.generate(scenarioOps->mapGenOptions.get(), scenarioOps->seedToBeUsed).release();
  760. // Update starting options
  761. for(int i = 0; i < map->players.size(); ++i)
  762. {
  763. const auto & playerInfo = map->players[i];
  764. if(playerInfo.canAnyonePlay())
  765. {
  766. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  767. playerSettings.compOnly = !playerInfo.canHumanPlay;
  768. playerSettings.team = playerInfo.team;
  769. playerSettings.castle = playerInfo.defaultCastle();
  770. if(playerSettings.playerID == PlayerSettings::PLAYER_AI && playerSettings.name.empty())
  771. {
  772. playerSettings.name = VLC->generaltexth->allTexts[468];
  773. }
  774. playerSettings.color = PlayerColor(i);
  775. }
  776. else
  777. {
  778. scenarioOps->playerInfos.erase(PlayerColor(i));
  779. }
  780. }
  781. logGlobal->infoStream() << boost::format("Generated random map in %i ms.") % sw.getDiff();
  782. }
  783. else
  784. {
  785. logGlobal->infoStream() << "Open map file: " << scenarioOps->mapname;
  786. map = CMapService::loadMap(scenarioOps->mapname).release();
  787. }
  788. }
  789. void CGameState::initCampaign()
  790. {
  791. logGlobal->infoStream() << "Open campaign map file: " << scenarioOps->campState->currentMap;
  792. auto campaign = scenarioOps->campState;
  793. assert(vstd::contains(campaign->camp->mapPieces, *scenarioOps->campState->currentMap));
  794. std::string & mapContent = campaign->camp->mapPieces[*scenarioOps->campState->currentMap];
  795. auto buffer = reinterpret_cast<const ui8 *>(mapContent.data());
  796. map = CMapService::loadMap(buffer, mapContent.size()).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 campaignScenario = getCampaignScenarioForCrossoverHeroes();
  1015. if(campaignScenario)
  1016. {
  1017. logGlobal->debugStream() << "\tPrepare crossover heroes";
  1018. auto crossoverHeroes = prepareCrossoverHeroes(campaignScenario);
  1019. logGlobal->debugStream() << "\tGenerate list of hero placeholders";
  1020. const auto campaignHeroReplacements = generateCampaignHeroesToReplace(crossoverHeroes);
  1021. // remove same heroes on the map which will be added through crossover heroes
  1022. /*for(auto & campaignHeroReplacement : campaignHeroReplacement)
  1023. {
  1024. campaignHeroReplacement.first->subID
  1025. }*/
  1026. logGlobal->debugStream() << "\tReplace placeholders with heroes";
  1027. replaceHeroesPlaceholders(campaignHeroReplacements);
  1028. }
  1029. }
  1030. }
  1031. void CGameState::placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos)
  1032. {
  1033. townPos.x += 1;
  1034. CGHeroInstance * hero = static_cast<CGHeroInstance*>(createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor));
  1035. hero->initHero();
  1036. map->getEditManager()->insertObject(hero, townPos);
  1037. }
  1038. const CCampaignScenario * CGameState::getCampaignScenarioForCrossoverHeroes() const
  1039. {
  1040. const CCampaignScenario * campaignScenario = nullptr;
  1041. auto campaignState = scenarioOps->campState;
  1042. auto bonus = campaignState->getBonusForCurrentMap();
  1043. if (bonus->type == CScenarioTravel::STravelBonus::HEROES_FROM_PREVIOUS_SCENARIO)
  1044. {
  1045. campaignScenario = &campaignState->camp->scenarios[bonus->info2];
  1046. }
  1047. else
  1048. {
  1049. if(!campaignState->mapsConquered.empty())
  1050. {
  1051. campaignScenario = &campaignState->camp->scenarios[campaignState->mapsConquered.back()];
  1052. }
  1053. }
  1054. return campaignScenario;
  1055. }
  1056. std::vector<CGHeroInstance *> CGameState::prepareCrossoverHeroes(const CCampaignScenario * campaignScenario)
  1057. {
  1058. auto crossoverHeroes = campaignScenario->crossoverHeroes; //TODO check if hero instances need to be copied
  1059. const auto & travelOptions = campaignScenario->travelOptions;
  1060. if (!(travelOptions.whatHeroKeeps & 1))
  1061. {
  1062. //trimming experience
  1063. for(CGHeroInstance * cgh : crossoverHeroes)
  1064. {
  1065. cgh->initExp();
  1066. }
  1067. }
  1068. if (!(travelOptions.whatHeroKeeps & 2))
  1069. {
  1070. //trimming prim skills
  1071. for(CGHeroInstance * cgh : crossoverHeroes)
  1072. {
  1073. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1074. {
  1075. auto sel = Selector::type(Bonus::PRIMARY_SKILL)
  1076. .And(Selector::subtype(g))
  1077. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL));
  1078. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  1079. }
  1080. }
  1081. }
  1082. if (!(travelOptions.whatHeroKeeps & 4))
  1083. {
  1084. //trimming sec skills
  1085. for(CGHeroInstance * cgh : crossoverHeroes)
  1086. {
  1087. cgh->secSkills = cgh->type->secSkillsInit;
  1088. }
  1089. }
  1090. if (!(travelOptions.whatHeroKeeps & 8))
  1091. {
  1092. //trimming spells
  1093. for(CGHeroInstance * cgh : crossoverHeroes)
  1094. {
  1095. cgh->spells.clear();
  1096. cgh->eraseArtSlot(ArtifactPosition(ArtifactPosition::SPELLBOOK)); // spellbook will also be removed
  1097. }
  1098. }
  1099. if (!(travelOptions.whatHeroKeeps & 16))
  1100. {
  1101. //trimming artifacts
  1102. for(CGHeroInstance * hero : crossoverHeroes)
  1103. {
  1104. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  1105. for (size_t i=0; i<totalArts; i++ )
  1106. {
  1107. auto artifactPosition = ArtifactPosition(i);
  1108. if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
  1109. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  1110. if(!info) continue;
  1111. const CArtifactInstance *art = info->artifact;
  1112. if(!art) continue;
  1113. int id = art->artType->id;
  1114. assert( 8*18 > id );//number of arts that fits into h3m format
  1115. bool takeable = travelOptions.artifsKeptByHero[id / 8] & ( 1 << (id%8) );
  1116. if(!takeable) hero->eraseArtSlot(ArtifactPosition(i));
  1117. }
  1118. }
  1119. }
  1120. //trimming creatures
  1121. for(CGHeroInstance * cgh : crossoverHeroes)
  1122. {
  1123. vstd::erase_if(cgh->stacks, [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  1124. {
  1125. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  1126. return !(travelOptions.monstersKeptByHero[crid / 8] & (1 << (crid % 8)) );
  1127. });
  1128. }
  1129. return std::move(crossoverHeroes);
  1130. }
  1131. void CGameState::placeStartingHeroes()
  1132. {
  1133. logGlobal->debugStream() << "\tGiving starting hero";
  1134. for(auto & playerSettingPair : scenarioOps->playerInfos)
  1135. {
  1136. auto playerColor = playerSettingPair.first;
  1137. auto & playerInfo = map->players[playerColor.getNum()];
  1138. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  1139. {
  1140. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  1141. if(scenarioOps->campState)
  1142. {
  1143. if(auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap())
  1144. {
  1145. if(campaignBonus->type == CScenarioTravel::STravelBonus::HERO && playerColor == PlayerColor(campaignBonus->info1)) continue;
  1146. }
  1147. }
  1148. int heroTypeId = pickNextHeroType(playerColor);
  1149. if(playerSettingPair.second.hero == -1) playerSettingPair.second.hero = heroTypeId;
  1150. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  1151. }
  1152. }
  1153. }
  1154. void CGameState::initStartingResources()
  1155. {
  1156. logGlobal->debugStream() << "\tSetting up resources";
  1157. const JsonNode config(ResourceID("config/startres.json"));
  1158. const JsonVector &vector = config["difficulty"].Vector();
  1159. const JsonNode &level = vector[scenarioOps->difficulty];
  1160. TResources startresAI(level["ai"]);
  1161. TResources startresHuman(level["human"]);
  1162. for (auto & elem : players)
  1163. {
  1164. PlayerState &p = elem.second;
  1165. if (p.human)
  1166. p.resources = startresHuman;
  1167. else
  1168. p.resources = startresAI;
  1169. }
  1170. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  1171. {
  1172. std::vector<const PlayerSettings *> ret;
  1173. for(auto it = scenarioOps->playerInfos.cbegin();
  1174. it != scenarioOps->playerInfos.cend(); ++it)
  1175. {
  1176. if(it->second.playerID != PlayerSettings::PLAYER_AI)
  1177. ret.push_back(&it->second);
  1178. }
  1179. return ret;
  1180. };
  1181. //give start resource bonus in case of campaign
  1182. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1183. {
  1184. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1185. if(chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1186. {
  1187. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1188. for(const PlayerSettings *ps : people)
  1189. {
  1190. std::vector<int> res; //resources we will give
  1191. switch (chosenBonus->info1)
  1192. {
  1193. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1194. res.push_back(chosenBonus->info1);
  1195. break;
  1196. case 0xFD: //wood+ore
  1197. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1198. break;
  1199. case 0xFE: //rare
  1200. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1201. break;
  1202. default:
  1203. assert(0);
  1204. break;
  1205. }
  1206. //increasing resource quantity
  1207. for (auto & re : res)
  1208. {
  1209. players[ps->color].resources[re] += chosenBonus->info2;
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }
  1215. void CGameState::initHeroes()
  1216. {
  1217. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1218. {
  1219. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  1220. {
  1221. logGlobal->warnStream() << "Warning - hero with uninitialized owner!";
  1222. continue;
  1223. }
  1224. hero->initHero();
  1225. getPlayer(hero->getOwner())->heroes.push_back(hero);
  1226. map->allHeroes[hero->type->ID.getNum()] = hero;
  1227. }
  1228. for(auto obj : map->objects) //prisons
  1229. {
  1230. if(obj && obj->ID == Obj::PRISON)
  1231. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  1232. }
  1233. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  1234. for(auto ph : map->predefinedHeroes)
  1235. {
  1236. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  1237. continue;
  1238. ph->initHero();
  1239. hpool.heroesPool[ph->subID] = ph;
  1240. hpool.pavailable[ph->subID] = 0xff;
  1241. heroesToCreate.erase(ph->type->ID);
  1242. map->allHeroes[ph->subID] = ph;
  1243. }
  1244. for(HeroTypeID htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  1245. {
  1246. auto vhi = new CGHeroInstance();
  1247. vhi->initHero(htype);
  1248. int typeID = htype.getNum();
  1249. map->allHeroes[typeID] = vhi;
  1250. hpool.heroesPool[typeID] = vhi;
  1251. hpool.pavailable[typeID] = 0xff;
  1252. }
  1253. for(auto & elem : map->disposedHeroes)
  1254. {
  1255. hpool.pavailable[elem.heroId] = elem.players;
  1256. }
  1257. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1258. {
  1259. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1260. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1261. {
  1262. //find human player
  1263. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  1264. for (auto & elem : players)
  1265. {
  1266. if(elem.second.human)
  1267. {
  1268. humanPlayer = elem.first;
  1269. break;
  1270. }
  1271. }
  1272. assert(humanPlayer != PlayerColor::NEUTRAL);
  1273. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1274. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1275. {
  1276. int maxB = -1;
  1277. for (int b=0; b<heroes.size(); ++b)
  1278. {
  1279. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1280. {
  1281. maxB = b;
  1282. }
  1283. }
  1284. if(maxB < 0)
  1285. logGlobal->warnStream() << "Warning - cannot give bonus to hero cause there are no heroes!";
  1286. else
  1287. giveCampaignBonusToHero(heroes[maxB]);
  1288. }
  1289. else //specific hero
  1290. {
  1291. for (auto & heroe : heroes)
  1292. {
  1293. if (heroe->subID == chosenBonus->info1)
  1294. {
  1295. giveCampaignBonusToHero(heroe);
  1296. break;
  1297. }
  1298. }
  1299. }
  1300. }
  1301. }
  1302. }
  1303. void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero)
  1304. {
  1305. const boost::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
  1306. if(!curBonus)
  1307. return;
  1308. if(curBonus->isBonusForHero())
  1309. {
  1310. //apply bonus
  1311. switch (curBonus->type)
  1312. {
  1313. case CScenarioTravel::STravelBonus::SPELL:
  1314. hero->spells.insert(SpellID(curBonus->info2));
  1315. break;
  1316. case CScenarioTravel::STravelBonus::MONSTER:
  1317. {
  1318. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  1319. {
  1320. if(hero->slotEmpty(SlotID(i)))
  1321. {
  1322. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  1323. break;
  1324. }
  1325. }
  1326. }
  1327. break;
  1328. case CScenarioTravel::STravelBonus::ARTIFACT:
  1329. gs->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2));
  1330. break;
  1331. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  1332. {
  1333. CArtifactInstance * scroll = CArtifactInstance::createScroll(SpellID(curBonus->info2).toSpell());
  1334. scroll->putAt(ArtifactLocation(hero, scroll->firstAvailableSlot(hero)));
  1335. }
  1336. break;
  1337. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  1338. {
  1339. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus->info2);
  1340. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1341. {
  1342. int val = ptr[g];
  1343. if (val == 0)
  1344. {
  1345. continue;
  1346. }
  1347. auto bb = new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, *scenarioOps->campState->currentMap, g);
  1348. hero->addNewBonus(bb);
  1349. }
  1350. }
  1351. break;
  1352. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  1353. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  1354. break;
  1355. }
  1356. }
  1357. }
  1358. void CGameState::initFogOfWar()
  1359. {
  1360. logGlobal->debugStream() << "\tFog of war"; //FIXME: should be initialized after all bonuses are set
  1361. for(auto & elem : teams)
  1362. {
  1363. elem.second.fogOfWarMap.resize(map->width);
  1364. for(int g=0; g<map->width; ++g)
  1365. elem.second.fogOfWarMap[g].resize(map->height);
  1366. for(int g=-0; g<map->width; ++g)
  1367. for(int h=0; h<map->height; ++h)
  1368. elem.second.fogOfWarMap[g][h].resize(map->twoLevel ? 2 : 1, 0);
  1369. for(int g=0; g<map->width; ++g)
  1370. for(int h=0; h<map->height; ++h)
  1371. for(int v = 0; v < (map->twoLevel ? 2 : 1); ++v)
  1372. elem.second.fogOfWarMap[g][h][v] = 0;
  1373. for(CGObjectInstance *obj : map->objects)
  1374. {
  1375. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  1376. std::unordered_set<int3, ShashInt3> tiles;
  1377. obj->getSightTiles(tiles);
  1378. for(int3 tile : tiles)
  1379. {
  1380. elem.second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1381. }
  1382. }
  1383. }
  1384. }
  1385. void CGameState::initStartingBonus()
  1386. {
  1387. logGlobal->debugStream() << "\tStarting bonuses";
  1388. for(auto & elem : players)
  1389. {
  1390. //starting bonus
  1391. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  1392. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(ran()%3);
  1393. switch(scenarioOps->playerInfos[elem.first].bonus)
  1394. {
  1395. case PlayerSettings::GOLD:
  1396. elem.second.resources[Res::GOLD] += 500 + (ran()%6)*100;
  1397. break;
  1398. case PlayerSettings::RESOURCE:
  1399. {
  1400. int res = VLC->townh->factions[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  1401. if(res == Res::WOOD_AND_ORE)
  1402. {
  1403. elem.second.resources[Res::WOOD] += 5 + ran()%6;
  1404. elem.second.resources[Res::ORE] += 5 + ran()%6;
  1405. }
  1406. else
  1407. {
  1408. elem.second.resources[res] += 3 + ran()%4;
  1409. }
  1410. break;
  1411. }
  1412. case PlayerSettings::ARTIFACT:
  1413. {
  1414. if(!elem.second.heroes.size())
  1415. {
  1416. logGlobal->debugStream() << "Cannot give starting artifact - no heroes!";
  1417. break;
  1418. }
  1419. CArtifact *toGive;
  1420. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1421. CGHeroInstance *hero = elem.second.heroes[0];
  1422. giveHeroArtifact(hero, toGive->id);
  1423. }
  1424. break;
  1425. }
  1426. }
  1427. }
  1428. void CGameState::initTowns()
  1429. {
  1430. logGlobal->debugStream() << "\tTowns";
  1431. //campaign bonuses for towns
  1432. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1433. {
  1434. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1435. if (chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1436. {
  1437. for (int g=0; g<map->towns.size(); ++g)
  1438. {
  1439. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1440. if (owner)
  1441. {
  1442. PlayerInfo & pi = map->players[owner->color.getNum()];
  1443. if (owner->human && //human-owned
  1444. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1445. {
  1446. map->towns[g]->builtBuildings.insert(
  1447. CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->subID, map->towns[g]->builtBuildings));
  1448. break;
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. CGTownInstance::universitySkills.clear();
  1455. for ( int i=0; i<4; i++)
  1456. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1457. for (auto & elem : map->towns)
  1458. {
  1459. CGTownInstance * vti =(elem);
  1460. if(!vti->town)
  1461. vti->town = VLC->townh->factions[vti->subID]->town;
  1462. if (vti->name.length()==0) // if town hasn't name we draw it
  1463. vti->name = vti->town->names[ran()%vti->town->names.size()];
  1464. //init buildings
  1465. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  1466. {
  1467. vti->builtBuildings.erase(BuildingID::DEFAULT);
  1468. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1469. vti->builtBuildings.insert(BuildingID::TAVERN);
  1470. vti->builtBuildings.insert(BuildingID::DWELL_FIRST);
  1471. if(ran()%2)
  1472. vti->builtBuildings.insert(BuildingID::DWELL_LVL_2);
  1473. }
  1474. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  1475. vstd::erase_if(vti->builtBuildings, [vti](BuildingID bid){
  1476. return !vti->town->buildings.count(bid) || !vti->town->buildings.at(bid); });
  1477. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  1478. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1479. //init hordes
  1480. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1481. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1482. {
  1483. vti->builtBuildings.erase(BuildingID(-31-i));//remove old ID
  1484. if (vti->town->hordeLvl.at(0) == i)//if town first horde is this one
  1485. {
  1486. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  1487. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))//if we have upgraded dwelling as well
  1488. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  1489. }
  1490. if (vti->town->hordeLvl.at(1) == i)//if town second horde is this one
  1491. {
  1492. vti->builtBuildings.insert(BuildingID::HORDE_2);
  1493. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))
  1494. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  1495. }
  1496. }
  1497. //Early check for #1444-like problems
  1498. for(auto building : vti->builtBuildings)
  1499. {
  1500. assert(vti->town->buildings.at(building) != nullptr);
  1501. UNUSED(building);
  1502. }
  1503. //town events
  1504. for(CCastleEvent &ev : vti->events)
  1505. {
  1506. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1507. if (vstd::contains(ev.buildings,(-31-i))) //if we have horde for this level
  1508. {
  1509. ev.buildings.erase(BuildingID(-31-i));
  1510. if (vti->town->hordeLvl.at(0) == i)
  1511. ev.buildings.insert(BuildingID::HORDE_1);
  1512. if (vti->town->hordeLvl.at(1) == i)
  1513. ev.buildings.insert(BuildingID::HORDE_2);
  1514. }
  1515. }
  1516. //init spells
  1517. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1518. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1519. {
  1520. CSpell *s = vti->obligatorySpells[z].toSpell();
  1521. vti->spells[s->level-1].push_back(s->id);
  1522. vti->possibleSpells -= s->id;
  1523. }
  1524. while(vti->possibleSpells.size())
  1525. {
  1526. ui32 total=0;
  1527. int sel = -1;
  1528. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1529. total += vti->possibleSpells[ps].toSpell()->probabilities[vti->subID];
  1530. if (total == 0) // remaining spells have 0 probability
  1531. break;
  1532. int r = ran()%total;
  1533. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1534. {
  1535. r -= vti->possibleSpells[ps].toSpell()->probabilities[vti->subID];
  1536. if(r<0)
  1537. {
  1538. sel = ps;
  1539. break;
  1540. }
  1541. }
  1542. if(sel<0)
  1543. sel=0;
  1544. CSpell *s = vti->possibleSpells[sel].toSpell();
  1545. vti->spells[s->level-1].push_back(s->id);
  1546. vti->possibleSpells -= s->id;
  1547. }
  1548. vti->possibleSpells.clear();
  1549. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1550. getPlayer(vti->getOwner())->towns.push_back(vti);
  1551. }
  1552. }
  1553. void CGameState::initMapObjects()
  1554. {
  1555. logGlobal->debugStream() << "\tObject initialization";
  1556. objCaller->preInit();
  1557. for(CGObjectInstance *obj : map->objects)
  1558. {
  1559. if(obj)
  1560. obj->initObj();
  1561. }
  1562. for(CGObjectInstance *obj : map->objects)
  1563. {
  1564. if(!obj)
  1565. continue;
  1566. switch (obj->ID)
  1567. {
  1568. case Obj::QUEST_GUARD:
  1569. case Obj::SEER_HUT:
  1570. {
  1571. auto q = static_cast<CGSeerHut*>(obj);
  1572. assert (q);
  1573. q->setObjToKill();
  1574. }
  1575. }
  1576. }
  1577. CGTeleport::postInit(); //pairing subterranean gates
  1578. }
  1579. void CGameState::initVisitingAndGarrisonedHeroes()
  1580. {
  1581. for(auto k=players.begin(); k!=players.end(); ++k)
  1582. {
  1583. if(k->first==PlayerColor::NEUTRAL)
  1584. continue;
  1585. //init visiting and garrisoned heroes
  1586. for(CGHeroInstance *h : k->second.heroes)
  1587. {
  1588. for(CGTownInstance *t : k->second.towns)
  1589. {
  1590. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1591. if(vistile == h->pos || h->pos==t->pos)
  1592. {
  1593. t->setVisitingHero(h);
  1594. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1595. {
  1596. map->removeBlockVisTiles(h);
  1597. h->pos.x -= 1;
  1598. map->addBlockVisTiles(h);
  1599. }
  1600. break;
  1601. }
  1602. }
  1603. }
  1604. }
  1605. }
  1606. BFieldType CGameState::battleGetBattlefieldType(int3 tile) const
  1607. {
  1608. if(tile==int3() && curB)
  1609. tile = curB->tile;
  1610. else if(tile==int3() && !curB)
  1611. return BFieldType::NONE;
  1612. const TerrainTile &t = map->getTile(tile);
  1613. //fight in mine -> subterranean
  1614. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1615. return BFieldType::SUBTERRANEAN;
  1616. for(auto &obj : map->objects)
  1617. {
  1618. //look only for objects covering given tile
  1619. if( !obj || obj->pos.z != tile.z
  1620. || !obj->coveringAt(tile.x - obj->pos.x, tile.y - obj->pos.y))
  1621. continue;
  1622. switch(obj->ID)
  1623. {
  1624. case Obj::CLOVER_FIELD:
  1625. return BFieldType::CLOVER_FIELD;
  1626. case Obj::CURSED_GROUND1: case Obj::CURSED_GROUND2:
  1627. return BFieldType::CURSED_GROUND;
  1628. case Obj::EVIL_FOG:
  1629. return BFieldType::EVIL_FOG;
  1630. case Obj::FAVORABLE_WINDS:
  1631. return BFieldType::FAVOURABLE_WINDS;
  1632. case Obj::FIERY_FIELDS:
  1633. return BFieldType::FIERY_FIELDS;
  1634. case Obj::HOLY_GROUNDS:
  1635. return BFieldType::HOLY_GROUND;
  1636. case Obj::LUCID_POOLS:
  1637. return BFieldType::LUCID_POOLS;
  1638. case Obj::MAGIC_CLOUDS:
  1639. return BFieldType::MAGIC_CLOUDS;
  1640. case Obj::MAGIC_PLAINS1: case Obj::MAGIC_PLAINS2:
  1641. return BFieldType::MAGIC_PLAINS;
  1642. case Obj::ROCKLANDS:
  1643. return BFieldType::ROCKLANDS;
  1644. }
  1645. }
  1646. if(!t.isWater() && t.isCoastal())
  1647. return BFieldType::SAND_SHORE;
  1648. switch(t.terType)
  1649. {
  1650. case ETerrainType::DIRT:
  1651. return BFieldType(rand()%3+3);
  1652. case ETerrainType::SAND:
  1653. return BFieldType::SAND_MESAS; //TODO: coast support
  1654. case ETerrainType::GRASS:
  1655. return BFieldType(rand()%2+6);
  1656. case ETerrainType::SNOW:
  1657. return BFieldType(rand()%2+10);
  1658. case ETerrainType::SWAMP:
  1659. return BFieldType::SWAMP_TREES;
  1660. case ETerrainType::ROUGH:
  1661. return BFieldType::ROUGH;
  1662. case ETerrainType::SUBTERRANEAN:
  1663. return BFieldType::SUBTERRANEAN;
  1664. case ETerrainType::LAVA:
  1665. return BFieldType::LAVA;
  1666. case ETerrainType::WATER:
  1667. return BFieldType::SHIP;
  1668. case ETerrainType::ROCK:
  1669. return BFieldType::ROCKLANDS;
  1670. default:
  1671. return BFieldType::NONE;
  1672. }
  1673. }
  1674. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1675. {
  1676. UpgradeInfo ret;
  1677. const CCreature *base = stack.type;
  1678. const CGHeroInstance *h = stack.armyObj->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(stack.armyObj) : nullptr;
  1679. const CGTownInstance *t = nullptr;
  1680. if(stack.armyObj->ID == Obj::TOWN)
  1681. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1682. else if(h)
  1683. { //hero specialty
  1684. TBonusListPtr lista = h->getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1685. for(const Bonus *it : *lista)
  1686. {
  1687. auto nid = CreatureID(it->additionalInfo);
  1688. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1689. {
  1690. ret.newID.push_back(nid);
  1691. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1692. }
  1693. }
  1694. t = h->visitedTown;
  1695. }
  1696. if(t)
  1697. {
  1698. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : t->creatures)
  1699. {
  1700. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1701. {
  1702. for(auto upgrID : dwelling.second)
  1703. {
  1704. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1705. {
  1706. ret.newID.push_back(upgrID);
  1707. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1708. }
  1709. }
  1710. }
  1711. }
  1712. }
  1713. //hero is visiting Hill Fort
  1714. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == Obj::HILL_FORT)
  1715. {
  1716. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1717. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1718. for(auto nid : base->upgrades)
  1719. {
  1720. ret.newID.push_back(nid);
  1721. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1722. }
  1723. }
  1724. if(ret.newID.size())
  1725. ret.oldID = base->idNumber;
  1726. for (Res::ResourceSet &cost : ret.cost)
  1727. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1728. return ret;
  1729. }
  1730. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 )
  1731. {
  1732. if ( color1 == color2 )
  1733. return PlayerRelations::SAME_PLAYER;
  1734. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1735. return PlayerRelations::ENEMIES;
  1736. const TeamState * ts = getPlayerTeam(color1);
  1737. if (ts && vstd::contains(ts->players, color2))
  1738. return PlayerRelations::ALLIES;
  1739. return PlayerRelations::ENEMIES;
  1740. }
  1741. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1742. {
  1743. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1744. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1745. for (auto & dir : dirs)
  1746. {
  1747. const int3 hlp = tile + dir;
  1748. if(!map->isInTheMap(hlp))
  1749. continue;
  1750. const TerrainTile &hlpt = map->getTile(hlp);
  1751. // //we cannot visit things from blocked tiles
  1752. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1753. // {
  1754. // continue;
  1755. // }
  1756. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dir.x && dir.y) //diagonal move through water
  1757. {
  1758. int3 hlp1 = tile,
  1759. hlp2 = tile;
  1760. hlp1.x += dir.x;
  1761. hlp2.y += dir.y;
  1762. if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
  1763. continue;
  1764. }
  1765. if((indeterminate(onLand) || onLand == (hlpt.terType!=ETerrainType::WATER) )
  1766. && hlpt.terType != ETerrainType::ROCK)
  1767. {
  1768. vec.push_back(hlp);
  1769. }
  1770. }
  1771. }
  1772. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1773. {
  1774. if(src == dest) //same tile
  1775. return 0;
  1776. TerrainTile &s = map->getTile(src),
  1777. &d = map->getTile(dest);
  1778. //get basic cost
  1779. int ret = h->getTileCost(d,s);
  1780. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1781. {
  1782. bool freeFlying = h->getBonusesCount(Selector::typeSubtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1783. if(!freeFlying)
  1784. {
  1785. ret *= 1.4; //40% penalty for movement over blocked tile
  1786. }
  1787. }
  1788. else if (d.terType == ETerrainType::WATER)
  1789. {
  1790. if(h->boat && s.hasFavourableWinds() && d.hasFavourableWinds()) //Favourable Winds
  1791. ret *= 0.666;
  1792. else if (!h->boat && h->getBonusesCount(Selector::typeSubtype(Bonus::WATER_WALKING, 1)) > 0)
  1793. ret *= 1.4; //40% penalty for water walking
  1794. }
  1795. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1796. {
  1797. int old = ret;
  1798. ret *= 1.414213;
  1799. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1800. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1801. {
  1802. return remainingMovePoints;
  1803. }
  1804. }
  1805. int left = remainingMovePoints-ret;
  1806. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1807. {
  1808. std::vector<int3> vec;
  1809. getNeighbours(d, dest, vec, s.terType != ETerrainType::WATER, true);
  1810. for(auto & elem : vec)
  1811. {
  1812. int fcost = getMovementCost(h,dest,elem,left,false);
  1813. if(fcost <= left)
  1814. {
  1815. return ret;
  1816. }
  1817. }
  1818. ret = remainingMovePoints;
  1819. }
  1820. return ret;
  1821. }
  1822. void CGameState::apply(CPack *pack)
  1823. {
  1824. ui16 typ = typeList.getTypeID(pack);
  1825. applierGs->apps[typ]->applyOnGS(this,pack);
  1826. }
  1827. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1828. {
  1829. CPathfinder pathfinder(out, this, hero);
  1830. pathfinder.calculatePaths(src, movement);
  1831. }
  1832. /**
  1833. * Tells if the tile is guarded by a monster as well as the position
  1834. * of the monster that will attack on it.
  1835. *
  1836. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1837. * the monster guarding the tile.
  1838. */
  1839. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1840. {
  1841. std::vector<CGObjectInstance*> guards;
  1842. const int3 originalPos = pos;
  1843. if (!map->isInTheMap(pos))
  1844. return guards;
  1845. const TerrainTile &posTile = map->getTile(pos);
  1846. if (posTile.visitable)
  1847. {
  1848. for (CGObjectInstance* obj : posTile.visitableObjects)
  1849. {
  1850. if(obj->blockVisit)
  1851. {
  1852. if (obj->ID == Obj::MONSTER) // Monster
  1853. guards.push_back(obj);
  1854. }
  1855. }
  1856. }
  1857. pos -= int3(1, 1, 0); // Start with top left.
  1858. for (int dx = 0; dx < 3; dx++)
  1859. {
  1860. for (int dy = 0; dy < 3; dy++)
  1861. {
  1862. if (map->isInTheMap(pos))
  1863. {
  1864. const auto & tile = map->getTile(pos);
  1865. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1866. {
  1867. for (CGObjectInstance* obj : tile.visitableObjects)
  1868. {
  1869. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1870. {
  1871. guards.push_back(obj);
  1872. }
  1873. }
  1874. }
  1875. }
  1876. pos.y++;
  1877. }
  1878. pos.y -= 3;
  1879. pos.x++;
  1880. }
  1881. return guards;
  1882. }
  1883. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1884. {
  1885. const int3 originalPos = pos;
  1886. // Give monster at position priority.
  1887. if (!map->isInTheMap(pos))
  1888. return int3(-1, -1, -1);
  1889. const TerrainTile &posTile = map->getTile(pos);
  1890. if (posTile.visitable)
  1891. {
  1892. for (CGObjectInstance* obj : posTile.visitableObjects)
  1893. {
  1894. if(obj->blockVisit)
  1895. {
  1896. if (obj->ID == Obj::MONSTER) // Monster
  1897. return pos;
  1898. else
  1899. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  1900. }
  1901. }
  1902. }
  1903. // See if there are any monsters adjacent.
  1904. pos -= int3(1, 1, 0); // Start with top left.
  1905. for (int dx = 0; dx < 3; dx++)
  1906. {
  1907. for (int dy = 0; dy < 3; dy++)
  1908. {
  1909. if (map->isInTheMap(pos))
  1910. {
  1911. const auto & tile = map->getTile(pos);
  1912. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1913. {
  1914. for (CGObjectInstance* obj : tile.visitableObjects)
  1915. {
  1916. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1917. {
  1918. return pos;
  1919. }
  1920. }
  1921. }
  1922. }
  1923. pos.y++;
  1924. }
  1925. pos.y -= 3;
  1926. pos.x++;
  1927. }
  1928. return int3(-1, -1, -1);
  1929. }
  1930. bool CGameState::isVisible(int3 pos, PlayerColor player)
  1931. {
  1932. if(player == PlayerColor::NEUTRAL)
  1933. return false;
  1934. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  1935. }
  1936. bool CGameState::isVisible( const CGObjectInstance *obj, boost::optional<PlayerColor> player )
  1937. {
  1938. if(!player)
  1939. return true;
  1940. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1941. return false;
  1942. //object is visible when at least one blocked tile is visible
  1943. for(int fx=0; fx<8; ++fx)
  1944. {
  1945. for(int fy=0; fy<6; ++fy)
  1946. {
  1947. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1948. if(map->isInTheMap(pos)
  1949. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1950. && isVisible(pos, *player) )
  1951. return true;
  1952. }
  1953. }
  1954. return false;
  1955. }
  1956. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1957. {
  1958. const TerrainTile * pom = &map->getTile(dst);
  1959. return checkForVisitableDir(src, pom, dst);
  1960. }
  1961. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  1962. {
  1963. for(ui32 b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1964. {
  1965. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1966. continue;
  1967. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1968. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1969. {
  1970. return false;
  1971. }
  1972. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1973. {
  1974. return false;
  1975. }
  1976. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1977. {
  1978. return false;
  1979. }
  1980. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1981. {
  1982. return false;
  1983. }
  1984. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1985. {
  1986. return false;
  1987. }
  1988. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1989. {
  1990. return false;
  1991. }
  1992. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1993. {
  1994. return false;
  1995. }
  1996. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1997. {
  1998. return false;
  1999. }
  2000. }
  2001. return true;
  2002. }
  2003. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(PlayerColor player) const
  2004. {
  2005. auto result = checkForVictory(player);
  2006. if (result == EVictoryLossCheckResult::NO_VICTORY_OR_LOSS) result = checkForLoss(player);
  2007. return result;
  2008. }
  2009. EVictoryLossCheckResult CGameState::checkForVictory( PlayerColor player ) const
  2010. {
  2011. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2012. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD || map->victoryCondition.allowNormalVictory
  2013. || (!p->human && !map->victoryCondition.appliesToAI)) //if the special victory condition applies only to human, AI has the standard)
  2014. {
  2015. if(player == checkForStandardWin())
  2016. return EVictoryLossCheckResult::VICTORY_STANDARD;
  2017. }
  2018. if (p->enteredWinningCheatCode)
  2019. { //cheater or tester, but has entered the code...
  2020. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD)
  2021. return EVictoryLossCheckResult::VICTORY_STANDARD;
  2022. else
  2023. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2024. }
  2025. if(p->human || map->victoryCondition.appliesToAI)
  2026. {
  2027. switch(map->victoryCondition.condition)
  2028. {
  2029. case EVictoryConditionType::ARTIFACT:
  2030. //check if any hero has winning artifact
  2031. for(auto & elem : p->heroes)
  2032. if(elem->hasArt(map->victoryCondition.objectId))
  2033. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2034. break;
  2035. case EVictoryConditionType::GATHERTROOP:
  2036. {
  2037. //check if in players armies there is enough creatures
  2038. int total = 0; //creature counter
  2039. for(size_t i = 0; i < map->objects.size(); i++)
  2040. {
  2041. const CArmedInstance *ai = nullptr;
  2042. if(map->objects[i]
  2043. && map->objects[i]->tempOwner == player //object controlled by player
  2044. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  2045. {
  2046. for(auto & elem : ai->Slots()) //iterate through army
  2047. if(elem.second->type->idNumber == map->victoryCondition.objectId) //it's searched creature
  2048. total += elem.second->count;
  2049. }
  2050. }
  2051. if(total >= map->victoryCondition.count)
  2052. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2053. }
  2054. break;
  2055. case EVictoryConditionType::GATHERRESOURCE:
  2056. if(p->resources[map->victoryCondition.objectId] >= map->victoryCondition.count)
  2057. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2058. break;
  2059. case EVictoryConditionType::BUILDCITY:
  2060. {
  2061. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2062. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.objectId && t->hallLevel()-1 >= map->victoryCondition.count)
  2063. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2064. }
  2065. break;
  2066. case EVictoryConditionType::BUILDGRAIL:
  2067. for(const CGTownInstance *t : map->towns)
  2068. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  2069. && t->tempOwner == player
  2070. && t->hasBuilt(BuildingID::GRAIL))
  2071. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2072. break;
  2073. case EVictoryConditionType::BEATHERO:
  2074. if(map->victoryCondition.obj->tempOwner >= PlayerColor::PLAYER_LIMIT) //target hero not present on map
  2075. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2076. break;
  2077. case EVictoryConditionType::CAPTURECITY:
  2078. {
  2079. if(map->victoryCondition.obj->tempOwner == player)
  2080. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2081. }
  2082. break;
  2083. case EVictoryConditionType::BEATMONSTER:
  2084. if(!getObj(map->victoryCondition.obj->id)) //target monster not present on map
  2085. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2086. break;
  2087. case EVictoryConditionType::TAKEDWELLINGS:
  2088. for(auto & elem : map->objects)
  2089. {
  2090. if(elem && elem->tempOwner != player) //check not flagged objs
  2091. {
  2092. switch(elem->ID)
  2093. {
  2094. case Obj::CREATURE_GENERATOR1: case Obj::CREATURE_GENERATOR2:
  2095. case Obj::CREATURE_GENERATOR3: case Obj::CREATURE_GENERATOR4:
  2096. case Obj::RANDOM_DWELLING: case Obj::RANDOM_DWELLING_LVL: case Obj::RANDOM_DWELLING_FACTION:
  2097. return EVictoryLossCheckResult::NO_VICTORY_OR_LOSS; //found not flagged dwelling - player not won
  2098. }
  2099. }
  2100. }
  2101. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2102. case EVictoryConditionType::TAKEMINES:
  2103. for(auto & elem : map->objects)
  2104. {
  2105. if(elem && elem->tempOwner != player) //check not flagged objs
  2106. {
  2107. switch(elem->ID)
  2108. {
  2109. case Obj::MINE: case Obj::ABANDONED_MINE:
  2110. return EVictoryLossCheckResult::NO_VICTORY_OR_LOSS; //found not flagged mine - player not won
  2111. }
  2112. }
  2113. }
  2114. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2115. case EVictoryConditionType::TRANSPORTITEM:
  2116. {
  2117. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2118. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.objectId))
  2119. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.objectId)))
  2120. {
  2121. return EVictoryLossCheckResult::VICTORY_SPECIAL;
  2122. }
  2123. }
  2124. break;
  2125. }
  2126. }
  2127. return EVictoryLossCheckResult::NO_VICTORY_OR_LOSS;
  2128. }
  2129. PlayerColor CGameState::checkForStandardWin() const
  2130. {
  2131. //std victory condition is:
  2132. //all enemies lost
  2133. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  2134. TeamID winnerTeam = TeamID::NO_TEAM;
  2135. for(auto & elem : players)
  2136. {
  2137. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  2138. {
  2139. if(supposedWinner == PlayerColor::NEUTRAL)
  2140. {
  2141. //first player remaining ingame - candidate for victory
  2142. supposedWinner = elem.second.color;
  2143. winnerTeam = elem.second.team;
  2144. }
  2145. else if(winnerTeam != elem.second.team)
  2146. {
  2147. //current candidate has enemy remaining in game -> no vicotry
  2148. return PlayerColor::NEUTRAL;
  2149. }
  2150. }
  2151. }
  2152. return supposedWinner;
  2153. }
  2154. bool CGameState::checkForStandardLoss( PlayerColor player ) const
  2155. {
  2156. //std loss condition is: player lost all towns and heroes
  2157. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  2158. return !p.heroes.size() && !p.towns.size();
  2159. }
  2160. struct statsHLP
  2161. {
  2162. typedef std::pair< PlayerColor, si64 > TStat;
  2163. //converts [<player's color, value>] to vec[place] -> platers
  2164. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  2165. {
  2166. std::sort(stats.begin(), stats.end(), statsHLP());
  2167. //put first element
  2168. std::vector< std::vector<PlayerColor> > ret;
  2169. std::vector<PlayerColor> tmp;
  2170. tmp.push_back( stats[0].first );
  2171. ret.push_back( tmp );
  2172. //the rest of elements
  2173. for(int g=1; g<stats.size(); ++g)
  2174. {
  2175. if(stats[g].second == stats[g-1].second)
  2176. {
  2177. (ret.end()-1)->push_back( stats[g].first );
  2178. }
  2179. else
  2180. {
  2181. //create next occupied rank
  2182. std::vector<PlayerColor> tmp;
  2183. tmp.push_back(stats[g].first);
  2184. ret.push_back(tmp);
  2185. }
  2186. }
  2187. return ret;
  2188. }
  2189. bool operator()(const TStat & a, const TStat & b) const
  2190. {
  2191. return a.second > b.second;
  2192. }
  2193. static const CGHeroInstance * findBestHero(CGameState * gs, PlayerColor color)
  2194. {
  2195. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2196. if(!h.size())
  2197. return nullptr;
  2198. //best hero will be that with highest exp
  2199. int best = 0;
  2200. for(int b=1; b<h.size(); ++b)
  2201. {
  2202. if(h[b]->exp > h[best]->exp)
  2203. {
  2204. best = b;
  2205. }
  2206. }
  2207. return h[best];
  2208. }
  2209. //calculates total number of artifacts that belong to given player
  2210. static int getNumberOfArts(const PlayerState * ps)
  2211. {
  2212. int ret = 0;
  2213. for(auto h : ps->heroes)
  2214. {
  2215. ret += h->artifactsInBackpack.size() + h->artifactsWorn.size();
  2216. }
  2217. return ret;
  2218. }
  2219. // get total strength of player army
  2220. static si64 getArmyStrength(const PlayerState * ps)
  2221. {
  2222. si64 str = 0;
  2223. for(auto h : ps->heroes)
  2224. {
  2225. if(!h->inTownGarrison) //original h3 behavior
  2226. str += h->getArmyStrength();
  2227. }
  2228. return str;
  2229. }
  2230. };
  2231. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2232. {
  2233. auto playerInactive = [&](PlayerColor color)
  2234. {
  2235. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  2236. };
  2237. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2238. { \
  2239. std::vector< std::pair< PlayerColor, si64 > > stats; \
  2240. for(auto g = players.begin(); g != players.end(); ++g) \
  2241. { \
  2242. if(playerInactive(g->second.color)) \
  2243. continue; \
  2244. std::pair< PlayerColor, si64 > stat; \
  2245. stat.first = g->second.color; \
  2246. stat.second = VAL_GETTER; \
  2247. stats.push_back(stat); \
  2248. } \
  2249. tgi.FIELD = statsHLP::getRank(stats); \
  2250. }
  2251. for(auto & elem : players)
  2252. {
  2253. if(!playerInactive(elem.second.color))
  2254. tgi.playerColors.push_back(elem.second.color);
  2255. }
  2256. if(level >= 1) //num of towns & num of heroes
  2257. {
  2258. //num of towns
  2259. FILL_FIELD(numOfTowns, g->second.towns.size())
  2260. //num of heroes
  2261. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2262. //best hero's portrait
  2263. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2264. {
  2265. if(playerInactive(g->second.color))
  2266. continue;
  2267. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2268. InfoAboutHero iah;
  2269. iah.initFromHero(best, level >= 8);
  2270. iah.army.clear();
  2271. tgi.colorToBestHero[g->second.color] = iah;
  2272. }
  2273. }
  2274. if(level >= 2) //gold
  2275. {
  2276. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2277. }
  2278. if(level >= 2) //wood & ore
  2279. {
  2280. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2281. }
  2282. if(level >= 3) //mercury, sulfur, crystal, gems
  2283. {
  2284. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2285. }
  2286. if(level >= 4) //obelisks found
  2287. {
  2288. FILL_FIELD(obelisks, CGObelisk::visited[gs->getPlayerTeam(g->second.color)->id])
  2289. }
  2290. if(level >= 5) //artifacts
  2291. {
  2292. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2293. }
  2294. if(level >= 6) //army strength
  2295. {
  2296. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2297. }
  2298. if(level >= 7) //income
  2299. {
  2300. //TODO:obtainPlayersStats - income
  2301. }
  2302. if(level >= 8) //best hero's stats
  2303. {
  2304. //already set in lvl 1 handling
  2305. }
  2306. if(level >= 9) //personality
  2307. {
  2308. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2309. {
  2310. if(playerInactive(g->second.color)) //do nothing for neutral player
  2311. continue;
  2312. if(g->second.human)
  2313. {
  2314. tgi.personality[g->second.color] = EAiTactic::NONE;
  2315. }
  2316. else //AI
  2317. {
  2318. tgi.personality[g->second.color] = map->players[g->second.color.getNum()].aiTactic;
  2319. }
  2320. }
  2321. }
  2322. if(level >= 10) //best creature
  2323. {
  2324. //best creatures belonging to player (highest AI value)
  2325. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2326. {
  2327. if(playerInactive(g->second.color)) //do nothing for neutral player
  2328. continue;
  2329. int bestCre = -1; //best creature's ID
  2330. for(auto & elem : g->second.heroes)
  2331. {
  2332. for(auto it = elem->Slots().begin(); it != elem->Slots().end(); ++it)
  2333. {
  2334. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2335. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2336. {
  2337. bestCre = toCmp;
  2338. }
  2339. }
  2340. }
  2341. tgi.bestCreature[g->second.color] = bestCre;
  2342. }
  2343. }
  2344. #undef FILL_FIELD
  2345. }
  2346. EVictoryLossCheckResult CGameState::checkForLoss( PlayerColor player ) const
  2347. {
  2348. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2349. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2350. if(checkForStandardLoss(player))
  2351. return EVictoryLossCheckResult::LOSS_STANDARD_HEROES_AND_TOWNS;
  2352. if (p->enteredLosingCheatCode)
  2353. {
  2354. return EVictoryLossCheckResult::LOSS_SPECIAL;
  2355. }
  2356. if(p->human) //special loss condition applies only to human player
  2357. {
  2358. switch(map->lossCondition.typeOfLossCon)
  2359. {
  2360. case ELossConditionType::LOSSCASTLE:
  2361. case ELossConditionType::LOSSHERO:
  2362. {
  2363. const CGObjectInstance *obj = map->lossCondition.obj;
  2364. assert(obj);
  2365. if(obj->tempOwner != player)
  2366. return EVictoryLossCheckResult::LOSS_SPECIAL;
  2367. }
  2368. break;
  2369. case ELossConditionType::TIMEEXPIRES:
  2370. if(map->lossCondition.timeLimit < day)
  2371. return EVictoryLossCheckResult::LOSS_SPECIAL;
  2372. break;
  2373. }
  2374. }
  2375. if(p->towns.empty() && p->daysWithoutCastle && *p->daysWithoutCastle >= 6 && currentPlayer != player)
  2376. {
  2377. return EVictoryLossCheckResult::LOSS_STANDARD_TOWNS_AND_TIME_OVER;
  2378. }
  2379. return EVictoryLossCheckResult::NO_VICTORY_OR_LOSS;
  2380. }
  2381. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2382. {
  2383. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2384. for ( auto i = players.cbegin() ; i != players.cend();i++)
  2385. for(auto j = i->second.availableHeroes.cbegin(); j != i->second.availableHeroes.cend(); j++)
  2386. if(*j)
  2387. pool.erase((**j).subID);
  2388. return pool;
  2389. }
  2390. void CGameState::buildBonusSystemTree()
  2391. {
  2392. buildGlobalTeamPlayerTree();
  2393. attachArmedObjects();
  2394. for(CGTownInstance *t : map->towns)
  2395. {
  2396. t->deserializationFix();
  2397. }
  2398. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2399. // are provided on initializing / deserializing
  2400. }
  2401. void CGameState::deserializationFix()
  2402. {
  2403. buildGlobalTeamPlayerTree();
  2404. attachArmedObjects();
  2405. }
  2406. void CGameState::buildGlobalTeamPlayerTree()
  2407. {
  2408. for(auto k=teams.begin(); k!=teams.end(); ++k)
  2409. {
  2410. TeamState *t = &k->second;
  2411. t->attachTo(&globalEffects);
  2412. for(PlayerColor teamMember : k->second.players)
  2413. {
  2414. PlayerState *p = getPlayer(teamMember);
  2415. assert(p);
  2416. p->attachTo(t);
  2417. }
  2418. }
  2419. }
  2420. void CGameState::attachArmedObjects()
  2421. {
  2422. for(CGObjectInstance *obj : map->objects)
  2423. {
  2424. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2425. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2426. }
  2427. }
  2428. void CGameState::giveHeroArtifact(CGHeroInstance *h, ArtifactID aid)
  2429. {
  2430. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2431. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2432. map->addNewArtifactInstance(ai);
  2433. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2434. }
  2435. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed /*= false*/) const
  2436. {
  2437. std::set<HeroTypeID> ret;
  2438. for(int i = 0; i < map->allowedHeroes.size(); i++)
  2439. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  2440. ret.insert(HeroTypeID(i));
  2441. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2442. {
  2443. if(hero->type)
  2444. ret -= hero->type->ID;
  2445. else
  2446. ret -= HeroTypeID(hero->subID);
  2447. }
  2448. for(auto obj : map->objects) //prisons
  2449. if(obj && obj->ID == Obj::PRISON)
  2450. ret -= HeroTypeID(obj->subID);
  2451. return ret;
  2452. }
  2453. std::vector<std::pair<CGHeroInstance*, ObjectInstanceID> > CGameState::generateCampaignHeroesToReplace(std::vector<CGHeroInstance *> & crossoverHeroes)
  2454. {
  2455. std::vector<std::pair<CGHeroInstance*, ObjectInstanceID> > campaignHeroReplacements;
  2456. //selecting heroes by type
  2457. for(int g = 0; g < map->objects.size(); ++g)
  2458. {
  2459. CGObjectInstance * obj = map->objects[g];
  2460. if (obj->ID == Obj::HERO_PLACEHOLDER)
  2461. {
  2462. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  2463. const ObjectInstanceID gid = ObjectInstanceID(g);
  2464. if(hp->subID != 0xFF) //select by type
  2465. {
  2466. bool found = false;
  2467. for(auto ghi : crossoverHeroes)
  2468. {
  2469. if (ghi->subID == hp->subID)
  2470. {
  2471. found = true;
  2472. campaignHeroReplacements.push_back(std::make_pair(ghi, gid));
  2473. crossoverHeroes -= ghi;
  2474. break;
  2475. }
  2476. }
  2477. if(!found)
  2478. {
  2479. auto nh = new CGHeroInstance();
  2480. nh->initHero(HeroTypeID(hp->subID));
  2481. campaignHeroReplacements.push_back(std::make_pair(nh, gid));
  2482. }
  2483. //TODO delete hero placeholder
  2484. }
  2485. }
  2486. }
  2487. //selecting heroes by power
  2488. std::sort(crossoverHeroes.begin(), crossoverHeroes.end(), [](const CGHeroInstance * a, const CGHeroInstance * b)
  2489. {
  2490. return a->getHeroStrength() > b->getHeroStrength();
  2491. }); //sort, descending strength
  2492. // sort hero placeholders descending power
  2493. std::vector<CGHeroPlaceholder *> heroPlaceholders;
  2494. for(int g = 0; g < map->objects.size(); ++g)
  2495. {
  2496. CGObjectInstance * obj = map->objects[g];
  2497. if(obj->ID == Obj::HERO_PLACEHOLDER)
  2498. {
  2499. CGHeroPlaceholder * hp = dynamic_cast<CGHeroPlaceholder*>(obj);
  2500. if(hp->subID == 0xFF) //select by power
  2501. {
  2502. heroPlaceholders.push_back(hp);
  2503. }
  2504. }
  2505. }
  2506. std::sort(heroPlaceholders.begin(), heroPlaceholders.end(), [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  2507. {
  2508. return a->power > b->power;
  2509. });
  2510. for(int i = 0; i < heroPlaceholders.size(); ++i)
  2511. {
  2512. auto heroPlaceholder = heroPlaceholders[i];
  2513. if(crossoverHeroes.size() > i)
  2514. {
  2515. campaignHeroReplacements.push_back(std::make_pair(crossoverHeroes[i], heroPlaceholder->id));
  2516. }
  2517. else
  2518. {
  2519. map->removeBlockVisTiles(heroPlaceholder, true);
  2520. delete heroPlaceholder;
  2521. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  2522. }
  2523. }
  2524. return campaignHeroReplacements;
  2525. }
  2526. void CGameState::replaceHeroesPlaceholders(const std::vector<std::pair<CGHeroInstance*, ObjectInstanceID> > &campHeroReplacements)
  2527. {
  2528. for(auto obj : campHeroReplacements)
  2529. {
  2530. CGHeroPlaceholder *placeholder = dynamic_cast<CGHeroPlaceholder*>(getObjInstance(obj.second));
  2531. CGHeroInstance *heroToPlace = obj.first;
  2532. heroToPlace->id = obj.second;
  2533. heroToPlace->tempOwner = placeholder->tempOwner;
  2534. heroToPlace->pos = placeholder->pos;
  2535. heroToPlace->type = VLC->heroh->heroes[heroToPlace->type->ID.getNum()]; //TODO is this reasonable? either old type can be still used or it can be deleted?
  2536. for(auto &&i : heroToPlace->stacks)
  2537. i.second->type = VLC->creh->creatures[i.second->getCreatureID()];
  2538. auto fixArtifact = [&](CArtifactInstance * art)
  2539. {
  2540. art->artType = VLC->arth->artifacts[art->artType->id];
  2541. gs->map->artInstances.push_back(art);
  2542. art->id = ArtifactInstanceID(gs->map->artInstances.size() - 1);
  2543. };
  2544. for(auto &&i : heroToPlace->artifactsWorn)
  2545. fixArtifact(i.second.artifact);
  2546. for(auto &&i : heroToPlace->artifactsInBackpack)
  2547. fixArtifact(i.artifact);
  2548. map->heroesOnMap.push_back(heroToPlace);
  2549. map->objects[heroToPlace->id.getNum()] = heroToPlace;
  2550. map->addBlockVisTiles(heroToPlace);
  2551. //const auto & travelOptions = scenarioOps->campState->getCurrentScenario().travelOptions;
  2552. }
  2553. }
  2554. bool CGameState::isUsedHero(HeroTypeID hid) const
  2555. {
  2556. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2557. if(hero->subID == hid.getNum())
  2558. return true;
  2559. for(auto obj : map->objects) //prisons
  2560. if(obj && obj->ID == Obj::PRISON && obj->subID == hid.getNum())
  2561. return true;
  2562. return false;
  2563. }
  2564. CGPathNode::CGPathNode()
  2565. :coord(-1,-1,-1)
  2566. {
  2567. accessible = NOT_SET;
  2568. land = 0;
  2569. moveRemains = 0;
  2570. turns = 255;
  2571. theNodeBefore = nullptr;
  2572. }
  2573. bool CGPathNode::reachable() const
  2574. {
  2575. return turns < 255;
  2576. }
  2577. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2578. {
  2579. assert(isValid);
  2580. out.nodes.clear();
  2581. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2582. if(!curnode->theNodeBefore)
  2583. return false;
  2584. while(curnode)
  2585. {
  2586. CGPathNode cpn = *curnode;
  2587. curnode = curnode->theNodeBefore;
  2588. out.nodes.push_back(cpn);
  2589. }
  2590. return true;
  2591. }
  2592. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2593. :sizes(Sizes)
  2594. {
  2595. hero = nullptr;
  2596. nodes = new CGPathNode**[sizes.x];
  2597. for(int i = 0; i < sizes.x; i++)
  2598. {
  2599. nodes[i] = new CGPathNode*[sizes.y];
  2600. for (int j = 0; j < sizes.y; j++)
  2601. {
  2602. nodes[i][j] = new CGPathNode[sizes.z];
  2603. }
  2604. }
  2605. }
  2606. CPathsInfo::~CPathsInfo()
  2607. {
  2608. for(int i = 0; i < sizes.x; i++)
  2609. {
  2610. for (int j = 0; j < sizes.y; j++)
  2611. {
  2612. delete [] nodes[i][j];
  2613. }
  2614. delete [] nodes[i];
  2615. }
  2616. delete [] nodes;
  2617. }
  2618. int3 CGPath::startPos() const
  2619. {
  2620. return nodes[nodes.size()-1].coord;
  2621. }
  2622. int3 CGPath::endPos() const
  2623. {
  2624. return nodes[0].coord;
  2625. }
  2626. void CGPath::convert( ui8 mode )
  2627. {
  2628. if(mode==0)
  2629. {
  2630. for(auto & elem : nodes)
  2631. {
  2632. elem.coord = CGHeroInstance::convertPosition(elem.coord,true);
  2633. }
  2634. }
  2635. }
  2636. PlayerState::PlayerState()
  2637. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2638. enteredLosingCheatCode(0), status(EPlayerStatus::INGAME)
  2639. {
  2640. setNodeType(PLAYER);
  2641. }
  2642. std::string PlayerState::nodeName() const
  2643. {
  2644. return "Player " + (color.getNum() < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color.getNum()] : boost::lexical_cast<std::string>(color));
  2645. }
  2646. InfoAboutArmy::InfoAboutArmy():
  2647. owner(PlayerColor::NEUTRAL)
  2648. {}
  2649. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2650. {
  2651. initFromArmy(Army, detailed);
  2652. }
  2653. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2654. {
  2655. army = ArmyDescriptor(Army, detailed);
  2656. owner = Army->tempOwner;
  2657. name = Army->getHoverText();
  2658. }
  2659. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2660. {
  2661. InfoAboutArmy::operator = (iah);
  2662. details = (iah.details ? new Details(*iah.details) : nullptr);
  2663. hclass = iah.hclass;
  2664. portrait = iah.portrait;
  2665. }
  2666. InfoAboutHero::InfoAboutHero():
  2667. details(nullptr),
  2668. hclass(nullptr),
  2669. portrait(-1)
  2670. {}
  2671. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2672. InfoAboutArmy()
  2673. {
  2674. assign(iah);
  2675. }
  2676. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, bool detailed)
  2677. : details(nullptr),
  2678. hclass(nullptr),
  2679. portrait(-1)
  2680. {
  2681. initFromHero(h, detailed);
  2682. }
  2683. InfoAboutHero::~InfoAboutHero()
  2684. {
  2685. delete details;
  2686. }
  2687. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2688. {
  2689. assign(iah);
  2690. return *this;
  2691. }
  2692. void InfoAboutHero::initFromHero(const CGHeroInstance *h, bool detailed)
  2693. {
  2694. if(!h)
  2695. return;
  2696. initFromArmy(h, detailed);
  2697. hclass = h->type->heroClass;
  2698. name = h->name;
  2699. portrait = h->portrait;
  2700. if(detailed)
  2701. {
  2702. //include details about hero
  2703. details = new Details;
  2704. details->luck = h->LuckVal();
  2705. details->morale = h->MoraleVal();
  2706. details->mana = h->mana;
  2707. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2708. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2709. {
  2710. details->primskills[i] = h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i));
  2711. }
  2712. }
  2713. }
  2714. InfoAboutTown::InfoAboutTown():
  2715. details(nullptr),
  2716. tType(nullptr),
  2717. built(0),
  2718. fortLevel(0)
  2719. {
  2720. }
  2721. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed)
  2722. {
  2723. initFromTown(t, detailed);
  2724. }
  2725. InfoAboutTown::~InfoAboutTown()
  2726. {
  2727. delete details;
  2728. }
  2729. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2730. {
  2731. initFromArmy(t, detailed);
  2732. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2733. built = t->builded;
  2734. fortLevel = t->fortLevel();
  2735. name = t->name;
  2736. tType = t->town;
  2737. if(detailed)
  2738. {
  2739. //include details about hero
  2740. details = new Details;
  2741. details->goldIncome = t->dailyIncome();
  2742. details->customRes = t->hasBuilt(BuildingID::RESOURCE_SILO);
  2743. details->hallLevel = t->hallLevel();
  2744. details->garrisonedHero = t->garrisonHero;
  2745. }
  2746. }
  2747. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2748. : isDetailed(detailed)
  2749. {
  2750. for(auto & elem : army->Slots())
  2751. {
  2752. if(detailed)
  2753. (*this)[elem.first] = *elem.second;
  2754. else
  2755. (*this)[elem.first] = CStackBasicDescriptor(elem.second->type, elem.second->getQuantityID());
  2756. }
  2757. }
  2758. ArmyDescriptor::ArmyDescriptor()
  2759. : isDetailed(false)
  2760. {
  2761. }
  2762. int ArmyDescriptor::getStrength() const
  2763. {
  2764. ui64 ret = 0;
  2765. if(isDetailed)
  2766. {
  2767. for(auto & elem : *this)
  2768. ret += elem.second.type->AIValue * elem.second.count;
  2769. }
  2770. else
  2771. {
  2772. for(auto & elem : *this)
  2773. ret += elem.second.type->AIValue * CCreature::estimateCreatureCount(elem.second.count);
  2774. }
  2775. return ret;
  2776. }
  2777. DuelParameters::SideSettings::StackSettings::StackSettings()
  2778. : type(CreatureID::NONE), count(0)
  2779. {
  2780. }
  2781. DuelParameters::SideSettings::StackSettings::StackSettings(CreatureID Type, si32 Count)
  2782. : type(Type), count(Count)
  2783. {
  2784. }
  2785. DuelParameters::SideSettings::SideSettings()
  2786. {
  2787. heroId = -1;
  2788. }
  2789. DuelParameters::DuelParameters():
  2790. terType(ETerrainType::DIRT),
  2791. bfieldType(BFieldType::ROCKLANDS)
  2792. {
  2793. }
  2794. DuelParameters DuelParameters::fromJSON(const std::string &fname)
  2795. {
  2796. DuelParameters ret;
  2797. const JsonNode duelData(ResourceID("DATA/" + fname, EResType::TEXT));
  2798. ret.terType = ETerrainType((int)duelData["terType"].Float());
  2799. ret.bfieldType = BFieldType((int)duelData["bfieldType"].Float());
  2800. for(const JsonNode &n : duelData["sides"].Vector())
  2801. {
  2802. SideSettings &ss = ret.sides[(int)n["side"].Float()];
  2803. int i = 0;
  2804. for(const JsonNode &stackNode : n["army"].Vector())
  2805. {
  2806. ss.stacks[i].type = CreatureID((si32)stackNode.Vector()[0].Float());
  2807. ss.stacks[i].count = stackNode.Vector()[1].Float();
  2808. i++;
  2809. }
  2810. if(n["heroid"].getType() == JsonNode::DATA_FLOAT)
  2811. ss.heroId = n["heroid"].Float();
  2812. else
  2813. ss.heroId = -1;
  2814. for(const JsonNode &entry : n["heroPrimSkills"].Vector())
  2815. ss.heroPrimSkills.push_back(entry.Float());
  2816. for(const JsonNode &skillNode : n["heroSecSkills"].Vector())
  2817. {
  2818. std::pair<si32, si8> secSkill;
  2819. secSkill.first = skillNode.Vector()[0].Float();
  2820. secSkill.second = skillNode.Vector()[1].Float();
  2821. ss.heroSecSkills.push_back(secSkill);
  2822. }
  2823. assert(ss.heroPrimSkills.empty() || ss.heroPrimSkills.size() == GameConstants::PRIMARY_SKILLS);
  2824. if(ss.heroId != -1)
  2825. {
  2826. const JsonNode & spells = n["spells"];
  2827. if(spells.getType() == JsonNode::DATA_STRING && spells.String() == "all")
  2828. {
  2829. for(auto spell : VLC->spellh->spells)
  2830. if(spell->id <= SpellID::SUMMON_AIR_ELEMENTAL)
  2831. ss.spells.insert(spell->id);
  2832. }
  2833. else
  2834. for(const JsonNode &spell : n["spells"].Vector())
  2835. ss.spells.insert(SpellID(spell.Float()));
  2836. }
  2837. }
  2838. for(const JsonNode &n : duelData["obstacles"].Vector())
  2839. {
  2840. auto oi = make_shared<CObstacleInstance>();
  2841. if(n.getType() == JsonNode::DATA_VECTOR)
  2842. {
  2843. oi->ID = n.Vector()[0].Float();
  2844. oi->pos = n.Vector()[1].Float();
  2845. }
  2846. else
  2847. {
  2848. assert(n.getType() == JsonNode::DATA_FLOAT);
  2849. oi->ID = 21;
  2850. oi->pos = n.Float();
  2851. }
  2852. oi->uniqueID = ret.obstacles.size();
  2853. ret.obstacles.push_back(oi);
  2854. }
  2855. for(const JsonNode &n : duelData["creatures"].Vector())
  2856. {
  2857. CusomCreature cc;
  2858. cc.id = n["id"].Float();
  2859. #define retreive(name) \
  2860. if(n[ #name ].getType() == JsonNode::DATA_FLOAT)\
  2861. cc.name = n[ #name ].Float(); \
  2862. else \
  2863. cc.name = -1;
  2864. retreive(attack);
  2865. retreive(defense);
  2866. retreive(HP);
  2867. retreive(dmg);
  2868. retreive(shoots);
  2869. retreive(speed);
  2870. ret.creatures.push_back(cc);
  2871. }
  2872. return ret;
  2873. }
  2874. TeamState::TeamState()
  2875. {
  2876. setNodeType(TEAM);
  2877. }
  2878. void CPathfinder::initializeGraph()
  2879. {
  2880. CGPathNode ***graph = out.nodes;
  2881. for(size_t i=0; i < out.sizes.x; ++i)
  2882. {
  2883. for(size_t j=0; j < out.sizes.y; ++j)
  2884. {
  2885. for(size_t k=0; k < out.sizes.z; ++k)
  2886. {
  2887. curPos = int3(i,j,k);
  2888. const TerrainTile *tinfo = &gs->map->getTile(int3(i, j, k));
  2889. CGPathNode &node = graph[i][j][k];
  2890. node.accessible = evaluateAccessibility(tinfo);
  2891. node.turns = 0xff;
  2892. node.moveRemains = 0;
  2893. node.coord.x = i;
  2894. node.coord.y = j;
  2895. node.coord.z = k;
  2896. node.land = tinfo->terType != ETerrainType::WATER;
  2897. node.theNodeBefore = nullptr;
  2898. }
  2899. }
  2900. }
  2901. }
  2902. void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*= -1*/)
  2903. {
  2904. assert(hero);
  2905. assert(hero == getHero(hero->id));
  2906. if(src.x < 0)
  2907. src = hero->getPosition(false);
  2908. if(movement < 0)
  2909. movement = hero->movement;
  2910. out.hero = hero;
  2911. out.hpos = src;
  2912. if(!gs->map->isInTheMap(src)/* || !gs->map->isInTheMap(dest)*/) //check input
  2913. {
  2914. logGlobal->errorStream() << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...";
  2915. return;
  2916. }
  2917. initializeGraph();
  2918. //initial tile - set cost on 0 and add to the queue
  2919. CGPathNode &initialNode = *getNode(src);
  2920. initialNode.turns = 0;
  2921. initialNode.moveRemains = movement;
  2922. mq.push_back(&initialNode);
  2923. std::vector<int3> neighbours;
  2924. neighbours.reserve(16);
  2925. while(!mq.empty())
  2926. {
  2927. cp = mq.front();
  2928. mq.pop_front();
  2929. const int3 sourceGuardPosition = guardingCreaturePosition(cp->coord);
  2930. bool guardedSource = (sourceGuardPosition != int3(-1, -1, -1) && cp->coord != src);
  2931. ct = &gs->map->getTile(cp->coord);
  2932. int movement = cp->moveRemains, turn = cp->turns;
  2933. if(!movement)
  2934. {
  2935. movement = hero->maxMovePoints(cp->land);
  2936. turn++;
  2937. }
  2938. //add accessible neighbouring nodes to the queue
  2939. neighbours.clear();
  2940. //handling subterranean gate => it's exit is the only neighbour
  2941. bool subterraneanEntry = (ct->topVisitableId() == Obj::SUBTERRANEAN_GATE && useSubterraneanGates);
  2942. if(subterraneanEntry)
  2943. {
  2944. //try finding the exit gate
  2945. if(const CGObjectInstance *outGate = getObj(CGTeleport::getMatchingGate(ct->visitableObjects.back()->id), false))
  2946. {
  2947. const int3 outPos = outGate->visitablePos();
  2948. //gs->getNeighbours(*getTile(outPos), outPos, neighbours, boost::logic::indeterminate, !cp->land);
  2949. neighbours.push_back(outPos);
  2950. }
  2951. else
  2952. {
  2953. //gate with no exit (blocked) -> do nothing with this node
  2954. continue;
  2955. }
  2956. }
  2957. gs->getNeighbours(*ct, cp->coord, neighbours, boost::logic::indeterminate, !cp->land);
  2958. for(auto & neighbour : neighbours)
  2959. {
  2960. const int3 &n = neighbour; //current neighbor
  2961. dp = getNode(n);
  2962. dt = &gs->map->getTile(n);
  2963. destTopVisObjID = dt->topVisitableId();
  2964. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  2965. int turnAtNextTile = turn;
  2966. const bool destIsGuardian = sourceGuardPosition == n;
  2967. if(!goodForLandSeaTransition())
  2968. continue;
  2969. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED )
  2970. continue;
  2971. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  2972. if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableId() == Obj::BOAT)
  2973. guardedSource = false;
  2974. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
  2975. //special case -> moving from src Subterranean gate to dest gate -> it's free
  2976. if(subterraneanEntry && destTopVisObjID == Obj::SUBTERRANEAN_GATE && cp->coord.z != dp->coord.z)
  2977. cost = 0;
  2978. int remains = movement - cost;
  2979. if(useEmbarkCost)
  2980. {
  2981. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  2982. cost = movement - remains;
  2983. }
  2984. if(remains < 0)
  2985. {
  2986. //occurs rarely, when hero with low movepoints tries to leave the road
  2987. turnAtNextTile++;
  2988. int moveAtNextTile = hero->maxMovePoints(cp->land);
  2989. cost = gs->getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2990. remains = moveAtNextTile - cost;
  2991. }
  2992. if((dp->turns==0xff //we haven't been here before
  2993. || dp->turns > turnAtNextTile
  2994. || (dp->turns >= turnAtNextTile && dp->moveRemains < remains)) //this route is faster
  2995. && (!guardedSource || destIsGuardian)) // Can step into tile of guard
  2996. {
  2997. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  2998. dp->moveRemains = remains;
  2999. dp->turns = turnAtNextTile;
  3000. dp->theNodeBefore = cp;
  3001. const bool guardedDst = guardingCreaturePosition(dp->coord) != int3(-1, -1, -1)
  3002. && dp->accessible == CGPathNode::BLOCKVIS;
  3003. if (dp->accessible == CGPathNode::ACCESSIBLE
  3004. || (useEmbarkCost && allowEmbarkAndDisembark)
  3005. || destTopVisObjID == Obj::SUBTERRANEAN_GATE
  3006. || (guardedDst && !guardedSource)) // Can step into a hostile tile once.
  3007. {
  3008. mq.push_back(dp);
  3009. }
  3010. }
  3011. } //neighbours loop
  3012. } //queue loop
  3013. out.isValid = true;
  3014. }
  3015. CGPathNode *CPathfinder::getNode(const int3 &coord)
  3016. {
  3017. return &out.nodes[coord.x][coord.y][coord.z];
  3018. }
  3019. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  3020. {
  3021. return gs->checkForVisitableDir(a, b) && gs->checkForVisitableDir(b, a);
  3022. }
  3023. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const TerrainTile *tinfo) const
  3024. {
  3025. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  3026. if(tinfo->terType == ETerrainType::ROCK || !FoW[curPos.x][curPos.y][curPos.z])
  3027. return CGPathNode::BLOCKED;
  3028. if(tinfo->visitable)
  3029. {
  3030. 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
  3031. {
  3032. return CGPathNode::BLOCKED;
  3033. }
  3034. else
  3035. {
  3036. for(const CGObjectInstance *obj : tinfo->visitableObjects)
  3037. {
  3038. if(obj->passableFor(hero->tempOwner)) //special object instance specific passableness flag - overwrites other accessibility flags
  3039. {
  3040. ret = CGPathNode::ACCESSIBLE;
  3041. }
  3042. else if(obj->blockVisit)
  3043. {
  3044. return CGPathNode::BLOCKVIS;
  3045. }
  3046. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  3047. {
  3048. ret = CGPathNode::VISITABLE;
  3049. }
  3050. }
  3051. }
  3052. }
  3053. else if (gs->map->isInTheMap(guardingCreaturePosition(curPos))
  3054. && !tinfo->blocked)
  3055. {
  3056. // Monster close by; blocked visit for battle.
  3057. return CGPathNode::BLOCKVIS;
  3058. }
  3059. return ret;
  3060. }
  3061. bool CPathfinder::goodForLandSeaTransition()
  3062. {
  3063. if(cp->land != dp->land) //hero can traverse land<->sea only in special circumstances
  3064. {
  3065. if(cp->land) //from land to sea -> embark or assault hero on boat
  3066. {
  3067. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  3068. return false;
  3069. if(destTopVisObjID != Obj::HERO && destTopVisObjID != Obj::BOAT) //only boat or hero can be accessed from land
  3070. return false;
  3071. if(destTopVisObjID == Obj::BOAT)
  3072. useEmbarkCost = 1;
  3073. }
  3074. else //disembark
  3075. {
  3076. //can disembark only on coastal tiles
  3077. if(!dt->isCoastal())
  3078. return false;
  3079. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  3080. if( (dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  3081. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  3082. return false;;
  3083. useEmbarkCost = 2;
  3084. }
  3085. }
  3086. return true;
  3087. }
  3088. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero) : CGameInfoCallback(_gs, boost::optional<PlayerColor>()), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap)
  3089. {
  3090. useSubterraneanGates = true;
  3091. allowEmbarkAndDisembark = true;
  3092. }
  3093. const EVictoryLossCheckResult EVictoryLossCheckResult::NO_VICTORY_OR_LOSS = EVictoryLossCheckResult(0);
  3094. const EVictoryLossCheckResult EVictoryLossCheckResult::VICTORY_STANDARD = EVictoryLossCheckResult(1);
  3095. const EVictoryLossCheckResult EVictoryLossCheckResult::VICTORY_SPECIAL = EVictoryLossCheckResult(2);
  3096. const EVictoryLossCheckResult EVictoryLossCheckResult::LOSS_STANDARD_HEROES_AND_TOWNS = EVictoryLossCheckResult(3);
  3097. const EVictoryLossCheckResult EVictoryLossCheckResult::LOSS_STANDARD_TOWNS_AND_TIME_OVER = EVictoryLossCheckResult(4);
  3098. const EVictoryLossCheckResult EVictoryLossCheckResult::LOSS_SPECIAL = EVictoryLossCheckResult(5);
  3099. EVictoryLossCheckResult::EVictoryLossCheckResult() : intValue(0)
  3100. {
  3101. }
  3102. EVictoryLossCheckResult::EVictoryLossCheckResult(si32 intValue) : intValue(intValue)
  3103. {
  3104. }
  3105. bool EVictoryLossCheckResult::operator==(EVictoryLossCheckResult const & other) const
  3106. {
  3107. return intValue == other.intValue;
  3108. }
  3109. bool EVictoryLossCheckResult::operator!=(EVictoryLossCheckResult const & other) const
  3110. {
  3111. return intValue != other.intValue;
  3112. }
  3113. bool EVictoryLossCheckResult::victory() const
  3114. {
  3115. return *this == VICTORY_STANDARD || *this == VICTORY_SPECIAL;
  3116. }
  3117. bool EVictoryLossCheckResult::loss() const
  3118. {
  3119. return !victory();
  3120. }
  3121. std::string EVictoryLossCheckResult::toString() const
  3122. {
  3123. if(*this == EVictoryLossCheckResult::NO_VICTORY_OR_LOSS) return "No victory or loss";
  3124. else if(*this == EVictoryLossCheckResult::VICTORY_STANDARD) return "Victory standard";
  3125. else if(*this == EVictoryLossCheckResult::VICTORY_SPECIAL) return "Victory special";
  3126. else if(*this == EVictoryLossCheckResult::LOSS_STANDARD_HEROES_AND_TOWNS) return "Loss standard heroes and towns";
  3127. else if(*this == EVictoryLossCheckResult::LOSS_STANDARD_TOWNS_AND_TIME_OVER) return "Loss standard towns and time over";
  3128. else if(*this == EVictoryLossCheckResult::LOSS_SPECIAL) return "Loss special";
  3129. else return "Unknown type";
  3130. }
  3131. std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult)
  3132. {
  3133. os << victoryLossCheckResult.toString();
  3134. return os;
  3135. }