CGameState.cpp 86 KB

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