2
0

CGameState.cpp 88 KB

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