CGameState.cpp 86 KB

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