CGameState.cpp 82 KB

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