CGameState.cpp 98 KB

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