2
0

CGameState.cpp 84 KB

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