CGameState.cpp 84 KB

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