CGameState.cpp 102 KB

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