CGameState.cpp 86 KB

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