CGameState.cpp 84 KB

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