CGameState.cpp 102 KB

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