CGameState.cpp 87 KB

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