CGameState.cpp 84 KB

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