CGameState.cpp 84 KB

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