2
0

CGameState.cpp 86 KB

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