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