CGameState.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210
  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 "ArtifactUtils.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 "CModHandler.h"
  21. #include "GameSettings.h"
  22. #include "TerrainHandler.h"
  23. #include "CSkillHandler.h"
  24. #include "mapping/CMap.h"
  25. #include "mapping/CMapService.h"
  26. #include "mapObjectConstructors/CObjectClassesHandler.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 = (dynamic_cast<CGTownInstance *>(obj))->alignmentToPlayer;
  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. globalEffects.setNodeType(CBonusSystemNode::GLOBAL_EFFECTS);
  650. }
  651. CGameState::~CGameState()
  652. {
  653. map.dellNull();
  654. curB.dellNull();
  655. for(auto ptr : hpool.heroesPool) // clean hero pool
  656. ptr.second.dellNull();
  657. }
  658. void CGameState::preInit(Services * services)
  659. {
  660. this->services = services;
  661. }
  662. void CGameState::init(const IMapService * mapService, StartInfo * si, bool allowSavingRandomMap)
  663. {
  664. preInitAuto();
  665. logGlobal->info("\tUsing random seed: %d", si->seedToBeUsed);
  666. getRandomGenerator().setSeed(si->seedToBeUsed);
  667. scenarioOps = CMemorySerializer::deepCopy(*si).release();
  668. initialOpts = CMemorySerializer::deepCopy(*si).release();
  669. si = nullptr;
  670. switch(scenarioOps->mode)
  671. {
  672. case StartInfo::NEW_GAME:
  673. initNewGame(mapService, allowSavingRandomMap);
  674. break;
  675. case StartInfo::CAMPAIGN:
  676. initCampaign();
  677. break;
  678. default:
  679. logGlobal->error("Wrong mode: %d", static_cast<int>(scenarioOps->mode));
  680. return;
  681. }
  682. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  683. logGlobal->info("Map loaded!");
  684. checkMapChecksum();
  685. day = 0;
  686. logGlobal->debug("Initialization:");
  687. initGlobalBonuses();
  688. initPlayerStates();
  689. placeCampaignHeroes();
  690. initGrailPosition();
  691. initRandomFactionsForPlayers();
  692. randomizeMapObjects();
  693. placeStartingHeroes();
  694. initStartingResources();
  695. initHeroes();
  696. initStartingBonus();
  697. initTowns();
  698. placeHeroesInTowns();
  699. initMapObjects();
  700. buildBonusSystemTree();
  701. initVisitingAndGarrisonedHeroes();
  702. initFogOfWar();
  703. // Explicitly initialize static variables
  704. for(auto & elem : players)
  705. {
  706. CGKeys::playerKeyMap[elem.first] = std::set<ui8>();
  707. }
  708. for(auto & elem : teams)
  709. {
  710. CGObelisk::visited[elem.first] = 0;
  711. }
  712. logGlobal->debug("\tChecking objectives");
  713. map->checkForObjectives(); //needs to be run when all objects are properly placed
  714. auto seedAfterInit = getRandomGenerator().nextInt();
  715. logGlobal->info("Seed after init is %d (before was %d)", seedAfterInit, scenarioOps->seedToBeUsed);
  716. if(scenarioOps->seedPostInit > 0)
  717. {
  718. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  719. assert(scenarioOps->seedPostInit == seedAfterInit);
  720. }
  721. else
  722. {
  723. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  724. }
  725. }
  726. void CGameState::updateEntity(Metatype metatype, int32_t index, const JsonNode & data)
  727. {
  728. switch(metatype)
  729. {
  730. case Metatype::ARTIFACT_INSTANCE:
  731. logGlobal->error("Artifact instance update is not implemented");
  732. break;
  733. case Metatype::CREATURE_INSTANCE:
  734. logGlobal->error("Creature instance update is not implemented");
  735. break;
  736. case Metatype::HERO_INSTANCE:
  737. //index is hero type
  738. if(index >= 0 && index < map->allHeroes.size())
  739. {
  740. CGHeroInstance * hero = map->allHeroes.at(index);
  741. hero->updateFrom(data);
  742. }
  743. else
  744. {
  745. logGlobal->error("Update entity: hero index %s is out of range [%d,%d]", index, 0, map->allHeroes.size());
  746. }
  747. break;
  748. case Metatype::MAP_OBJECT_INSTANCE:
  749. if(index >= 0 && index < map->objects.size())
  750. {
  751. CGObjectInstance * obj = getObjInstance(ObjectInstanceID(index));
  752. obj->updateFrom(data);
  753. }
  754. else
  755. {
  756. logGlobal->error("Update entity: object index %s is out of range [%d,%d]", index, 0, map->objects.size());
  757. }
  758. break;
  759. default:
  760. services->updateEntity(metatype, index, data);
  761. break;
  762. }
  763. }
  764. void CGameState::updateOnLoad(StartInfo * si)
  765. {
  766. preInitAuto();
  767. scenarioOps->playerInfos = si->playerInfos;
  768. for(auto & i : si->playerInfos)
  769. gs->players[i.first].human = i.second.isControlledByHuman();
  770. }
  771. void CGameState::preInitAuto()
  772. {
  773. if(services == nullptr)
  774. {
  775. logGlobal->error("Game state preinit missing");
  776. preInit(VLC);
  777. }
  778. }
  779. void CGameState::initNewGame(const IMapService * mapService, bool allowSavingRandomMap)
  780. {
  781. if(scenarioOps->createRandomMap())
  782. {
  783. logGlobal->info("Create random map.");
  784. CStopWatch sw;
  785. // Gen map
  786. CMapGenerator mapGenerator(*scenarioOps->mapGenOptions, scenarioOps->seedToBeUsed);
  787. std::unique_ptr<CMap> randomMap = mapGenerator.generate();
  788. if(allowSavingRandomMap)
  789. {
  790. try
  791. {
  792. auto path = VCMIDirs::get().userCachePath() / "RandomMaps";
  793. boost::filesystem::create_directories(path);
  794. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  795. const std::string templateName = options->getMapTemplate()->getName();
  796. const ui32 seed = scenarioOps->seedToBeUsed;
  797. const std::string fileName = boost::str(boost::format("%s_%d.vmap") % templateName % seed );
  798. const auto fullPath = path / fileName;
  799. mapService->saveMap(randomMap, fullPath);
  800. logGlobal->info("Random map has been saved to:");
  801. logGlobal->info(fullPath.string());
  802. }
  803. catch(...)
  804. {
  805. logGlobal->error("Saving random map failed with exception");
  806. handleException();
  807. }
  808. }
  809. map = randomMap.release();
  810. // Update starting options
  811. for(int i = 0; i < map->players.size(); ++i)
  812. {
  813. const auto & playerInfo = map->players[i];
  814. if(playerInfo.canAnyonePlay())
  815. {
  816. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  817. playerSettings.compOnly = !playerInfo.canHumanPlay;
  818. playerSettings.team = playerInfo.team;
  819. playerSettings.castle = playerInfo.defaultCastle();
  820. if(playerSettings.isControlledByAI() && playerSettings.name.empty())
  821. {
  822. playerSettings.name = VLC->generaltexth->allTexts[468];
  823. }
  824. playerSettings.color = PlayerColor(i);
  825. }
  826. else
  827. {
  828. scenarioOps->playerInfos.erase(PlayerColor(i));
  829. }
  830. }
  831. logGlobal->info("Generated random map in %i ms.", sw.getDiff());
  832. }
  833. else
  834. {
  835. logGlobal->info("Open map file: %s", scenarioOps->mapname);
  836. const ResourceID mapURI(scenarioOps->mapname, EResType::MAP);
  837. map = mapService->loadMap(mapURI).release();
  838. }
  839. }
  840. void CGameState::initCampaign()
  841. {
  842. logGlobal->info("Open campaign map file: %d", scenarioOps->campState->currentMap.value());
  843. map = scenarioOps->campState->getMap();
  844. }
  845. void CGameState::checkMapChecksum()
  846. {
  847. logGlobal->info("\tOur checksum for the map: %d", map->checksum);
  848. if(scenarioOps->mapfileChecksum)
  849. {
  850. logGlobal->info("\tServer checksum for %s: %d", scenarioOps->mapname, scenarioOps->mapfileChecksum);
  851. if(map->checksum != scenarioOps->mapfileChecksum)
  852. {
  853. logGlobal->error("Wrong map checksum!!!");
  854. throw std::runtime_error("Wrong checksum");
  855. }
  856. }
  857. else
  858. {
  859. scenarioOps->mapfileChecksum = map->checksum;
  860. }
  861. }
  862. void CGameState::initGlobalBonuses()
  863. {
  864. const JsonNode & baseBonuses = VLC->settings()->getValue(EGameSettings::BONUSES_GLOBAL);
  865. logGlobal->debug("\tLoading global bonuses");
  866. for(const auto & b : baseBonuses.Struct())
  867. {
  868. auto bonus = JsonUtils::parseBonus(b.second);
  869. bonus->source = BonusSource::GLOBAL;//for all
  870. bonus->sid = -1; //there is one global object
  871. globalEffects.addNewBonus(bonus);
  872. }
  873. VLC->creh->loadCrExpBon(globalEffects);
  874. }
  875. void CGameState::initGrailPosition()
  876. {
  877. logGlobal->debug("\tPicking grail position");
  878. //pick grail location
  879. if(map->grailPos.x < 0 || map->grailRadius) //grail not set or set within a radius around some place
  880. {
  881. if(!map->grailRadius) //radius not given -> anywhere on map
  882. map->grailRadius = map->width * 2;
  883. std::vector<int3> allowedPos;
  884. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  885. // add all not blocked tiles in range
  886. for (int z = 0; z < map->levels(); z++)
  887. {
  888. for(int x = BORDER_WIDTH; x < map->width - BORDER_WIDTH ; x++)
  889. {
  890. for(int y = BORDER_WIDTH; y < map->height - BORDER_WIDTH; y++)
  891. {
  892. const TerrainTile &t = map->getTile(int3(x, y, z));
  893. if(!t.blocked
  894. && !t.visitable
  895. && t.terType->isLand()
  896. && t.terType->isPassable()
  897. && (int)map->grailPos.dist2dSQ(int3(x, y, z)) <= (map->grailRadius * map->grailRadius))
  898. allowedPos.emplace_back(x, y, z);
  899. }
  900. }
  901. }
  902. //remove tiles with holes
  903. for(auto & elem : map->objects)
  904. if(elem && elem->ID == Obj::HOLE)
  905. allowedPos -= elem->pos;
  906. if(!allowedPos.empty())
  907. {
  908. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, getRandomGenerator());
  909. }
  910. else
  911. {
  912. logGlobal->warn("Grail cannot be placed, no appropriate tile found!");
  913. }
  914. }
  915. }
  916. void CGameState::initRandomFactionsForPlayers()
  917. {
  918. logGlobal->debug("\tPicking random factions for players");
  919. for(auto & elem : scenarioOps->playerInfos)
  920. {
  921. if(elem.second.castle==-1)
  922. {
  923. auto randomID = getRandomGenerator().nextInt((int)map->players[elem.first.getNum()].allowedFactions.size() - 1);
  924. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  925. std::advance(iter, randomID);
  926. elem.second.castle = *iter;
  927. }
  928. }
  929. }
  930. void CGameState::randomizeMapObjects()
  931. {
  932. logGlobal->debug("\tRandomizing objects");
  933. for(CGObjectInstance *obj : map->objects)
  934. {
  935. if(!obj) continue;
  936. randomizeObject(obj);
  937. //handle Favouring Winds - mark tiles under it
  938. if(obj->ID == Obj::FAVORABLE_WINDS)
  939. {
  940. for (int i = 0; i < obj->getWidth() ; i++)
  941. {
  942. for (int j = 0; j < obj->getHeight() ; j++)
  943. {
  944. int3 pos = obj->pos - int3(i,j,0);
  945. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  946. }
  947. }
  948. }
  949. }
  950. }
  951. void CGameState::initPlayerStates()
  952. {
  953. logGlobal->debug("\tCreating player entries in gs");
  954. for(auto & elem : scenarioOps->playerInfos)
  955. {
  956. PlayerState & p = players[elem.first];
  957. p.color=elem.first;
  958. p.human = elem.second.isControlledByHuman();
  959. p.team = map->players[elem.first.getNum()].team;
  960. teams[p.team].id = p.team;//init team
  961. teams[p.team].players.insert(elem.first);//add player to team
  962. }
  963. }
  964. void CGameState::placeCampaignHeroes()
  965. {
  966. if (scenarioOps->campState)
  967. {
  968. // place bonus hero
  969. auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap();
  970. bool campaignGiveHero = campaignBonus && campaignBonus->type == CScenarioTravel::STravelBonus::HERO;
  971. if(campaignGiveHero)
  972. {
  973. auto playerColor = PlayerColor(campaignBonus->info1);
  974. auto it = scenarioOps->playerInfos.find(playerColor);
  975. if(it != scenarioOps->playerInfos.end())
  976. {
  977. auto heroTypeId = campaignBonus->info2;
  978. if(heroTypeId == 0xffff) // random bonus hero
  979. {
  980. heroTypeId = pickUnusedHeroTypeRandomly(playerColor);
  981. }
  982. placeStartingHero(playerColor, HeroTypeID(heroTypeId), map->players[playerColor.getNum()].posOfMainTown);
  983. }
  984. }
  985. // replace heroes placeholders
  986. auto crossoverHeroes = getCrossoverHeroesFromPreviousScenarios();
  987. if(!crossoverHeroes.heroesFromAnyPreviousScenarios.empty())
  988. {
  989. logGlobal->debug("\tGenerate list of hero placeholders");
  990. auto campaignHeroReplacements = generateCampaignHeroesToReplace(crossoverHeroes);
  991. logGlobal->debug("\tPrepare crossover heroes");
  992. prepareCrossoverHeroes(campaignHeroReplacements, scenarioOps->campState->getCurrentScenario().travelOptions);
  993. // remove same heroes on the map which will be added through crossover heroes
  994. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  995. // with the same hero type id
  996. std::vector<CGHeroInstance *> removedHeroes;
  997. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  998. {
  999. auto * hero = getUsedHero(HeroTypeID(campaignHeroReplacement.hero->subID));
  1000. if(hero)
  1001. {
  1002. removedHeroes.push_back(hero);
  1003. map->heroesOnMap -= hero;
  1004. map->objects[hero->id.getNum()] = nullptr;
  1005. map->removeBlockVisTiles(hero, true);
  1006. }
  1007. }
  1008. logGlobal->debug("\tReplace placeholders with heroes");
  1009. replaceHeroesPlaceholders(campaignHeroReplacements);
  1010. // now add removed heroes again with unused type ID
  1011. for(auto * hero : removedHeroes)
  1012. {
  1013. si32 heroTypeId = 0;
  1014. if(hero->ID == Obj::HERO)
  1015. {
  1016. heroTypeId = pickUnusedHeroTypeRandomly(hero->tempOwner);
  1017. }
  1018. else if(hero->ID == Obj::PRISON)
  1019. {
  1020. auto unusedHeroTypeIds = getUnusedAllowedHeroes();
  1021. if(!unusedHeroTypeIds.empty())
  1022. {
  1023. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, getRandomGenerator())).getNum();
  1024. }
  1025. else
  1026. {
  1027. logGlobal->error("No free hero type ID found to replace prison.");
  1028. assert(0);
  1029. }
  1030. }
  1031. else
  1032. {
  1033. assert(0); // should not happen
  1034. }
  1035. hero->subID = heroTypeId;
  1036. hero->portrait = hero->subID;
  1037. map->getEditManager()->insertObject(hero);
  1038. }
  1039. }
  1040. }
  1041. // remove hero placeholders on map
  1042. for(auto obj : map->objects)
  1043. {
  1044. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  1045. {
  1046. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  1047. map->removeBlockVisTiles(heroPlaceholder, true);
  1048. map->instanceNames.erase(obj->instanceName);
  1049. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  1050. delete heroPlaceholder;
  1051. }
  1052. }
  1053. }
  1054. void CGameState::placeStartingHero(const PlayerColor & playerColor, const HeroTypeID & heroTypeId, int3 townPos)
  1055. {
  1056. for(auto town : map->towns)
  1057. {
  1058. if(town->getPosition() == townPos)
  1059. {
  1060. townPos = town->visitablePos();
  1061. break;
  1062. }
  1063. }
  1064. CGObjectInstance * hero = createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor);
  1065. hero->pos += hero->getVisitableOffset();
  1066. map->getEditManager()->insertObject(hero);
  1067. }
  1068. CGameState::CrossoverHeroesList CGameState::getCrossoverHeroesFromPreviousScenarios() const
  1069. {
  1070. CrossoverHeroesList crossoverHeroes;
  1071. auto campaignState = scenarioOps->campState;
  1072. auto bonus = campaignState->getBonusForCurrentMap();
  1073. if(bonus && bonus->type == CScenarioTravel::STravelBonus::HEROES_FROM_PREVIOUS_SCENARIO)
  1074. {
  1075. std::vector<CGHeroInstance *> heroes;
  1076. for(auto & node : campaignState->camp->scenarios[bonus->info2].crossoverHeroes)
  1077. {
  1078. auto * h = CCampaignState::crossoverDeserialize(node);
  1079. heroes.push_back(h);
  1080. }
  1081. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = heroes;
  1082. }
  1083. else
  1084. {
  1085. if(!campaignState->mapsConquered.empty())
  1086. {
  1087. std::vector<CGHeroInstance *> heroes = {};
  1088. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = heroes;
  1089. crossoverHeroes.heroesFromPreviousScenario = heroes;
  1090. for(auto mapNr : campaignState->mapsConquered)
  1091. {
  1092. // create a list of deleted heroes
  1093. auto & scenario = campaignState->camp->scenarios[mapNr];
  1094. auto lostCrossoverHeroes = scenario.getLostCrossoverHeroes();
  1095. // remove heroes which didn't reached the end of the scenario, but were available at the start
  1096. for(auto * hero : lostCrossoverHeroes)
  1097. {
  1098. // auto hero = CCampaignState::crossoverDeserialize(node);
  1099. vstd::erase_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  1100. {
  1101. return hero->subID == h->subID;
  1102. });
  1103. }
  1104. // now add heroes which completed the scenario
  1105. for(auto node : scenario.crossoverHeroes)
  1106. {
  1107. auto * hero = CCampaignState::crossoverDeserialize(node);
  1108. // add new heroes and replace old heroes with newer ones
  1109. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  1110. {
  1111. return hero->subID == h->subID;
  1112. });
  1113. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  1114. {
  1115. // replace old hero with newer one
  1116. crossoverHeroes.heroesFromAnyPreviousScenarios[it - crossoverHeroes.heroesFromAnyPreviousScenarios.begin()] = hero;
  1117. }
  1118. else
  1119. {
  1120. // add new hero
  1121. crossoverHeroes.heroesFromAnyPreviousScenarios.push_back(hero);
  1122. }
  1123. if(mapNr == campaignState->mapsConquered.back())
  1124. {
  1125. crossoverHeroes.heroesFromPreviousScenario.push_back(hero);
  1126. }
  1127. }
  1128. }
  1129. }
  1130. }
  1131. return crossoverHeroes;
  1132. }
  1133. void CGameState::prepareCrossoverHeroes(std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions)
  1134. {
  1135. // create heroes list for convenience iterating
  1136. std::vector<CGHeroInstance *> crossoverHeroes;
  1137. crossoverHeroes.reserve(campaignHeroReplacements.size());
  1138. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  1139. {
  1140. crossoverHeroes.push_back(campaignHeroReplacement.hero);
  1141. }
  1142. // TODO replace magic numbers with named constants
  1143. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  1144. if(!travelOptions.whatHeroKeeps.experience)
  1145. {
  1146. //trimming experience
  1147. for(CGHeroInstance * cgh : crossoverHeroes)
  1148. {
  1149. cgh->initExp(getRandomGenerator());
  1150. }
  1151. }
  1152. if(!travelOptions.whatHeroKeeps.primarySkills)
  1153. {
  1154. //trimming prim skills
  1155. for(CGHeroInstance * cgh : crossoverHeroes)
  1156. {
  1157. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1158. {
  1159. auto sel = Selector::type()(BonusType::PRIMARY_SKILL)
  1160. .And(Selector::subtype()(g))
  1161. .And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL));
  1162. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  1163. }
  1164. }
  1165. }
  1166. if(!travelOptions.whatHeroKeeps.secondarySkills)
  1167. {
  1168. //trimming sec skills
  1169. for(CGHeroInstance * cgh : crossoverHeroes)
  1170. {
  1171. cgh->secSkills = cgh->type->secSkillsInit;
  1172. cgh->recreateSecondarySkillsBonuses();
  1173. }
  1174. }
  1175. if(!travelOptions.whatHeroKeeps.spells)
  1176. {
  1177. for(CGHeroInstance * cgh : crossoverHeroes)
  1178. {
  1179. cgh->removeSpellbook();
  1180. }
  1181. }
  1182. if(!travelOptions.whatHeroKeeps.artifacts)
  1183. {
  1184. //trimming artifacts
  1185. for(CGHeroInstance * hero : crossoverHeroes)
  1186. {
  1187. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  1188. for (size_t i = 0; i < totalArts; i++ )
  1189. {
  1190. auto artifactPosition = ArtifactPosition((si32)i);
  1191. if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
  1192. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  1193. if(!info)
  1194. continue;
  1195. // TODO: why would there be nullptr artifacts?
  1196. const CArtifactInstance *art = info->artifact;
  1197. if(!art)
  1198. continue;
  1199. bool takeable = travelOptions.artifactsKeptByHero.count(art->artType->getId());
  1200. ArtifactLocation al(hero, artifactPosition);
  1201. if(!takeable && !al.getSlot()->locked) //don't try removing locked artifacts -> it crashes #1719
  1202. al.removeArtifact();
  1203. }
  1204. }
  1205. }
  1206. //trimming creatures
  1207. for(CGHeroInstance * cgh : crossoverHeroes)
  1208. {
  1209. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  1210. {
  1211. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  1212. return !travelOptions.monstersKeptByHero.count(crid);
  1213. };
  1214. auto stacksCopy = cgh->stacks; //copy of the map, so we can iterate iover it and remove stacks
  1215. for(auto &slotPair : stacksCopy)
  1216. if(shouldSlotBeErased(slotPair))
  1217. cgh->eraseStack(slotPair.first);
  1218. }
  1219. // Removing short-term bonuses
  1220. for(CGHeroInstance * cgh : crossoverHeroes)
  1221. {
  1222. cgh->removeBonusesRecursive(CSelector(Bonus::OneDay)
  1223. .Or(CSelector(Bonus::OneWeek))
  1224. .Or(CSelector(Bonus::NTurns))
  1225. .Or(CSelector(Bonus::NDays))
  1226. .Or(CSelector(Bonus::OneBattle)));
  1227. }
  1228. }
  1229. void CGameState::placeStartingHeroes()
  1230. {
  1231. logGlobal->debug("\tGiving starting hero");
  1232. for(auto & playerSettingPair : scenarioOps->playerInfos)
  1233. {
  1234. auto playerColor = playerSettingPair.first;
  1235. auto & playerInfo = map->players[playerColor.getNum()];
  1236. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  1237. {
  1238. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  1239. if(scenarioOps->campState)
  1240. {
  1241. if(auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap())
  1242. {
  1243. if(campaignBonus->type == CScenarioTravel::STravelBonus::HERO && playerColor == PlayerColor(campaignBonus->info1))
  1244. continue;
  1245. }
  1246. }
  1247. int heroTypeId = pickNextHeroType(playerColor);
  1248. if(playerSettingPair.second.hero == -1)
  1249. playerSettingPair.second.hero = heroTypeId;
  1250. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  1251. }
  1252. }
  1253. }
  1254. void CGameState::initStartingResources()
  1255. {
  1256. logGlobal->debug("\tSetting up resources");
  1257. const JsonNode config(ResourceID("config/startres.json"));
  1258. const JsonVector &vector = config["difficulty"].Vector();
  1259. const JsonNode &level = vector[scenarioOps->difficulty];
  1260. TResources startresAI(level["ai"]);
  1261. TResources startresHuman(level["human"]);
  1262. for (auto & elem : players)
  1263. {
  1264. PlayerState &p = elem.second;
  1265. if (p.human)
  1266. p.resources = startresHuman;
  1267. else
  1268. p.resources = startresAI;
  1269. }
  1270. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  1271. {
  1272. std::vector<const PlayerSettings *> ret;
  1273. for(const auto & playerInfo : scenarioOps->playerInfos)
  1274. {
  1275. if(playerInfo.second.isControlledByHuman())
  1276. ret.push_back(&playerInfo.second);
  1277. }
  1278. return ret;
  1279. };
  1280. //give start resource bonus in case of campaign
  1281. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1282. {
  1283. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1284. if(chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1285. {
  1286. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1287. for(const PlayerSettings *ps : people)
  1288. {
  1289. std::vector<int> res; //resources we will give
  1290. switch (chosenBonus->info1)
  1291. {
  1292. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1293. res.push_back(chosenBonus->info1);
  1294. break;
  1295. case 0xFD: //wood+ore
  1296. res.push_back(GameResID(EGameResID::WOOD));
  1297. res.push_back(GameResID(EGameResID::ORE));
  1298. break;
  1299. case 0xFE: //rare
  1300. res.push_back(GameResID(EGameResID::MERCURY));
  1301. res.push_back(GameResID(EGameResID::SULFUR));
  1302. res.push_back(GameResID(EGameResID::CRYSTAL));
  1303. res.push_back(GameResID(EGameResID::GEMS));
  1304. break;
  1305. default:
  1306. assert(0);
  1307. break;
  1308. }
  1309. //increasing resource quantity
  1310. for (auto & re : res)
  1311. {
  1312. players[ps->color].resources[re] += chosenBonus->info2;
  1313. }
  1314. }
  1315. }
  1316. }
  1317. }
  1318. void CGameState::initHeroes()
  1319. {
  1320. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1321. {
  1322. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  1323. {
  1324. logGlobal->warn("Hero with uninitialized owner!");
  1325. continue;
  1326. }
  1327. hero->initHero(getRandomGenerator());
  1328. getPlayerState(hero->getOwner())->heroes.push_back(hero);
  1329. map->allHeroes[hero->type->getIndex()] = hero;
  1330. }
  1331. for(auto obj : map->objects) //prisons
  1332. {
  1333. if(obj && obj->ID == Obj::PRISON)
  1334. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  1335. }
  1336. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  1337. for(auto ph : map->predefinedHeroes)
  1338. {
  1339. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  1340. continue;
  1341. ph->initHero(getRandomGenerator());
  1342. hpool.heroesPool[ph->subID] = ph;
  1343. hpool.pavailable[ph->subID] = 0xff;
  1344. heroesToCreate.erase(ph->type->getId());
  1345. map->allHeroes[ph->subID] = ph;
  1346. }
  1347. for(const HeroTypeID & htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  1348. {
  1349. auto * vhi = new CGHeroInstance();
  1350. vhi->initHero(getRandomGenerator(), htype);
  1351. int typeID = htype.getNum();
  1352. map->allHeroes[typeID] = vhi;
  1353. hpool.heroesPool[typeID] = vhi;
  1354. hpool.pavailable[typeID] = 0xff;
  1355. }
  1356. for(auto & elem : map->disposedHeroes)
  1357. {
  1358. hpool.pavailable[elem.heroId] = elem.players;
  1359. }
  1360. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1361. {
  1362. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1363. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1364. {
  1365. //find human player
  1366. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  1367. for (auto & elem : players)
  1368. {
  1369. if(elem.second.human)
  1370. {
  1371. humanPlayer = elem.first;
  1372. break;
  1373. }
  1374. }
  1375. assert(humanPlayer != PlayerColor::NEUTRAL);
  1376. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1377. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1378. {
  1379. int maxB = -1;
  1380. for (int b=0; b<heroes.size(); ++b)
  1381. {
  1382. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1383. {
  1384. maxB = b;
  1385. }
  1386. }
  1387. if(maxB < 0)
  1388. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  1389. else
  1390. giveCampaignBonusToHero(heroes[maxB]);
  1391. }
  1392. else //specific hero
  1393. {
  1394. for (auto & heroe : heroes)
  1395. {
  1396. if (heroe->subID == chosenBonus->info1)
  1397. {
  1398. giveCampaignBonusToHero(heroe);
  1399. break;
  1400. }
  1401. }
  1402. }
  1403. }
  1404. }
  1405. }
  1406. void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero)
  1407. {
  1408. const std::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
  1409. if(!curBonus)
  1410. return;
  1411. if(curBonus->isBonusForHero())
  1412. {
  1413. //apply bonus
  1414. switch (curBonus->type)
  1415. {
  1416. case CScenarioTravel::STravelBonus::SPELL:
  1417. hero->addSpellToSpellbook(SpellID(curBonus->info2));
  1418. break;
  1419. case CScenarioTravel::STravelBonus::MONSTER:
  1420. {
  1421. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  1422. {
  1423. if(hero->slotEmpty(SlotID(i)))
  1424. {
  1425. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  1426. break;
  1427. }
  1428. }
  1429. }
  1430. break;
  1431. case CScenarioTravel::STravelBonus::ARTIFACT:
  1432. if(!gs->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2)))
  1433. logGlobal->error("Cannot give starting artifact - no free slots!");
  1434. break;
  1435. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  1436. {
  1437. CArtifactInstance * scroll = ArtifactUtils::createScroll(SpellID(curBonus->info2));
  1438. const auto slot = ArtifactUtils::getArtAnyPosition(hero, scroll->getTypeId());
  1439. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  1440. scroll->putAt(ArtifactLocation(hero, slot));
  1441. else
  1442. logGlobal->error("Cannot give starting scroll - no free slots!");
  1443. }
  1444. break;
  1445. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  1446. {
  1447. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus->info2);
  1448. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1449. {
  1450. int val = ptr[g];
  1451. if (val == 0)
  1452. {
  1453. continue;
  1454. }
  1455. auto bb = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::PRIMARY_SKILL, BonusSource::CAMPAIGN_BONUS, val, *scenarioOps->campState->currentMap, g);
  1456. hero->addNewBonus(bb);
  1457. }
  1458. }
  1459. break;
  1460. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  1461. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  1462. break;
  1463. }
  1464. }
  1465. }
  1466. void CGameState::initFogOfWar()
  1467. {
  1468. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  1469. int layers = map->levels();
  1470. for(auto & elem : teams)
  1471. {
  1472. auto fow = elem.second.fogOfWarMap;
  1473. fow->resize(boost::extents[layers][map->width][map->height]);
  1474. std::fill(fow->data(), fow->data() + fow->num_elements(), 0);
  1475. for(CGObjectInstance *obj : map->objects)
  1476. {
  1477. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  1478. std::unordered_set<int3> tiles;
  1479. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), obj->tempOwner, 1);
  1480. for(const int3 & tile : tiles)
  1481. {
  1482. (*elem.second.fogOfWarMap)[tile.z][tile.x][tile.y] = 1;
  1483. }
  1484. }
  1485. }
  1486. }
  1487. void CGameState::initStartingBonus()
  1488. {
  1489. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1490. return;
  1491. // These are the single scenario bonuses; predefined
  1492. // campaign bonuses are spread out over other init* functions.
  1493. logGlobal->debug("\tStarting bonuses");
  1494. for(auto & elem : players)
  1495. {
  1496. //starting bonus
  1497. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  1498. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(getRandomGenerator().nextInt(2));
  1499. switch(scenarioOps->playerInfos[elem.first].bonus)
  1500. {
  1501. case PlayerSettings::GOLD:
  1502. elem.second.resources[EGameResID::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  1503. break;
  1504. case PlayerSettings::RESOURCE:
  1505. {
  1506. auto res = (*VLC->townh)[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  1507. if(res == EGameResID::WOOD_AND_ORE)
  1508. {
  1509. int amount = getRandomGenerator().nextInt(5, 10);
  1510. elem.second.resources[EGameResID::WOOD] += amount;
  1511. elem.second.resources[EGameResID::ORE] += amount;
  1512. }
  1513. else
  1514. {
  1515. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  1516. }
  1517. break;
  1518. }
  1519. case PlayerSettings::ARTIFACT:
  1520. {
  1521. if(elem.second.heroes.empty())
  1522. {
  1523. logGlobal->error("Cannot give starting artifact - no heroes!");
  1524. break;
  1525. }
  1526. const Artifact * toGive = VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE).toArtifact(VLC->artifacts());
  1527. CGHeroInstance *hero = elem.second.heroes[0];
  1528. if(!giveHeroArtifact(hero, toGive->getId()))
  1529. logGlobal->error("Cannot give starting artifact - no free slots!");
  1530. }
  1531. break;
  1532. }
  1533. }
  1534. }
  1535. void CGameState::initTowns()
  1536. {
  1537. logGlobal->debug("\tTowns");
  1538. //campaign bonuses for towns
  1539. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1540. {
  1541. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1542. if (chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1543. {
  1544. for (int g=0; g<map->towns.size(); ++g)
  1545. {
  1546. PlayerState * owner = getPlayerState(map->towns[g]->getOwner());
  1547. if (owner)
  1548. {
  1549. PlayerInfo & pi = map->players[owner->color.getNum()];
  1550. if (owner->human && //human-owned
  1551. map->towns[g]->pos == pi.posOfMainTown)
  1552. {
  1553. BuildingID buildingId;
  1554. if(scenarioOps->campState->camp->header.version == CampaignVersion::VCMI)
  1555. buildingId = BuildingID(chosenBonus->info1);
  1556. else
  1557. buildingId = CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->subID, map->towns[g]->builtBuildings);
  1558. map->towns[g]->builtBuildings.insert(buildingId);
  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. static const 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 };
  1581. static const BuildingID upgradedDwellings[] = { BuildingID::DWELL_UP_FIRST, BuildingID::DWELL_LVL_2_UP, BuildingID::DWELL_LVL_3_UP, BuildingID::DWELL_LVL_4_UP, BuildingID::DWELL_LVL_5_UP, BuildingID::DWELL_LVL_6_UP, BuildingID::DWELL_LVL_7_UP };
  1582. static const BuildingID hordes[] = { BuildingID::HORDE_PLACEHOLDER1, BuildingID::HORDE_PLACEHOLDER2, BuildingID::HORDE_PLACEHOLDER3, BuildingID::HORDE_PLACEHOLDER4, BuildingID::HORDE_PLACEHOLDER5, BuildingID::HORDE_PLACEHOLDER6, BuildingID::HORDE_PLACEHOLDER7 };
  1583. //init buildings
  1584. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  1585. {
  1586. vti->builtBuildings.erase(BuildingID::DEFAULT);
  1587. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1588. if(vti->tempOwner != PlayerColor::NEUTRAL)
  1589. vti->builtBuildings.insert(BuildingID::TAVERN);
  1590. auto definesBuildingsChances = VLC->settings()->getVector(EGameSettings::TOWNS_STARTING_DWELLING_CHANCES);
  1591. for(int i = 0; i < definesBuildingsChances.size(); i++)
  1592. {
  1593. if((getRandomGenerator().nextInt(1,100) <= definesBuildingsChances[i]))
  1594. {
  1595. vti->builtBuildings.insert(basicDwellings[i]);
  1596. }
  1597. }
  1598. }
  1599. // village hall must always exist
  1600. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1601. //init hordes
  1602. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  1603. {
  1604. if (vstd::contains(vti->builtBuildings, hordes[i])) //if we have horde for this level
  1605. {
  1606. vti->builtBuildings.erase(hordes[i]);//remove old ID
  1607. if (vti->getTown()->hordeLvl.at(0) == i)//if town first horde is this one
  1608. {
  1609. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  1610. //if we have upgraded dwelling as well
  1611. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  1612. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  1613. }
  1614. if (vti->getTown()->hordeLvl.at(1) == i)//if town second horde is this one
  1615. {
  1616. vti->builtBuildings.insert(BuildingID::HORDE_2);
  1617. if (vstd::contains(vti->builtBuildings, upgradedDwellings[i]))
  1618. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  1619. }
  1620. }
  1621. }
  1622. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  1623. //But DO NOT remove horde placeholders before they are replaced
  1624. vstd::erase_if(vti->builtBuildings, [vti](const BuildingID & bid)
  1625. {
  1626. return !vti->getTown()->buildings.count(bid) || !vti->getTown()->buildings.at(bid);
  1627. });
  1628. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  1629. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1630. //Early check for #1444-like problems
  1631. for([[maybe_unused]] const auto & building : vti->builtBuildings)
  1632. {
  1633. assert(vti->getTown()->buildings.at(building) != nullptr);
  1634. }
  1635. //town events
  1636. for(CCastleEvent &ev : vti->events)
  1637. {
  1638. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1639. if (vstd::contains(ev.buildings,hordes[i])) //if we have horde for this level
  1640. {
  1641. ev.buildings.erase(hordes[i]);
  1642. if (vti->getTown()->hordeLvl.at(0) == i)
  1643. ev.buildings.insert(BuildingID::HORDE_1);
  1644. if (vti->getTown()->hordeLvl.at(1) == i)
  1645. ev.buildings.insert(BuildingID::HORDE_2);
  1646. }
  1647. }
  1648. //init spells
  1649. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1650. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1651. {
  1652. const auto * s = vti->obligatorySpells[z].toSpell();
  1653. vti->spells[s->level-1].push_back(s->id);
  1654. vti->possibleSpells -= s->id;
  1655. }
  1656. while(!vti->possibleSpells.empty())
  1657. {
  1658. ui32 total=0;
  1659. int sel = -1;
  1660. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1661. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1662. if (total == 0) // remaining spells have 0 probability
  1663. break;
  1664. auto r = getRandomGenerator().nextInt(total - 1);
  1665. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1666. {
  1667. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->getFaction());
  1668. if(r<0)
  1669. {
  1670. sel = ps;
  1671. break;
  1672. }
  1673. }
  1674. if(sel<0)
  1675. sel=0;
  1676. const auto * s = vti->possibleSpells[sel].toSpell();
  1677. vti->spells[s->level-1].push_back(s->id);
  1678. vti->possibleSpells -= s->id;
  1679. }
  1680. vti->possibleSpells.clear();
  1681. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1682. getPlayerState(vti->getOwner())->towns.emplace_back(vti);
  1683. }
  1684. }
  1685. void CGameState::initMapObjects()
  1686. {
  1687. logGlobal->debug("\tObject initialization");
  1688. // objCaller->preInit();
  1689. for(CGObjectInstance *obj : map->objects)
  1690. {
  1691. if(obj)
  1692. {
  1693. logGlobal->trace("Calling Init for object %d, %s, %s", obj->id.getNum(), obj->typeName, obj->subTypeName);
  1694. obj->initObj(getRandomGenerator());
  1695. }
  1696. }
  1697. for(CGObjectInstance *obj : map->objects)
  1698. {
  1699. if(!obj)
  1700. continue;
  1701. switch (obj->ID)
  1702. {
  1703. case Obj::QUEST_GUARD:
  1704. case Obj::SEER_HUT:
  1705. {
  1706. auto * q = dynamic_cast<CGSeerHut *>(obj);
  1707. assert (q);
  1708. q->setObjToKill();
  1709. }
  1710. }
  1711. }
  1712. CGSubterraneanGate::postInit(); //pairing subterranean gates
  1713. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  1714. }
  1715. void CGameState::placeHeroesInTowns()
  1716. {
  1717. for(auto & player : players)
  1718. {
  1719. if(player.first == PlayerColor::NEUTRAL)
  1720. continue;
  1721. for(CGHeroInstance * h : player.second.heroes)
  1722. {
  1723. for(CGTownInstance * t : player.second.towns)
  1724. {
  1725. if(h->visitablePos().z != t->visitablePos().z)
  1726. continue;
  1727. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos().x, h->visitablePos().y);
  1728. // current hero position is at one of blocking tiles of current town
  1729. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  1730. if (heroOnTownBlockableTile)
  1731. {
  1732. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  1733. map->removeBlockVisTiles(h);
  1734. h->pos = correctedPos;
  1735. map->addBlockVisTiles(h);
  1736. assert(t->visitableAt(h->visitablePos().x, h->visitablePos().y));
  1737. }
  1738. }
  1739. }
  1740. }
  1741. }
  1742. void CGameState::initVisitingAndGarrisonedHeroes()
  1743. {
  1744. for(auto & player : players)
  1745. {
  1746. if(player.first == PlayerColor::NEUTRAL)
  1747. continue;
  1748. //init visiting and garrisoned heroes
  1749. for(CGHeroInstance * h : player.second.heroes)
  1750. {
  1751. for(CGTownInstance * t : player.second.towns)
  1752. {
  1753. if(h->visitablePos().z != t->visitablePos().z)
  1754. continue;
  1755. if (t->visitableAt(h->visitablePos().x, h->visitablePos().y))
  1756. {
  1757. assert(t->visitingHero == nullptr);
  1758. t->setVisitingHero(h);
  1759. }
  1760. }
  1761. }
  1762. }
  1763. for (auto hero : map->heroesOnMap)
  1764. {
  1765. if (hero->visitedTown)
  1766. {
  1767. assert (hero->visitedTown->visitingHero == hero);
  1768. }
  1769. }
  1770. }
  1771. BattleField CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  1772. {
  1773. if(!tile.valid() && curB)
  1774. tile = curB->tile;
  1775. else if(!tile.valid() && !curB)
  1776. return BattleField::NONE;
  1777. const TerrainTile &t = map->getTile(tile);
  1778. auto * topObject = t.visitableObjects.front();
  1779. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  1780. {
  1781. return topObject->getBattlefield();
  1782. }
  1783. for(auto &obj : map->objects)
  1784. {
  1785. //look only for objects covering given tile
  1786. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  1787. continue;
  1788. auto customBattlefield = obj->getBattlefield();
  1789. if(customBattlefield != BattleField::NONE)
  1790. return customBattlefield;
  1791. }
  1792. if(map->isCoastalTile(tile)) //coastal tile is always ground
  1793. return BattleField::fromString("sand_shore");
  1794. return BattleField(*RandomGeneratorUtil::nextItem(t.terType->battleFields, rand));
  1795. }
  1796. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  1797. {
  1798. assert(obj);
  1799. assert(obj->hasStackAtSlot(stackPos));
  1800. out = fillUpgradeInfo(obj->getStack(stackPos));
  1801. }
  1802. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance &stack) const
  1803. {
  1804. UpgradeInfo ret;
  1805. const CCreature *base = stack.type;
  1806. const CGHeroInstance * h = stack.armyObj->ID == Obj::HERO ? dynamic_cast<const CGHeroInstance *>(stack.armyObj) : nullptr;
  1807. const CGTownInstance *t = nullptr;
  1808. if(stack.armyObj->ID == Obj::TOWN)
  1809. t = dynamic_cast<const CGTownInstance *>(stack.armyObj);
  1810. else if(h)
  1811. { //hero specialty
  1812. TConstBonusListPtr lista = h->getBonuses(Selector::typeSubtype(BonusType::SPECIAL_UPGRADE, base->getId()));
  1813. for(const auto & it : *lista)
  1814. {
  1815. auto nid = CreatureID(it->additionalInfo[0]);
  1816. if (nid != base->getId()) //in very specific case the upgrade is available by default (?)
  1817. {
  1818. ret.newID.push_back(nid);
  1819. ret.cost.push_back(nid.toCreature()->getFullRecruitCost() - base->getFullRecruitCost());
  1820. }
  1821. }
  1822. t = h->visitedTown;
  1823. }
  1824. if(t)
  1825. {
  1826. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : t->creatures)
  1827. {
  1828. if (vstd::contains(dwelling.second, base->getId())) //Dwelling with our creature
  1829. {
  1830. for(const auto & upgrID : dwelling.second)
  1831. {
  1832. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1833. {
  1834. ret.newID.push_back(upgrID);
  1835. ret.cost.push_back(upgrID.toCreature()->getFullRecruitCost() - base->getFullRecruitCost());
  1836. }
  1837. }
  1838. }
  1839. }
  1840. }
  1841. //hero is visiting Hill Fort
  1842. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == Obj::HILL_FORT)
  1843. {
  1844. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1845. const int costModifier = costModifiers[std::min<int>(std::max((int)base->getLevel() - 1, 0), std::size(costModifiers) - 1)];
  1846. for(const auto & nid : base->upgrades)
  1847. {
  1848. ret.newID.push_back(nid);
  1849. ret.cost.push_back((nid.toCreature()->getFullRecruitCost() - base->getFullRecruitCost()) * costModifier / 100);
  1850. }
  1851. }
  1852. if(!ret.newID.empty())
  1853. ret.oldID = base->getId();
  1854. for (ResourceSet &cost : ret.cost)
  1855. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1856. return ret;
  1857. }
  1858. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  1859. {
  1860. if ( color1 == color2 )
  1861. return PlayerRelations::SAME_PLAYER;
  1862. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1863. return PlayerRelations::ENEMIES;
  1864. const TeamState * ts = getPlayerTeam(color1);
  1865. if (ts && vstd::contains(ts->players, color2))
  1866. return PlayerRelations::ALLIES;
  1867. return PlayerRelations::ENEMIES;
  1868. }
  1869. void CGameState::apply(CPack *pack)
  1870. {
  1871. ui16 typ = typeList.getTypeID(pack);
  1872. applier->getApplier(typ)->applyOnGS(this, pack);
  1873. }
  1874. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  1875. {
  1876. calculatePaths(std::make_shared<SingleHeroPathfinderConfig>(out, this, hero));
  1877. }
  1878. void CGameState::calculatePaths(const std::shared_ptr<PathfinderConfig> & config)
  1879. {
  1880. //FIXME: creating pathfinder is costly, maybe reset / clear is enough?
  1881. CPathfinder pathfinder(this, config);
  1882. pathfinder.calculatePaths();
  1883. }
  1884. /**
  1885. * Tells if the tile is guarded by a monster as well as the position
  1886. * of the monster that will attack on it.
  1887. *
  1888. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1889. * the monster guarding the tile.
  1890. */
  1891. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1892. {
  1893. std::vector<CGObjectInstance*> guards;
  1894. const int3 originalPos = pos;
  1895. if (!map->isInTheMap(pos))
  1896. return guards;
  1897. const TerrainTile &posTile = map->getTile(pos);
  1898. if (posTile.visitable)
  1899. {
  1900. for (CGObjectInstance* obj : posTile.visitableObjects)
  1901. {
  1902. if(obj->blockVisit)
  1903. {
  1904. if (obj->ID == Obj::MONSTER) // Monster
  1905. guards.push_back(obj);
  1906. }
  1907. }
  1908. }
  1909. pos -= int3(1, 1, 0); // Start with top left.
  1910. for (int dx = 0; dx < 3; dx++)
  1911. {
  1912. for (int dy = 0; dy < 3; dy++)
  1913. {
  1914. if (map->isInTheMap(pos))
  1915. {
  1916. const auto & tile = map->getTile(pos);
  1917. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1918. {
  1919. for (CGObjectInstance* obj : tile.visitableObjects)
  1920. {
  1921. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1922. {
  1923. guards.push_back(obj);
  1924. }
  1925. }
  1926. }
  1927. }
  1928. pos.y++;
  1929. }
  1930. pos.y -= 3;
  1931. pos.x++;
  1932. }
  1933. return guards;
  1934. }
  1935. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1936. {
  1937. return gs->map->guardingCreaturePositions[pos.z][pos.x][pos.y];
  1938. }
  1939. void CGameState::updateRumor()
  1940. {
  1941. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1942. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1943. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1944. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1945. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1946. int rumorId = -1;
  1947. int rumorExtra = -1;
  1948. auto & rand = getRandomGenerator();
  1949. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1950. do
  1951. {
  1952. switch(rumor.type)
  1953. {
  1954. case RumorState::TYPE_SPECIAL:
  1955. {
  1956. SThievesGuildInfo tgi;
  1957. obtainPlayersStats(tgi, 20);
  1958. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1959. if(rumorId == RumorState::RUMOR_GRAIL)
  1960. {
  1961. rumorExtra = getTile(map->grailPos)->terType->getIndex();
  1962. break;
  1963. }
  1964. std::vector<PlayerColor> players = {};
  1965. switch(rumorId)
  1966. {
  1967. case RumorState::RUMOR_OBELISKS:
  1968. players = tgi.obelisks[0];
  1969. break;
  1970. case RumorState::RUMOR_ARTIFACTS:
  1971. players = tgi.artifacts[0];
  1972. break;
  1973. case RumorState::RUMOR_ARMY:
  1974. players = tgi.army[0];
  1975. break;
  1976. case RumorState::RUMOR_INCOME:
  1977. players = tgi.income[0];
  1978. break;
  1979. }
  1980. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1981. break;
  1982. }
  1983. case RumorState::TYPE_MAP:
  1984. // Makes sure that map rumors only used if there enough rumors too choose from
  1985. if(!map->rumors.empty() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1986. {
  1987. rumorId = rand.nextInt((int)map->rumors.size() - 1);
  1988. break;
  1989. }
  1990. else
  1991. rumor.type = RumorState::TYPE_RAND;
  1992. [[fallthrough]];
  1993. case RumorState::TYPE_RAND:
  1994. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randtvrn");
  1995. rumorId = rand.nextInt((int)vector.size() - 1);
  1996. break;
  1997. }
  1998. }
  1999. while(!rumor.update(rumorId, rumorExtra));
  2000. }
  2001. bool CGameState::isVisible(int3 pos, const std::optional<PlayerColor> & player) const
  2002. {
  2003. if (!map->isInTheMap(pos))
  2004. return false;
  2005. if (!player)
  2006. return true;
  2007. if(player == PlayerColor::NEUTRAL)
  2008. return false;
  2009. if(player->isSpectator())
  2010. return true;
  2011. return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y];
  2012. }
  2013. bool CGameState::isVisible(const CGObjectInstance * obj, const std::optional<PlayerColor> & player) const
  2014. {
  2015. if(!player)
  2016. return true;
  2017. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  2018. if (player == obj->tempOwner)
  2019. return true;
  2020. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  2021. return false;
  2022. //object is visible when at least one blocked tile is visible
  2023. for(int fy=0; fy < obj->getHeight(); ++fy)
  2024. {
  2025. for(int fx=0; fx < obj->getWidth(); ++fx)
  2026. {
  2027. int3 pos = obj->pos + int3(-fx, -fy, 0);
  2028. if ( map->isInTheMap(pos) &&
  2029. obj->coveringAt(pos.x, pos.y) &&
  2030. isVisible(pos, *player))
  2031. return true;
  2032. }
  2033. }
  2034. return false;
  2035. }
  2036. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2037. {
  2038. const TerrainTile * pom = &map->getTile(dst);
  2039. return map->checkForVisitableDir(src, pom, dst);
  2040. }
  2041. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(const PlayerColor & player) const
  2042. {
  2043. const std::string & messageWonSelf = VLC->generaltexth->allTexts[659];
  2044. const std::string & messageWonOther = VLC->generaltexth->allTexts[5];
  2045. const std::string & messageLostSelf = VLC->generaltexth->allTexts[7];
  2046. const std::string & messageLostOther = VLC->generaltexth->allTexts[8];
  2047. auto evaluateEvent = [=](const EventCondition & condition)
  2048. {
  2049. return this->checkForVictory(player, condition);
  2050. };
  2051. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  2052. //cheater or tester, but has entered the code...
  2053. if (p->enteredWinningCheatCode)
  2054. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  2055. if (p->enteredLosingCheatCode)
  2056. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  2057. for (const TriggeredEvent & event : map->triggeredEvents)
  2058. {
  2059. if (event.trigger.test(evaluateEvent))
  2060. {
  2061. if (event.effect.type == EventEffect::VICTORY)
  2062. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  2063. if (event.effect.type == EventEffect::DEFEAT)
  2064. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  2065. }
  2066. }
  2067. if (checkForStandardLoss(player))
  2068. {
  2069. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  2070. }
  2071. return EVictoryLossCheckResult();
  2072. }
  2073. bool CGameState::checkForVictory(const PlayerColor & player, const EventCondition & condition) const
  2074. {
  2075. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  2076. switch (condition.condition)
  2077. {
  2078. case EventCondition::STANDARD_WIN:
  2079. {
  2080. return player == checkForStandardWin();
  2081. }
  2082. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  2083. {
  2084. for(const auto & elem : p->heroes)
  2085. if(elem->hasArt(ArtifactID(condition.objectType)))
  2086. return true;
  2087. return false;
  2088. }
  2089. case EventCondition::HAVE_CREATURES:
  2090. {
  2091. //check if in players armies there is enough creatures
  2092. int total = 0; //creature counter
  2093. for(auto object : map->objects)
  2094. {
  2095. const CArmedInstance *ai = nullptr;
  2096. if(object
  2097. && object->tempOwner == player //object controlled by player
  2098. && (ai = dynamic_cast<const CArmedInstance *>(object.get()))) //contains army
  2099. {
  2100. for(const auto & elem : ai->Slots()) //iterate through army
  2101. if(elem.second->type->getId() == condition.objectType) //it's searched creature
  2102. total += elem.second->count;
  2103. }
  2104. }
  2105. return total >= condition.value;
  2106. }
  2107. case EventCondition::HAVE_RESOURCES:
  2108. {
  2109. return p->resources[condition.objectType] >= condition.value;
  2110. }
  2111. case EventCondition::HAVE_BUILDING:
  2112. {
  2113. if (condition.object) // specific town
  2114. {
  2115. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  2116. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  2117. }
  2118. else // any town
  2119. {
  2120. for (const CGTownInstance * t : p->towns)
  2121. {
  2122. if (t->hasBuilt(BuildingID(condition.objectType)))
  2123. return true;
  2124. }
  2125. return false;
  2126. }
  2127. }
  2128. case EventCondition::DESTROY:
  2129. {
  2130. if (condition.object) // mode A - destroy specific object of this type
  2131. {
  2132. if(const auto * hero = dynamic_cast<const CGHeroInstance *>(condition.object))
  2133. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  2134. else
  2135. return getObj(condition.object->id) == nullptr;
  2136. }
  2137. else
  2138. {
  2139. for(const auto & elem : map->objects) // mode B - destroy all objects of this type
  2140. {
  2141. if(elem && elem->ID == condition.objectType)
  2142. return false;
  2143. }
  2144. return true;
  2145. }
  2146. }
  2147. case EventCondition::CONTROL:
  2148. {
  2149. // list of players that need to control object to fulfull condition
  2150. // NOTE: cgameinfocallback specified explicitly in order to get const version
  2151. const auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  2152. if (condition.object) // mode A - flag one specific object, like town
  2153. {
  2154. return team.count(condition.object->tempOwner) != 0;
  2155. }
  2156. else
  2157. {
  2158. for(const auto & elem : map->objects) // mode B - flag all objects of this type
  2159. {
  2160. //check not flagged objs
  2161. if ( elem && elem->ID == condition.objectType && team.count(elem->tempOwner) == 0 )
  2162. return false;
  2163. }
  2164. return true;
  2165. }
  2166. }
  2167. case EventCondition::TRANSPORT:
  2168. {
  2169. const auto * t = dynamic_cast<const CGTownInstance *>(condition.object);
  2170. return (t->visitingHero && t->visitingHero->hasArt(ArtifactID(condition.objectType))) ||
  2171. (t->garrisonHero && t->garrisonHero->hasArt(ArtifactID(condition.objectType)));
  2172. }
  2173. case EventCondition::DAYS_PASSED:
  2174. {
  2175. return (si32)gs->day > condition.value;
  2176. }
  2177. case EventCondition::IS_HUMAN:
  2178. {
  2179. return p->human ? condition.value == 1 : condition.value == 0;
  2180. }
  2181. case EventCondition::DAYS_WITHOUT_TOWN:
  2182. {
  2183. if (p->daysWithoutCastle)
  2184. return p->daysWithoutCastle >= condition.value;
  2185. else
  2186. return false;
  2187. }
  2188. case EventCondition::CONST_VALUE:
  2189. {
  2190. return condition.value; // just convert to bool
  2191. }
  2192. case EventCondition::HAVE_0:
  2193. {
  2194. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2195. //TODO: support new condition format
  2196. return false;
  2197. }
  2198. case EventCondition::HAVE_BUILDING_0:
  2199. {
  2200. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2201. //TODO: support new condition format
  2202. return false;
  2203. }
  2204. case EventCondition::DESTROY_0:
  2205. {
  2206. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2207. //TODO: support new condition format
  2208. return false;
  2209. }
  2210. default:
  2211. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  2212. return false;
  2213. }
  2214. }
  2215. PlayerColor CGameState::checkForStandardWin() const
  2216. {
  2217. //std victory condition is:
  2218. //all enemies lost
  2219. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  2220. TeamID winnerTeam = TeamID::NO_TEAM;
  2221. for(const auto & elem : players)
  2222. {
  2223. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  2224. {
  2225. if(supposedWinner == PlayerColor::NEUTRAL)
  2226. {
  2227. //first player remaining ingame - candidate for victory
  2228. supposedWinner = elem.second.color;
  2229. winnerTeam = elem.second.team;
  2230. }
  2231. else if(winnerTeam != elem.second.team)
  2232. {
  2233. //current candidate has enemy remaining in game -> no vicotry
  2234. return PlayerColor::NEUTRAL;
  2235. }
  2236. }
  2237. }
  2238. return supposedWinner;
  2239. }
  2240. bool CGameState::checkForStandardLoss(const PlayerColor & player) const
  2241. {
  2242. //std loss condition is: player lost all towns and heroes
  2243. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  2244. return pState.checkVanquished();
  2245. }
  2246. struct statsHLP
  2247. {
  2248. using TStat = std::pair<PlayerColor, si64>;
  2249. //converts [<player's color, value>] to vec[place] -> platers
  2250. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  2251. {
  2252. std::sort(stats.begin(), stats.end(), statsHLP());
  2253. //put first element
  2254. std::vector< std::vector<PlayerColor> > ret;
  2255. std::vector<PlayerColor> tmp;
  2256. tmp.push_back( stats[0].first );
  2257. ret.push_back( tmp );
  2258. //the rest of elements
  2259. for(int g=1; g<stats.size(); ++g)
  2260. {
  2261. if(stats[g].second == stats[g-1].second)
  2262. {
  2263. (ret.end()-1)->push_back( stats[g].first );
  2264. }
  2265. else
  2266. {
  2267. //create next occupied rank
  2268. std::vector<PlayerColor> tmp;
  2269. tmp.push_back(stats[g].first);
  2270. ret.push_back(tmp);
  2271. }
  2272. }
  2273. return ret;
  2274. }
  2275. bool operator()(const TStat & a, const TStat & b) const
  2276. {
  2277. return a.second > b.second;
  2278. }
  2279. static const CGHeroInstance * findBestHero(CGameState * gs, const PlayerColor & color)
  2280. {
  2281. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2282. if(h.empty())
  2283. return nullptr;
  2284. //best hero will be that with highest exp
  2285. int best = 0;
  2286. for(int b=1; b<h.size(); ++b)
  2287. {
  2288. if(h[b]->exp > h[best]->exp)
  2289. {
  2290. best = b;
  2291. }
  2292. }
  2293. return h[best];
  2294. }
  2295. //calculates total number of artifacts that belong to given player
  2296. static int getNumberOfArts(const PlayerState * ps)
  2297. {
  2298. int ret = 0;
  2299. for(auto h : ps->heroes)
  2300. {
  2301. ret += (int)h->artifactsInBackpack.size() + (int)h->artifactsWorn.size();
  2302. }
  2303. return ret;
  2304. }
  2305. // get total strength of player army
  2306. static si64 getArmyStrength(const PlayerState * ps)
  2307. {
  2308. si64 str = 0;
  2309. for(auto h : ps->heroes)
  2310. {
  2311. if(!h->inTownGarrison) //original h3 behavior
  2312. str += h->getArmyStrength();
  2313. }
  2314. return str;
  2315. }
  2316. // get total gold income
  2317. static int getIncome(const PlayerState * ps)
  2318. {
  2319. int totalIncome = 0;
  2320. const CGObjectInstance * heroOrTown = nullptr;
  2321. //Heroes can produce gold as well - skill, specialty or arts
  2322. for(const auto & h : ps->heroes)
  2323. {
  2324. totalIncome += h->valOfBonuses(Selector::typeSubtype(BonusType::GENERATE_RESOURCE, GameResID(EGameResID::GOLD)));
  2325. if(!heroOrTown)
  2326. heroOrTown = h;
  2327. }
  2328. //Add town income of all towns
  2329. for(const auto & t : ps->towns)
  2330. {
  2331. totalIncome += t->dailyIncome()[EGameResID::GOLD];
  2332. if(!heroOrTown)
  2333. heroOrTown = t;
  2334. }
  2335. /// FIXME: Dirty dirty hack
  2336. /// Stats helper need some access to gamestate.
  2337. std::vector<const CGObjectInstance *> ownedObjects;
  2338. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  2339. {
  2340. if(obj && obj->tempOwner == ps->color)
  2341. ownedObjects.push_back(obj);
  2342. }
  2343. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  2344. /// I'm really need to find out about callback interface design...
  2345. for(const auto * object : ownedObjects)
  2346. {
  2347. //Mines
  2348. if ( object->ID == Obj::MINE )
  2349. {
  2350. const auto * mine = dynamic_cast<const CGMine *>(object);
  2351. assert(mine);
  2352. if (mine->producedResource == EGameResID::GOLD)
  2353. totalIncome += mine->producedQuantity;
  2354. }
  2355. }
  2356. return totalIncome;
  2357. }
  2358. };
  2359. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2360. {
  2361. auto playerInactive = [&](const PlayerColor & color)
  2362. {
  2363. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  2364. };
  2365. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2366. { \
  2367. std::vector< std::pair< PlayerColor, si64 > > stats; \
  2368. for(auto g = players.begin(); g != players.end(); ++g) \
  2369. { \
  2370. if(playerInactive(g->second.color)) \
  2371. continue; \
  2372. std::pair< PlayerColor, si64 > stat; \
  2373. stat.first = g->second.color; \
  2374. stat.second = VAL_GETTER; \
  2375. stats.push_back(stat); \
  2376. } \
  2377. tgi.FIELD = statsHLP::getRank(stats); \
  2378. }
  2379. for(auto & elem : players)
  2380. {
  2381. if(!playerInactive(elem.second.color))
  2382. tgi.playerColors.push_back(elem.second.color);
  2383. }
  2384. if(level >= 0) //num of towns & num of heroes
  2385. {
  2386. //num of towns
  2387. FILL_FIELD(numOfTowns, g->second.towns.size())
  2388. //num of heroes
  2389. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2390. }
  2391. if(level >= 1) //best hero's portrait
  2392. {
  2393. for(const auto & player : players)
  2394. {
  2395. if(playerInactive(player.second.color))
  2396. continue;
  2397. const CGHeroInstance * best = statsHLP::findBestHero(this, player.second.color);
  2398. InfoAboutHero iah;
  2399. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  2400. iah.army.clear();
  2401. tgi.colorToBestHero[player.second.color] = iah;
  2402. }
  2403. }
  2404. if(level >= 2) //gold
  2405. {
  2406. FILL_FIELD(gold, g->second.resources[EGameResID::GOLD])
  2407. }
  2408. if(level >= 2) //wood & ore
  2409. {
  2410. FILL_FIELD(woodOre, g->second.resources[EGameResID::WOOD] + g->second.resources[EGameResID::ORE])
  2411. }
  2412. if(level >= 3) //mercury, sulfur, crystal, gems
  2413. {
  2414. FILL_FIELD(mercSulfCrystGems, g->second.resources[EGameResID::MERCURY] + g->second.resources[EGameResID::SULFUR] + g->second.resources[EGameResID::CRYSTAL] + g->second.resources[EGameResID::GEMS])
  2415. }
  2416. if(level >= 3) //obelisks found
  2417. {
  2418. auto getObeliskVisited = [](const TeamID & t)
  2419. {
  2420. if(CGObelisk::visited.count(t))
  2421. return CGObelisk::visited[t];
  2422. else
  2423. return ui8(0);
  2424. };
  2425. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  2426. }
  2427. if(level >= 4) //artifacts
  2428. {
  2429. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2430. }
  2431. if(level >= 4) //army strength
  2432. {
  2433. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2434. }
  2435. if(level >= 5) //income
  2436. {
  2437. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  2438. }
  2439. if(level >= 2) //best hero's stats
  2440. {
  2441. //already set in lvl 1 handling
  2442. }
  2443. if(level >= 3) //personality
  2444. {
  2445. for(const auto & player : players)
  2446. {
  2447. if(playerInactive(player.second.color)) //do nothing for neutral player
  2448. continue;
  2449. if(player.second.human)
  2450. {
  2451. tgi.personality[player.second.color] = EAiTactic::NONE;
  2452. }
  2453. else //AI
  2454. {
  2455. tgi.personality[player.second.color] = map->players[player.second.color.getNum()].aiTactic;
  2456. }
  2457. }
  2458. }
  2459. if(level >= 4) //best creature
  2460. {
  2461. //best creatures belonging to player (highest AI value)
  2462. for(const auto & player : players)
  2463. {
  2464. if(playerInactive(player.second.color)) //do nothing for neutral player
  2465. continue;
  2466. int bestCre = -1; //best creature's ID
  2467. for(const auto & elem : player.second.heroes)
  2468. {
  2469. for(const auto & it : elem->Slots())
  2470. {
  2471. int toCmp = it.second->type->getId(); //ID of creature we should compare with the best one
  2472. if(bestCre == -1 || VLC->creh->objects[bestCre]->getAIValue() < VLC->creh->objects[toCmp]->getAIValue())
  2473. {
  2474. bestCre = toCmp;
  2475. }
  2476. }
  2477. }
  2478. tgi.bestCreature[player.second.color] = bestCre;
  2479. }
  2480. }
  2481. #undef FILL_FIELD
  2482. }
  2483. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2484. {
  2485. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2486. for(const auto & player : players)
  2487. for(auto availableHero : player.second.availableHeroes)
  2488. if(availableHero)
  2489. pool.erase((*availableHero).subID);
  2490. return pool;
  2491. }
  2492. void CGameState::buildBonusSystemTree()
  2493. {
  2494. buildGlobalTeamPlayerTree();
  2495. attachArmedObjects();
  2496. for(CGTownInstance *t : map->towns)
  2497. {
  2498. t->deserializationFix();
  2499. }
  2500. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2501. // are provided on initializing / deserializing
  2502. }
  2503. void CGameState::deserializationFix()
  2504. {
  2505. buildGlobalTeamPlayerTree();
  2506. attachArmedObjects();
  2507. }
  2508. void CGameState::buildGlobalTeamPlayerTree()
  2509. {
  2510. for(auto & team : teams)
  2511. {
  2512. TeamState * t = &team.second;
  2513. t->attachTo(globalEffects);
  2514. for(const PlayerColor & teamMember : team.second.players)
  2515. {
  2516. PlayerState *p = getPlayerState(teamMember);
  2517. assert(p);
  2518. p->attachTo(*t);
  2519. }
  2520. }
  2521. }
  2522. void CGameState::attachArmedObjects()
  2523. {
  2524. for(CGObjectInstance *obj : map->objects)
  2525. {
  2526. if(auto * armed = dynamic_cast<CArmedInstance *>(obj))
  2527. {
  2528. armed->whatShouldBeAttached().attachTo(armed->whereShouldBeAttached(this));
  2529. }
  2530. }
  2531. }
  2532. bool CGameState::giveHeroArtifact(CGHeroInstance * h, const ArtifactID & aid)
  2533. {
  2534. CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  2535. CArtifactInstance * ai = ArtifactUtils::createNewArtifactInstance(artifact);
  2536. map->addNewArtifactInstance(ai);
  2537. auto slot = ArtifactUtils::getArtAnyPosition(h, aid);
  2538. if(ArtifactUtils::isSlotEquipment(slot) || ArtifactUtils::isSlotBackpack(slot))
  2539. {
  2540. ai->putAt(ArtifactLocation(h, slot));
  2541. return true;
  2542. }
  2543. else
  2544. {
  2545. return false;
  2546. }
  2547. }
  2548. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  2549. {
  2550. std::set<HeroTypeID> ret;
  2551. for(int i = 0; i < map->allowedHeroes.size(); i++)
  2552. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  2553. ret.insert(HeroTypeID(i));
  2554. for(const auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  2555. {
  2556. if(playerSettingPair.second.hero != PlayerSettings::RANDOM)
  2557. ret -= HeroTypeID(playerSettingPair.second.hero);
  2558. }
  2559. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2560. {
  2561. if(hero->type)
  2562. ret -= hero->type->getId();
  2563. else
  2564. ret -= HeroTypeID(hero->subID);
  2565. }
  2566. for(auto obj : map->objects) //prisons
  2567. if(obj && obj->ID == Obj::PRISON)
  2568. ret -= HeroTypeID(obj->subID);
  2569. return ret;
  2570. }
  2571. std::vector<CGameState::CampaignHeroReplacement> CGameState::generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes)
  2572. {
  2573. std::vector<CampaignHeroReplacement> campaignHeroReplacements;
  2574. //selecting heroes by type
  2575. for(auto obj : map->objects)
  2576. {
  2577. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2578. {
  2579. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2580. if(heroPlaceholder->subID != 0xFF) //select by type
  2581. {
  2582. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [heroPlaceholder](CGHeroInstance * hero)
  2583. {
  2584. return hero->subID == heroPlaceholder->subID;
  2585. });
  2586. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  2587. {
  2588. auto * hero = *it;
  2589. crossoverHeroes.removeHeroFromBothLists(hero);
  2590. campaignHeroReplacements.emplace_back(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id);
  2591. }
  2592. }
  2593. }
  2594. }
  2595. //selecting heroes by power
  2596. range::sort(crossoverHeroes.heroesFromPreviousScenario, [](const CGHeroInstance * a, const CGHeroInstance * b)
  2597. {
  2598. return a->getHeroStrength() > b->getHeroStrength();
  2599. }); //sort, descending strength
  2600. // sort hero placeholders descending power
  2601. std::vector<CGHeroPlaceholder *> heroPlaceholders;
  2602. for(auto obj : map->objects)
  2603. {
  2604. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2605. {
  2606. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2607. if(heroPlaceholder->subID == 0xFF) //select by power
  2608. {
  2609. heroPlaceholders.push_back(heroPlaceholder);
  2610. }
  2611. }
  2612. }
  2613. range::sort(heroPlaceholders, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  2614. {
  2615. return a->power > b->power;
  2616. });
  2617. for(int i = 0; i < heroPlaceholders.size(); ++i)
  2618. {
  2619. auto * heroPlaceholder = heroPlaceholders[i];
  2620. if(crossoverHeroes.heroesFromPreviousScenario.size() > i)
  2621. {
  2622. auto * hero = crossoverHeroes.heroesFromPreviousScenario[i];
  2623. campaignHeroReplacements.emplace_back(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id);
  2624. }
  2625. }
  2626. return campaignHeroReplacements;
  2627. }
  2628. void CGameState::replaceHeroesPlaceholders(const std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements)
  2629. {
  2630. for(const auto & campaignHeroReplacement : campaignHeroReplacements)
  2631. {
  2632. auto * heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  2633. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  2634. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  2635. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  2636. heroToPlace->pos = heroPlaceholder->pos;
  2637. heroToPlace->type = VLC->heroh->objects[heroToPlace->subID];
  2638. heroToPlace->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO,
  2639. heroToPlace->type->heroClass->getIndex())->getTemplates().front();
  2640. for(auto &&i : heroToPlace->stacks)
  2641. i.second->type = VLC->creh->objects[i.second->getCreatureID()];
  2642. auto fixArtifact = [&](CArtifactInstance * art)
  2643. {
  2644. art->artType = VLC->arth->objects[art->artType->getId()];
  2645. gs->map->artInstances.emplace_back(art);
  2646. art->id = ArtifactInstanceID((si32)gs->map->artInstances.size() - 1);
  2647. };
  2648. for(auto &&i : heroToPlace->artifactsWorn)
  2649. fixArtifact(i.second.artifact);
  2650. for(auto &&i : heroToPlace->artifactsInBackpack)
  2651. fixArtifact(i.artifact);
  2652. map->removeBlockVisTiles(heroPlaceholder, true);
  2653. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  2654. map->instanceNames.erase(heroPlaceholder->instanceName);
  2655. map->heroesOnMap.emplace_back(heroToPlace);
  2656. map->objects[heroToPlace->id.getNum()] = heroToPlace;
  2657. map->addBlockVisTiles(heroToPlace);
  2658. map->instanceNames[heroToPlace->instanceName] = heroToPlace;
  2659. delete heroPlaceholder;
  2660. scenarioOps->campState->getCurrentScenario().placedCrossoverHeroes.push_back(CCampaignState::crossoverSerialize(heroToPlace));
  2661. }
  2662. }
  2663. bool CGameState::isUsedHero(const HeroTypeID & hid) const
  2664. {
  2665. return getUsedHero(hid);
  2666. }
  2667. CGHeroInstance * CGameState::getUsedHero(const HeroTypeID & hid) const
  2668. {
  2669. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2670. {
  2671. if(hero->type && hero->type->getId() == hid)
  2672. {
  2673. return hero;
  2674. }
  2675. }
  2676. for(auto obj : map->objects) //prisons
  2677. {
  2678. if(obj && obj->ID == Obj::PRISON )
  2679. {
  2680. auto * hero = dynamic_cast<CGHeroInstance *>(obj.get());
  2681. assert(hero);
  2682. if ( hero->type && hero->type->getId() == hid )
  2683. return hero;
  2684. }
  2685. }
  2686. return nullptr;
  2687. }
  2688. bool RumorState::update(int id, int extra)
  2689. {
  2690. if(vstd::contains(last, type))
  2691. {
  2692. if(last[type].first != id)
  2693. {
  2694. last[type].first = id;
  2695. last[type].second = extra;
  2696. }
  2697. else
  2698. return false;
  2699. }
  2700. else
  2701. last[type] = std::make_pair(id, extra);
  2702. return true;
  2703. }
  2704. InfoAboutArmy::InfoAboutArmy():
  2705. owner(PlayerColor::NEUTRAL)
  2706. {}
  2707. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2708. {
  2709. initFromArmy(Army, detailed);
  2710. }
  2711. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2712. {
  2713. army = ArmyDescriptor(Army, detailed);
  2714. owner = Army->tempOwner;
  2715. name = Army->getObjectName();
  2716. }
  2717. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2718. {
  2719. vstd::clear_pointer(details);
  2720. InfoAboutArmy::operator = (iah);
  2721. details = (iah.details ? new Details(*iah.details) : nullptr);
  2722. hclass = iah.hclass;
  2723. portrait = iah.portrait;
  2724. }
  2725. InfoAboutHero::InfoAboutHero(): portrait(-1) {}
  2726. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah): InfoAboutArmy(iah)
  2727. {
  2728. assign(iah);
  2729. }
  2730. InfoAboutHero::InfoAboutHero(const CGHeroInstance * h, InfoAboutHero::EInfoLevel infoLevel):
  2731. portrait(-1)
  2732. {
  2733. initFromHero(h, infoLevel);
  2734. }
  2735. InfoAboutHero::~InfoAboutHero()
  2736. {
  2737. vstd::clear_pointer(details);
  2738. }
  2739. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2740. {
  2741. assign(iah);
  2742. return *this;
  2743. }
  2744. void InfoAboutHero::initFromHero(const CGHeroInstance *h, InfoAboutHero::EInfoLevel infoLevel)
  2745. {
  2746. vstd::clear_pointer(details);
  2747. if(!h)
  2748. return;
  2749. bool detailed = ( (infoLevel == EInfoLevel::DETAILED) || (infoLevel == EInfoLevel::INBATTLE) );
  2750. initFromArmy(h, detailed);
  2751. hclass = h->type->heroClass;
  2752. name = h->getNameTranslated();
  2753. portrait = h->portrait;
  2754. if(detailed)
  2755. {
  2756. //include details about hero
  2757. details = new Details();
  2758. details->luck = h->luckVal();
  2759. details->morale = h->moraleVal();
  2760. details->mana = h->mana;
  2761. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2762. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2763. {
  2764. details->primskills[i] = h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i));
  2765. }
  2766. if (infoLevel == EInfoLevel::INBATTLE)
  2767. details->manaLimit = h->manaLimit();
  2768. else
  2769. details->manaLimit = -1; //we do not want to leak max mana info outside battle so set to meaningless value
  2770. }
  2771. }
  2772. InfoAboutTown::InfoAboutTown():
  2773. details(nullptr),
  2774. tType(nullptr),
  2775. built(0),
  2776. fortLevel(0)
  2777. {
  2778. }
  2779. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed):
  2780. details(nullptr),
  2781. tType(nullptr),
  2782. built(0),
  2783. fortLevel(0)
  2784. {
  2785. initFromTown(t, detailed);
  2786. }
  2787. InfoAboutTown::~InfoAboutTown()
  2788. {
  2789. vstd::clear_pointer(details);
  2790. }
  2791. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2792. {
  2793. initFromArmy(t, detailed);
  2794. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2795. built = t->builded;
  2796. fortLevel = t->fortLevel();
  2797. name = t->getNameTranslated();
  2798. tType = t->getTown();
  2799. vstd::clear_pointer(details);
  2800. if(detailed)
  2801. {
  2802. //include details about hero
  2803. details = new Details();
  2804. TResources income = t->dailyIncome();
  2805. details->goldIncome = income[EGameResID::GOLD];
  2806. details->customRes = t->hasBuilt(BuildingID::RESOURCE_SILO);
  2807. details->hallLevel = t->hallLevel();
  2808. details->garrisonedHero = t->garrisonHero;
  2809. }
  2810. }
  2811. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2812. : isDetailed(detailed)
  2813. {
  2814. for(const auto & elem : army->Slots())
  2815. {
  2816. if(detailed)
  2817. (*this)[elem.first] = *elem.second;
  2818. else
  2819. (*this)[elem.first] = CStackBasicDescriptor(elem.second->type, (int)elem.second->getQuantityID());
  2820. }
  2821. }
  2822. ArmyDescriptor::ArmyDescriptor()
  2823. : isDetailed(false)
  2824. {
  2825. }
  2826. int ArmyDescriptor::getStrength() const
  2827. {
  2828. ui64 ret = 0;
  2829. if(isDetailed)
  2830. {
  2831. for(const auto & elem : *this)
  2832. ret += elem.second.type->getAIValue() * elem.second.count;
  2833. }
  2834. else
  2835. {
  2836. for(const auto & elem : *this)
  2837. ret += elem.second.type->getAIValue() * CCreature::estimateCreatureCount(elem.second.count);
  2838. }
  2839. return static_cast<int>(ret);
  2840. }
  2841. TeamState::TeamState()
  2842. {
  2843. setNodeType(TEAM);
  2844. fogOfWarMap = std::make_shared<boost::multi_array<ui8, 3>>();
  2845. }
  2846. TeamState::TeamState(TeamState && other) noexcept:
  2847. CBonusSystemNode(std::move(other)),
  2848. id(other.id)
  2849. {
  2850. std::swap(players, other.players);
  2851. std::swap(fogOfWarMap, other.fogOfWarMap);
  2852. }
  2853. CRandomGenerator & CGameState::getRandomGenerator()
  2854. {
  2855. return rand;
  2856. }
  2857. VCMI_LIB_NAMESPACE_END