CGameState.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131
  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. initSightMap();
  683. // Explicitly initialize static variables
  684. for(auto & elem : players)
  685. {
  686. CGKeys::playerKeyMap[elem.first] = std::set<ui8>();
  687. }
  688. for(auto & elem : teams)
  689. {
  690. CGObelisk::visited[elem.first] = 0;
  691. }
  692. logGlobal->debug("\tChecking objectives");
  693. map->checkForObjectives(); //needs to be run when all objects are properly placed
  694. auto seedAfterInit = getRandomGenerator().nextInt();
  695. logGlobal->info("Seed after init is %d (before was %d)", seedAfterInit, scenarioOps->seedToBeUsed);
  696. if(scenarioOps->seedPostInit > 0)
  697. {
  698. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  699. assert(scenarioOps->seedPostInit == seedAfterInit);
  700. }
  701. else
  702. {
  703. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  704. }
  705. }
  706. void CGameState::initNewGame(bool allowSavingRandomMap)
  707. {
  708. if(scenarioOps->createRandomMap())
  709. {
  710. logGlobal->info("Create random map.");
  711. CStopWatch sw;
  712. // Gen map
  713. CMapGenerator mapGenerator;
  714. std::unique_ptr<CMap> randomMap = mapGenerator.generate(scenarioOps->mapGenOptions.get(), scenarioOps->seedToBeUsed);
  715. if(allowSavingRandomMap)
  716. {
  717. try
  718. {
  719. auto path = VCMIDirs::get().userCachePath() / "RandomMaps";
  720. boost::filesystem::create_directories(path);
  721. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  722. const std::string templateName = options->getMapTemplate()->getName();
  723. const ui32 seed = scenarioOps->seedToBeUsed;
  724. const std::string fileName = boost::str(boost::format("%s_%d.vmap") % templateName % seed );
  725. const auto fullPath = path / fileName;
  726. CMapService::saveMap(randomMap, fullPath);
  727. logGlobal->info("Random map has been saved to:");
  728. logGlobal->info(fullPath.string());
  729. }
  730. catch(...)
  731. {
  732. logGlobal->error("Saving random map failed with exception");
  733. handleException();
  734. }
  735. }
  736. map = randomMap.release();
  737. // Update starting options
  738. for(int i = 0; i < map->players.size(); ++i)
  739. {
  740. const auto & playerInfo = map->players[i];
  741. if(playerInfo.canAnyonePlay())
  742. {
  743. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  744. playerSettings.compOnly = !playerInfo.canHumanPlay;
  745. playerSettings.team = playerInfo.team;
  746. playerSettings.castle = playerInfo.defaultCastle();
  747. if(playerSettings.playerID == PlayerSettings::PLAYER_AI && playerSettings.name.empty())
  748. {
  749. playerSettings.name = VLC->generaltexth->allTexts[468];
  750. }
  751. playerSettings.color = PlayerColor(i);
  752. }
  753. else
  754. {
  755. scenarioOps->playerInfos.erase(PlayerColor(i));
  756. }
  757. }
  758. logGlobal->info("Generated random map in %i ms.", sw.getDiff());
  759. }
  760. else
  761. {
  762. logGlobal->info("Open map file: %s", scenarioOps->mapname);
  763. const ResourceID mapURI(scenarioOps->mapname, EResType::MAP);
  764. map = CMapService::loadMap(mapURI).release();
  765. }
  766. }
  767. void CGameState::initCampaign()
  768. {
  769. logGlobal->info("Open campaign map file: %d", scenarioOps->campState->currentMap.get());
  770. auto campaign = scenarioOps->campState;
  771. assert(vstd::contains(campaign->camp->mapPieces, *scenarioOps->campState->currentMap));
  772. std::string scenarioName = scenarioOps->mapname.substr(0, scenarioOps->mapname.find('.'));
  773. boost::to_lower(scenarioName);
  774. scenarioName += ':' + boost::lexical_cast<std::string>(*campaign->currentMap);
  775. std::string & mapContent = campaign->camp->mapPieces[*campaign->currentMap];
  776. auto buffer = reinterpret_cast<const ui8 *>(mapContent.data());
  777. map = CMapService::loadMap(buffer, mapContent.size(), scenarioName).release();
  778. }
  779. void CGameState::checkMapChecksum()
  780. {
  781. logGlobal->info("\tOur checksum for the map: %d", map->checksum);
  782. if(scenarioOps->mapfileChecksum)
  783. {
  784. logGlobal->info("\tServer checksum for %s: %d", scenarioOps->mapname, scenarioOps->mapfileChecksum);
  785. if(map->checksum != scenarioOps->mapfileChecksum)
  786. {
  787. logGlobal->error("Wrong map checksum!!!");
  788. throw std::runtime_error("Wrong checksum");
  789. }
  790. }
  791. else
  792. {
  793. scenarioOps->mapfileChecksum = map->checksum;
  794. }
  795. }
  796. void CGameState::initGrailPosition()
  797. {
  798. logGlobal->debug("\tPicking grail position");
  799. //pick grail location
  800. if(map->grailPos.x < 0 || map->grailRadius) //grail not set or set within a radius around some place
  801. {
  802. if(!map->grailRadius) //radius not given -> anywhere on map
  803. map->grailRadius = map->width * 2;
  804. std::vector<int3> allowedPos;
  805. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  806. // add all not blocked tiles in range
  807. for (int i = BORDER_WIDTH; i < map->width - BORDER_WIDTH ; i++)
  808. {
  809. for (int j = BORDER_WIDTH; j < map->height - BORDER_WIDTH; j++)
  810. {
  811. for (int k = 0; k < (map->twoLevel ? 2 : 1); k++)
  812. {
  813. const TerrainTile &t = map->getTile(int3(i, j, k));
  814. if(!t.blocked
  815. && !t.visitable
  816. && t.terType != ETerrainType::WATER
  817. && t.terType != ETerrainType::ROCK
  818. && map->grailPos.dist2dSQ(int3(i, j, k)) <= (map->grailRadius * map->grailRadius))
  819. allowedPos.push_back(int3(i,j,k));
  820. }
  821. }
  822. }
  823. //remove tiles with holes
  824. for(auto & elem : map->objects)
  825. if(elem && elem->ID == Obj::HOLE)
  826. allowedPos -= elem->pos;
  827. if(!allowedPos.empty())
  828. {
  829. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, getRandomGenerator());
  830. }
  831. else
  832. {
  833. logGlobal->warn("Grail cannot be placed, no appropriate tile found!");
  834. }
  835. }
  836. }
  837. void CGameState::initRandomFactionsForPlayers()
  838. {
  839. logGlobal->debug("\tPicking random factions for players");
  840. for(auto & elem : scenarioOps->playerInfos)
  841. {
  842. if(elem.second.castle==-1)
  843. {
  844. auto randomID = getRandomGenerator().nextInt(map->players[elem.first.getNum()].allowedFactions.size() - 1);
  845. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  846. std::advance(iter, randomID);
  847. elem.second.castle = *iter;
  848. }
  849. }
  850. }
  851. void CGameState::randomizeMapObjects()
  852. {
  853. logGlobal->debug("\tRandomizing objects");
  854. for(CGObjectInstance *obj : map->objects)
  855. {
  856. if(!obj) continue;
  857. randomizeObject(obj);
  858. //handle Favouring Winds - mark tiles under it
  859. if(obj->ID == Obj::FAVORABLE_WINDS)
  860. {
  861. for (int i = 0; i < obj->getWidth() ; i++)
  862. {
  863. for (int j = 0; j < obj->getHeight() ; j++)
  864. {
  865. int3 pos = obj->pos - int3(i,j,0);
  866. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  867. }
  868. }
  869. }
  870. }
  871. }
  872. void CGameState::initPlayerStates()
  873. {
  874. logGlobal->debug("\tCreating player entries in gs");
  875. for(auto & elem : scenarioOps->playerInfos)
  876. {
  877. PlayerState & p = players[elem.first];
  878. //std::pair<PlayerColor, PlayerState> ins(elem.first,PlayerState());
  879. p.color=elem.first;
  880. p.human = elem.second.playerID;
  881. p.team = map->players[elem.first.getNum()].team;
  882. teams[p.team].id = p.team;//init team
  883. teams[p.team].players.insert(elem.first);//add player to team
  884. //players.insert(ins);
  885. }
  886. }
  887. void CGameState::placeCampaignHeroes()
  888. {
  889. if (scenarioOps->campState)
  890. {
  891. // place bonus hero
  892. auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap();
  893. bool campaignGiveHero = campaignBonus && campaignBonus.get().type == CScenarioTravel::STravelBonus::HERO;
  894. if(campaignGiveHero)
  895. {
  896. auto playerColor = PlayerColor(campaignBonus->info1);
  897. auto it = scenarioOps->playerInfos.find(playerColor);
  898. if(it != scenarioOps->playerInfos.end())
  899. {
  900. auto heroTypeId = campaignBonus->info2;
  901. if(heroTypeId == 0xffff) // random bonus hero
  902. {
  903. heroTypeId = pickUnusedHeroTypeRandomly(playerColor);
  904. }
  905. placeStartingHero(playerColor, HeroTypeID(heroTypeId), map->players[playerColor.getNum()].posOfMainTown);
  906. }
  907. }
  908. // replace heroes placeholders
  909. auto crossoverHeroes = getCrossoverHeroesFromPreviousScenarios();
  910. if(!crossoverHeroes.heroesFromAnyPreviousScenarios.empty())
  911. {
  912. logGlobal->debug("\tGenerate list of hero placeholders");
  913. auto campaignHeroReplacements = generateCampaignHeroesToReplace(crossoverHeroes);
  914. logGlobal->debug("\tPrepare crossover heroes");
  915. prepareCrossoverHeroes(campaignHeroReplacements, scenarioOps->campState->getCurrentScenario().travelOptions);
  916. // remove same heroes on the map which will be added through crossover heroes
  917. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  918. // with the same hero type id
  919. std::vector<CGHeroInstance *> removedHeroes;
  920. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  921. {
  922. auto hero = getUsedHero(HeroTypeID(campaignHeroReplacement.hero->subID));
  923. if(hero)
  924. {
  925. removedHeroes.push_back(hero);
  926. map->heroesOnMap -= hero;
  927. map->objects[hero->id.getNum()] = nullptr;
  928. map->removeBlockVisTiles(hero, true);
  929. }
  930. }
  931. logGlobal->debug("\tReplace placeholders with heroes");
  932. replaceHeroesPlaceholders(campaignHeroReplacements);
  933. // remove hero placeholders on map
  934. for(auto obj : map->objects)
  935. {
  936. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  937. {
  938. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  939. map->removeBlockVisTiles(heroPlaceholder, true);
  940. map->instanceNames.erase(obj->instanceName);
  941. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  942. delete heroPlaceholder;
  943. }
  944. }
  945. // now add removed heroes again with unused type ID
  946. for(auto hero : removedHeroes)
  947. {
  948. si32 heroTypeId = 0;
  949. if(hero->ID == Obj::HERO)
  950. {
  951. heroTypeId = pickUnusedHeroTypeRandomly(hero->tempOwner);
  952. }
  953. else if(hero->ID == Obj::PRISON)
  954. {
  955. auto unusedHeroTypeIds = getUnusedAllowedHeroes();
  956. if(!unusedHeroTypeIds.empty())
  957. {
  958. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, getRandomGenerator())).getNum();
  959. }
  960. else
  961. {
  962. logGlobal->error("No free hero type ID found to replace prison.");
  963. assert(0);
  964. }
  965. }
  966. else
  967. {
  968. assert(0); // should not happen
  969. }
  970. hero->subID = heroTypeId;
  971. hero->portrait = hero->subID;
  972. map->getEditManager()->insertObject(hero);
  973. }
  974. }
  975. }
  976. }
  977. void CGameState::placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos)
  978. {
  979. townPos.x -= 2; //FIXME: use actual visitable offset of town
  980. CGObjectInstance * hero = createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor);
  981. hero->pos += hero->getVisitableOffset();
  982. map->getEditManager()->insertObject(hero);
  983. }
  984. CGameState::CrossoverHeroesList CGameState::getCrossoverHeroesFromPreviousScenarios() const
  985. {
  986. CrossoverHeroesList crossoverHeroes;
  987. auto campaignState = scenarioOps->campState;
  988. auto bonus = campaignState->getBonusForCurrentMap();
  989. if (bonus && bonus->type == CScenarioTravel::STravelBonus::HEROES_FROM_PREVIOUS_SCENARIO)
  990. {
  991. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = campaignState->camp->scenarios[bonus->info2].crossoverHeroes;
  992. }
  993. else
  994. {
  995. if(!campaignState->mapsConquered.empty())
  996. {
  997. crossoverHeroes.heroesFromPreviousScenario = campaignState->camp->scenarios[campaignState->mapsConquered.back()].crossoverHeroes;
  998. for(auto mapNr : campaignState->mapsConquered)
  999. {
  1000. // create a list of deleted heroes
  1001. auto & scenario = campaignState->camp->scenarios[mapNr];
  1002. auto lostCrossoverHeroes = scenario.getLostCrossoverHeroes();
  1003. // remove heroes which didn't reached the end of the scenario, but were available at the start
  1004. for(auto hero : lostCrossoverHeroes)
  1005. {
  1006. vstd::erase_if(crossoverHeroes.heroesFromAnyPreviousScenarios,
  1007. CGObjectInstanceBySubIdFinder(hero));
  1008. }
  1009. // now add heroes which completed the scenario
  1010. for(auto hero : scenario.crossoverHeroes)
  1011. {
  1012. // add new heroes and replace old heroes with newer ones
  1013. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, CGObjectInstanceBySubIdFinder(hero));
  1014. if (it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  1015. {
  1016. // replace old hero with newer one
  1017. crossoverHeroes.heroesFromAnyPreviousScenarios[it - crossoverHeroes.heroesFromAnyPreviousScenarios.begin()] = hero;
  1018. }
  1019. else
  1020. {
  1021. // add new hero
  1022. crossoverHeroes.heroesFromAnyPreviousScenarios.push_back(hero);
  1023. }
  1024. }
  1025. }
  1026. }
  1027. }
  1028. return crossoverHeroes;
  1029. }
  1030. void CGameState::prepareCrossoverHeroes(std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions)
  1031. {
  1032. // create heroes list for convenience iterating
  1033. std::vector<CGHeroInstance *> crossoverHeroes;
  1034. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  1035. {
  1036. crossoverHeroes.push_back(campaignHeroReplacement.hero);
  1037. }
  1038. // TODO replace magic numbers with named constants
  1039. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  1040. if(!(travelOptions.whatHeroKeeps & 1))
  1041. {
  1042. //trimming experience
  1043. for(CGHeroInstance * cgh : crossoverHeroes)
  1044. {
  1045. cgh->initExp(getRandomGenerator());
  1046. }
  1047. }
  1048. if(!(travelOptions.whatHeroKeeps & 2))
  1049. {
  1050. //trimming prim skills
  1051. for(CGHeroInstance * cgh : crossoverHeroes)
  1052. {
  1053. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1054. {
  1055. auto sel = Selector::type(Bonus::PRIMARY_SKILL)
  1056. .And(Selector::subtype(g))
  1057. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL));
  1058. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  1059. }
  1060. }
  1061. }
  1062. if(!(travelOptions.whatHeroKeeps & 4))
  1063. {
  1064. //trimming sec skills
  1065. for(CGHeroInstance * cgh : crossoverHeroes)
  1066. {
  1067. cgh->secSkills = cgh->type->secSkillsInit;
  1068. cgh->recreateSecondarySkillsBonuses();
  1069. }
  1070. }
  1071. if(!(travelOptions.whatHeroKeeps & 8))
  1072. {
  1073. for(CGHeroInstance * cgh : crossoverHeroes)
  1074. {
  1075. // Trimming spells
  1076. cgh->spells.clear();
  1077. // Spellbook will also be removed
  1078. if (cgh->hasSpellbook())
  1079. ArtifactLocation(cgh, ArtifactPosition(ArtifactPosition::SPELLBOOK)).removeArtifact();
  1080. }
  1081. }
  1082. if(!(travelOptions.whatHeroKeeps & 16))
  1083. {
  1084. //trimming artifacts
  1085. for(CGHeroInstance * hero : crossoverHeroes)
  1086. {
  1087. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  1088. for (size_t i = 0; i < totalArts; i++ )
  1089. {
  1090. auto artifactPosition = ArtifactPosition(i);
  1091. if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
  1092. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  1093. if(!info)
  1094. continue;
  1095. // TODO: why would there be nullptr artifacts?
  1096. const CArtifactInstance *art = info->artifact;
  1097. if(!art)
  1098. continue;
  1099. int id = art->artType->id;
  1100. assert( 8*18 > id );//number of arts that fits into h3m format
  1101. bool takeable = travelOptions.artifsKeptByHero[id / 8] & ( 1 << (id%8) );
  1102. ArtifactLocation al(hero, artifactPosition);
  1103. if(!takeable && !al.getSlot()->locked) //don't try removing locked artifacts -> it crashes #1719
  1104. al.removeArtifact();
  1105. }
  1106. }
  1107. }
  1108. //trimming creatures
  1109. for(CGHeroInstance * cgh : crossoverHeroes)
  1110. {
  1111. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  1112. {
  1113. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  1114. return !(travelOptions.monstersKeptByHero[crid / 8] & (1 << (crid % 8)));
  1115. };
  1116. auto stacksCopy = cgh->stacks; //copy of the map, so we can iterate iover it and remove stacks
  1117. for(auto &slotPair : stacksCopy)
  1118. if(shouldSlotBeErased(slotPair))
  1119. cgh->eraseStack(slotPair.first);
  1120. }
  1121. // Removing short-term bonuses
  1122. for(CGHeroInstance * cgh : crossoverHeroes)
  1123. {
  1124. cgh->popBonuses(CSelector(Bonus::OneDay)
  1125. .Or(CSelector(Bonus::OneWeek))
  1126. .Or(CSelector(Bonus::NTurns))
  1127. .Or(CSelector(Bonus::NDays))
  1128. .Or(CSelector(Bonus::OneBattle)));
  1129. }
  1130. }
  1131. void CGameState::placeStartingHeroes()
  1132. {
  1133. logGlobal->debug("\tGiving starting hero");
  1134. for(auto & playerSettingPair : scenarioOps->playerInfos)
  1135. {
  1136. auto playerColor = playerSettingPair.first;
  1137. auto & playerInfo = map->players[playerColor.getNum()];
  1138. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  1139. {
  1140. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  1141. if(scenarioOps->campState)
  1142. {
  1143. if(auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap())
  1144. {
  1145. if(campaignBonus->type == CScenarioTravel::STravelBonus::HERO && playerColor == PlayerColor(campaignBonus->info1)) continue;
  1146. }
  1147. }
  1148. int heroTypeId = pickNextHeroType(playerColor);
  1149. if(playerSettingPair.second.hero == -1)
  1150. playerSettingPair.second.hero = heroTypeId;
  1151. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  1152. }
  1153. }
  1154. }
  1155. void CGameState::initStartingResources()
  1156. {
  1157. logGlobal->debug("\tSetting up resources");
  1158. const JsonNode config(ResourceID("config/startres.json"));
  1159. const JsonVector &vector = config["difficulty"].Vector();
  1160. const JsonNode &level = vector[scenarioOps->difficulty];
  1161. TResources startresAI(level["ai"]);
  1162. TResources startresHuman(level["human"]);
  1163. for (auto & elem : players)
  1164. {
  1165. PlayerState &p = elem.second;
  1166. if (p.human)
  1167. p.resources = startresHuman;
  1168. else
  1169. p.resources = startresAI;
  1170. }
  1171. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  1172. {
  1173. std::vector<const PlayerSettings *> ret;
  1174. for(auto it = scenarioOps->playerInfos.cbegin();
  1175. it != scenarioOps->playerInfos.cend(); ++it)
  1176. {
  1177. if(it->second.playerID != PlayerSettings::PLAYER_AI)
  1178. ret.push_back(&it->second);
  1179. }
  1180. return ret;
  1181. };
  1182. //give start resource bonus in case of campaign
  1183. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1184. {
  1185. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1186. if(chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1187. {
  1188. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1189. for(const PlayerSettings *ps : people)
  1190. {
  1191. std::vector<int> res; //resources we will give
  1192. switch (chosenBonus->info1)
  1193. {
  1194. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1195. res.push_back(chosenBonus->info1);
  1196. break;
  1197. case 0xFD: //wood+ore
  1198. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1199. break;
  1200. case 0xFE: //rare
  1201. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1202. break;
  1203. default:
  1204. assert(0);
  1205. break;
  1206. }
  1207. //increasing resource quantity
  1208. for (auto & re : res)
  1209. {
  1210. players[ps->color].resources[re] += chosenBonus->info2;
  1211. }
  1212. }
  1213. }
  1214. }
  1215. }
  1216. void CGameState::initHeroes()
  1217. {
  1218. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1219. {
  1220. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  1221. {
  1222. logGlobal->warn("Hero with uninitialized owner!");
  1223. continue;
  1224. }
  1225. hero->initHero(getRandomGenerator());
  1226. getPlayer(hero->getOwner())->heroes.push_back(hero);
  1227. map->allHeroes[hero->type->ID.getNum()] = hero;
  1228. }
  1229. for(auto obj : map->objects) //prisons
  1230. {
  1231. if(obj && obj->ID == Obj::PRISON)
  1232. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  1233. }
  1234. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  1235. for(auto ph : map->predefinedHeroes)
  1236. {
  1237. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  1238. continue;
  1239. ph->initHero(getRandomGenerator());
  1240. hpool.heroesPool[ph->subID] = ph;
  1241. hpool.pavailable[ph->subID] = 0xff;
  1242. heroesToCreate.erase(ph->type->ID);
  1243. map->allHeroes[ph->subID] = ph;
  1244. }
  1245. for(HeroTypeID htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  1246. {
  1247. auto vhi = new CGHeroInstance();
  1248. vhi->initHero(getRandomGenerator(), htype);
  1249. int typeID = htype.getNum();
  1250. map->allHeroes[typeID] = vhi;
  1251. hpool.heroesPool[typeID] = vhi;
  1252. hpool.pavailable[typeID] = 0xff;
  1253. }
  1254. for(auto & elem : map->disposedHeroes)
  1255. {
  1256. hpool.pavailable[elem.heroId] = elem.players;
  1257. }
  1258. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1259. {
  1260. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1261. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1262. {
  1263. //find human player
  1264. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  1265. for (auto & elem : players)
  1266. {
  1267. if(elem.second.human)
  1268. {
  1269. humanPlayer = elem.first;
  1270. break;
  1271. }
  1272. }
  1273. assert(humanPlayer != PlayerColor::NEUTRAL);
  1274. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1275. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1276. {
  1277. int maxB = -1;
  1278. for (int b=0; b<heroes.size(); ++b)
  1279. {
  1280. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1281. {
  1282. maxB = b;
  1283. }
  1284. }
  1285. if(maxB < 0)
  1286. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  1287. else
  1288. giveCampaignBonusToHero(heroes[maxB]);
  1289. }
  1290. else //specific hero
  1291. {
  1292. for (auto & heroe : heroes)
  1293. {
  1294. if (heroe->subID == chosenBonus->info1)
  1295. {
  1296. giveCampaignBonusToHero(heroe);
  1297. break;
  1298. }
  1299. }
  1300. }
  1301. }
  1302. }
  1303. }
  1304. void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero)
  1305. {
  1306. const boost::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
  1307. if(!curBonus)
  1308. return;
  1309. if(curBonus->isBonusForHero())
  1310. {
  1311. //apply bonus
  1312. switch (curBonus->type)
  1313. {
  1314. case CScenarioTravel::STravelBonus::SPELL:
  1315. hero->spells.insert(SpellID(curBonus->info2));
  1316. break;
  1317. case CScenarioTravel::STravelBonus::MONSTER:
  1318. {
  1319. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  1320. {
  1321. if(hero->slotEmpty(SlotID(i)))
  1322. {
  1323. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  1324. break;
  1325. }
  1326. }
  1327. }
  1328. break;
  1329. case CScenarioTravel::STravelBonus::ARTIFACT:
  1330. gs->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2));
  1331. break;
  1332. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  1333. {
  1334. CArtifactInstance * scroll = CArtifactInstance::createScroll(SpellID(curBonus->info2).toSpell());
  1335. scroll->putAt(ArtifactLocation(hero, scroll->firstAvailableSlot(hero)));
  1336. }
  1337. break;
  1338. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  1339. {
  1340. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus->info2);
  1341. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1342. {
  1343. int val = ptr[g];
  1344. if (val == 0)
  1345. {
  1346. continue;
  1347. }
  1348. auto bb = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, *scenarioOps->campState->currentMap, g);
  1349. hero->addNewBonus(bb);
  1350. }
  1351. }
  1352. break;
  1353. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  1354. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  1355. break;
  1356. }
  1357. }
  1358. }
  1359. void CGameState::removeSightnObj(const CGObjectInstance * obj)
  1360. {
  1361. addSightObj(obj, false);
  1362. }
  1363. void CGameState::addSightObj(const CGObjectInstance * obj, bool add)
  1364. {
  1365. assert(obj);
  1366. if(!vstd::contains(players, obj->tempOwner))
  1367. return;
  1368. auto p = getPlayer(obj->tempOwner);
  1369. if(p->status != EPlayerStatus::INGAME)
  1370. return;
  1371. addSightObj(p->team, obj, add);
  1372. }
  1373. void CGameState::addSightObj(TeamID team, const CGObjectInstance * obj, bool add)
  1374. {
  1375. auto ts = getTeam(team);
  1376. std::unordered_set<int3, ShashInt3> tiles;
  1377. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius());
  1378. for(int3 t : tiles)
  1379. {
  1380. /// This code expect that tile can't be within sight range of more than 254 player-owned objects
  1381. /// Assert is best way to do these checks since if they fail that's mean code is broken
  1382. assert(ts->fogOfWarMap[t.x][t.y][t.z] != 255);
  1383. if(add)
  1384. {
  1385. if(ts->fogOfWarMap[t.x][t.y][t.z] == FoWChange::HIDDEN)
  1386. ts->fogOfWarMap[t.x][t.y][t.z] = FoWChange::WITHIN_SIGHT_RANGE; //Object revealed tile
  1387. else
  1388. ts->fogOfWarMap[t.x][t.y][t.z]++; //One more object have sight over tile
  1389. }
  1390. else
  1391. {
  1392. /// There was no objects with sight over this tile, but for some reason we try to remove sight anyway
  1393. /// That's mean when ownership or sight radius of object changed sight map wasn't appropriately updated
  1394. assert(ts->fogOfWarMap[t.x][t.y][t.z] == FoWChange::REVEALED);
  1395. ts->fogOfWarMap[t.x][t.y][t.z]--;
  1396. }
  1397. }
  1398. }
  1399. void CGameState::initSightMap()
  1400. {
  1401. for(CGObjectInstance * obj : map->objects)
  1402. {
  1403. if(!obj)
  1404. continue; //not a flagged object
  1405. addSightObj(obj);
  1406. }
  1407. }
  1408. void CGameState::initFogOfWar()
  1409. {
  1410. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  1411. for(auto & elem : teams)
  1412. {
  1413. elem.second.fogOfWarMap.resize(map->width);
  1414. for(int g=0; g<map->width; ++g)
  1415. elem.second.fogOfWarMap[g].resize(map->height);
  1416. for(int g=-0; g<map->width; ++g)
  1417. for(int h=0; h<map->height; ++h)
  1418. elem.second.fogOfWarMap[g][h].resize(map->twoLevel ? 2 : 1, 0);
  1419. for(int g=0; g<map->width; ++g)
  1420. for(int h=0; h<map->height; ++h)
  1421. for(int v = 0; v < (map->twoLevel ? 2 : 1); ++v)
  1422. elem.second.fogOfWarMap[g][h][v] = 0;
  1423. }
  1424. }
  1425. void CGameState::initStartingBonus()
  1426. {
  1427. logGlobal->debug("\tStarting bonuses");
  1428. for(auto & elem : players)
  1429. {
  1430. //starting bonus
  1431. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  1432. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(getRandomGenerator().nextInt(2));
  1433. switch(scenarioOps->playerInfos[elem.first].bonus)
  1434. {
  1435. case PlayerSettings::GOLD:
  1436. elem.second.resources[Res::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  1437. break;
  1438. case PlayerSettings::RESOURCE:
  1439. {
  1440. int res = VLC->townh->factions[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  1441. if(res == Res::WOOD_AND_ORE)
  1442. {
  1443. int amount = getRandomGenerator().nextInt(5, 10);
  1444. elem.second.resources[Res::WOOD] += amount;
  1445. elem.second.resources[Res::ORE] += amount;
  1446. }
  1447. else
  1448. {
  1449. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  1450. }
  1451. break;
  1452. }
  1453. case PlayerSettings::ARTIFACT:
  1454. {
  1455. if(!elem.second.heroes.size())
  1456. {
  1457. logGlobal->error("Cannot give starting artifact - no heroes!");
  1458. break;
  1459. }
  1460. CArtifact *toGive;
  1461. toGive = VLC->arth->artifacts[VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE)];
  1462. CGHeroInstance *hero = elem.second.heroes[0];
  1463. giveHeroArtifact(hero, toGive->id);
  1464. }
  1465. break;
  1466. }
  1467. }
  1468. }
  1469. void CGameState::initTowns()
  1470. {
  1471. logGlobal->debug("\tTowns");
  1472. //campaign bonuses for towns
  1473. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1474. {
  1475. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1476. if (chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1477. {
  1478. for (int g=0; g<map->towns.size(); ++g)
  1479. {
  1480. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1481. if (owner)
  1482. {
  1483. PlayerInfo & pi = map->players[owner->color.getNum()];
  1484. if (owner->human && //human-owned
  1485. map->towns[g]->pos == pi.posOfMainTown)
  1486. {
  1487. map->towns[g]->builtBuildings.insert(
  1488. CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->subID, map->towns[g]->builtBuildings));
  1489. break;
  1490. }
  1491. }
  1492. }
  1493. }
  1494. }
  1495. CGTownInstance::universitySkills.clear();
  1496. for ( int i=0; i<4; i++)
  1497. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1498. for (auto & elem : map->towns)
  1499. {
  1500. CGTownInstance * vti =(elem);
  1501. if(!vti->town)
  1502. {
  1503. vti->town = VLC->townh->factions[vti->subID]->town;
  1504. }
  1505. if(vti->name.empty())
  1506. {
  1507. vti->name = *RandomGeneratorUtil::nextItem(vti->town->names, getRandomGenerator());
  1508. }
  1509. //init buildings
  1510. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  1511. {
  1512. vti->builtBuildings.erase(BuildingID::DEFAULT);
  1513. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1514. if(vti->tempOwner != PlayerColor::NEUTRAL)
  1515. vti->builtBuildings.insert(BuildingID::TAVERN);
  1516. vti->builtBuildings.insert(BuildingID::DWELL_FIRST);
  1517. if(getRandomGenerator().nextInt(1) == 1)
  1518. {
  1519. vti->builtBuildings.insert(BuildingID::DWELL_LVL_2);
  1520. }
  1521. }
  1522. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  1523. vstd::erase_if(vti->builtBuildings, [vti](BuildingID bid){
  1524. return !vti->town->buildings.count(bid) || !vti->town->buildings.at(bid); });
  1525. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  1526. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1527. //init hordes
  1528. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1529. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1530. {
  1531. vti->builtBuildings.erase(BuildingID(-31-i));//remove old ID
  1532. if (vti->town->hordeLvl.at(0) == i)//if town first horde is this one
  1533. {
  1534. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  1535. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))//if we have upgraded dwelling as well
  1536. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  1537. }
  1538. if (vti->town->hordeLvl.at(1) == i)//if town second horde is this one
  1539. {
  1540. vti->builtBuildings.insert(BuildingID::HORDE_2);
  1541. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))
  1542. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  1543. }
  1544. }
  1545. //Early check for #1444-like problems
  1546. for(auto building : vti->builtBuildings)
  1547. {
  1548. assert(vti->town->buildings.at(building) != nullptr);
  1549. UNUSED(building);
  1550. }
  1551. //town events
  1552. for(CCastleEvent &ev : vti->events)
  1553. {
  1554. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1555. if (vstd::contains(ev.buildings,(-31-i))) //if we have horde for this level
  1556. {
  1557. ev.buildings.erase(BuildingID(-31-i));
  1558. if (vti->town->hordeLvl.at(0) == i)
  1559. ev.buildings.insert(BuildingID::HORDE_1);
  1560. if (vti->town->hordeLvl.at(1) == i)
  1561. ev.buildings.insert(BuildingID::HORDE_2);
  1562. }
  1563. }
  1564. //init spells
  1565. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1566. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1567. {
  1568. auto s = vti->obligatorySpells[z].toSpell();
  1569. vti->spells[s->level-1].push_back(s->id);
  1570. vti->possibleSpells -= s->id;
  1571. }
  1572. while(vti->possibleSpells.size())
  1573. {
  1574. ui32 total=0;
  1575. int sel = -1;
  1576. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1577. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->subID);
  1578. if (total == 0) // remaining spells have 0 probability
  1579. break;
  1580. auto r = getRandomGenerator().nextInt(total - 1);
  1581. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1582. {
  1583. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->subID);
  1584. if(r<0)
  1585. {
  1586. sel = ps;
  1587. break;
  1588. }
  1589. }
  1590. if(sel<0)
  1591. sel=0;
  1592. auto s = vti->possibleSpells[sel].toSpell();
  1593. vti->spells[s->level-1].push_back(s->id);
  1594. vti->possibleSpells -= s->id;
  1595. }
  1596. vti->possibleSpells.clear();
  1597. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1598. getPlayer(vti->getOwner())->towns.push_back(vti);
  1599. }
  1600. }
  1601. void CGameState::initMapObjects()
  1602. {
  1603. logGlobal->debug("\tObject initialization");
  1604. // objCaller->preInit();
  1605. for(CGObjectInstance *obj : map->objects)
  1606. {
  1607. if(obj)
  1608. {
  1609. logGlobal->trace("Calling Init for object %d, %s, %s", obj->id.getNum(), obj->typeName, obj->subTypeName);
  1610. obj->initObj(getRandomGenerator());
  1611. }
  1612. }
  1613. for(CGObjectInstance *obj : map->objects)
  1614. {
  1615. if(!obj)
  1616. continue;
  1617. switch (obj->ID)
  1618. {
  1619. case Obj::QUEST_GUARD:
  1620. case Obj::SEER_HUT:
  1621. {
  1622. auto q = static_cast<CGSeerHut*>(obj);
  1623. assert (q);
  1624. q->setObjToKill();
  1625. }
  1626. }
  1627. }
  1628. CGSubterraneanGate::postInit(); //pairing subterranean gates
  1629. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  1630. }
  1631. void CGameState::initVisitingAndGarrisonedHeroes()
  1632. {
  1633. for(auto k=players.begin(); k!=players.end(); ++k)
  1634. {
  1635. if(k->first==PlayerColor::NEUTRAL)
  1636. continue;
  1637. //init visiting and garrisoned heroes
  1638. for(CGHeroInstance *h : k->second.heroes)
  1639. {
  1640. for(CGTownInstance *t : k->second.towns)
  1641. {
  1642. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1643. if(vistile == h->pos || h->pos==t->pos)
  1644. {
  1645. t->setVisitingHero(h);
  1646. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1647. {
  1648. map->removeBlockVisTiles(h);
  1649. h->pos.x -= 1;
  1650. map->addBlockVisTiles(h);
  1651. }
  1652. break;
  1653. }
  1654. }
  1655. }
  1656. }
  1657. for (auto hero : map->heroesOnMap)
  1658. {
  1659. if (hero->visitedTown)
  1660. {
  1661. assert (hero->visitedTown->visitingHero == hero);
  1662. }
  1663. }
  1664. }
  1665. BFieldType CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  1666. {
  1667. if(!tile.valid() && curB)
  1668. tile = curB->tile;
  1669. else if(!tile.valid() && !curB)
  1670. return BFieldType::NONE;
  1671. const TerrainTile &t = map->getTile(tile);
  1672. //fight in mine -> subterranean
  1673. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1674. return BFieldType::SUBTERRANEAN;
  1675. for(auto &obj : map->objects)
  1676. {
  1677. //look only for objects covering given tile
  1678. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  1679. continue;
  1680. switch(obj->ID)
  1681. {
  1682. case Obj::CLOVER_FIELD:
  1683. return BFieldType::CLOVER_FIELD;
  1684. case Obj::CURSED_GROUND1: case Obj::CURSED_GROUND2:
  1685. return BFieldType::CURSED_GROUND;
  1686. case Obj::EVIL_FOG:
  1687. return BFieldType::EVIL_FOG;
  1688. case Obj::FAVORABLE_WINDS:
  1689. return BFieldType::FAVORABLE_WINDS;
  1690. case Obj::FIERY_FIELDS:
  1691. return BFieldType::FIERY_FIELDS;
  1692. case Obj::HOLY_GROUNDS:
  1693. return BFieldType::HOLY_GROUND;
  1694. case Obj::LUCID_POOLS:
  1695. return BFieldType::LUCID_POOLS;
  1696. case Obj::MAGIC_CLOUDS:
  1697. return BFieldType::MAGIC_CLOUDS;
  1698. case Obj::MAGIC_PLAINS1: case Obj::MAGIC_PLAINS2:
  1699. return BFieldType::MAGIC_PLAINS;
  1700. case Obj::ROCKLANDS:
  1701. return BFieldType::ROCKLANDS;
  1702. }
  1703. }
  1704. if(map->isCoastalTile(tile)) //coastal tile is always ground
  1705. return BFieldType::SAND_SHORE;
  1706. switch(t.terType)
  1707. {
  1708. case ETerrainType::DIRT:
  1709. return BFieldType(rand.nextInt(3, 5));
  1710. case ETerrainType::SAND:
  1711. return BFieldType::SAND_MESAS; //TODO: coast support
  1712. case ETerrainType::GRASS:
  1713. return BFieldType(rand.nextInt(6, 7));
  1714. case ETerrainType::SNOW:
  1715. return BFieldType(rand.nextInt(10, 11));
  1716. case ETerrainType::SWAMP:
  1717. return BFieldType::SWAMP_TREES;
  1718. case ETerrainType::ROUGH:
  1719. return BFieldType::ROUGH;
  1720. case ETerrainType::SUBTERRANEAN:
  1721. return BFieldType::SUBTERRANEAN;
  1722. case ETerrainType::LAVA:
  1723. return BFieldType::LAVA;
  1724. case ETerrainType::WATER:
  1725. return BFieldType::SHIP;
  1726. case ETerrainType::ROCK:
  1727. return BFieldType::ROCKLANDS;
  1728. default:
  1729. return BFieldType::NONE;
  1730. }
  1731. }
  1732. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1733. {
  1734. UpgradeInfo ret;
  1735. const CCreature *base = stack.type;
  1736. const CGHeroInstance *h = stack.armyObj->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(stack.armyObj) : nullptr;
  1737. const CGTownInstance *t = nullptr;
  1738. if(stack.armyObj->ID == Obj::TOWN)
  1739. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1740. else if(h)
  1741. { //hero specialty
  1742. TBonusListPtr lista = h->getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1743. for(const std::shared_ptr<Bonus> it : *lista)
  1744. {
  1745. auto nid = CreatureID(it->additionalInfo);
  1746. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1747. {
  1748. ret.newID.push_back(nid);
  1749. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1750. }
  1751. }
  1752. t = h->visitedTown;
  1753. }
  1754. if(t)
  1755. {
  1756. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : t->creatures)
  1757. {
  1758. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1759. {
  1760. for(auto upgrID : dwelling.second)
  1761. {
  1762. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1763. {
  1764. ret.newID.push_back(upgrID);
  1765. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1766. }
  1767. }
  1768. }
  1769. }
  1770. }
  1771. //hero is visiting Hill Fort
  1772. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == Obj::HILL_FORT)
  1773. {
  1774. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1775. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1776. for(auto nid : base->upgrades)
  1777. {
  1778. ret.newID.push_back(nid);
  1779. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1780. }
  1781. }
  1782. if(ret.newID.size())
  1783. ret.oldID = base->idNumber;
  1784. for (Res::ResourceSet &cost : ret.cost)
  1785. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1786. return ret;
  1787. }
  1788. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 )
  1789. {
  1790. if ( color1 == color2 )
  1791. return PlayerRelations::SAME_PLAYER;
  1792. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1793. return PlayerRelations::ENEMIES;
  1794. const TeamState * ts = getPlayerTeam(color1);
  1795. if (ts && vstd::contains(ts->players, color2))
  1796. return PlayerRelations::ALLIES;
  1797. return PlayerRelations::ENEMIES;
  1798. }
  1799. void CGameState::apply(CPack *pack)
  1800. {
  1801. ui16 typ = typeList.getTypeID(pack);
  1802. applierGs->getApplier(typ)->applyOnGS(this,pack);
  1803. }
  1804. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  1805. {
  1806. CPathfinder pathfinder(out, this, hero);
  1807. pathfinder.calculatePaths();
  1808. }
  1809. /**
  1810. * Tells if the tile is guarded by a monster as well as the position
  1811. * of the monster that will attack on it.
  1812. *
  1813. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1814. * the monster guarding the tile.
  1815. */
  1816. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1817. {
  1818. std::vector<CGObjectInstance*> guards;
  1819. const int3 originalPos = pos;
  1820. if (!map->isInTheMap(pos))
  1821. return guards;
  1822. const TerrainTile &posTile = map->getTile(pos);
  1823. if (posTile.visitable)
  1824. {
  1825. for (CGObjectInstance* obj : posTile.visitableObjects)
  1826. {
  1827. if(obj->blockVisit)
  1828. {
  1829. if (obj->ID == Obj::MONSTER) // Monster
  1830. guards.push_back(obj);
  1831. }
  1832. }
  1833. }
  1834. pos -= int3(1, 1, 0); // Start with top left.
  1835. for (int dx = 0; dx < 3; dx++)
  1836. {
  1837. for (int dy = 0; dy < 3; dy++)
  1838. {
  1839. if (map->isInTheMap(pos))
  1840. {
  1841. const auto & tile = map->getTile(pos);
  1842. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1843. {
  1844. for (CGObjectInstance* obj : tile.visitableObjects)
  1845. {
  1846. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1847. {
  1848. guards.push_back(obj);
  1849. }
  1850. }
  1851. }
  1852. }
  1853. pos.y++;
  1854. }
  1855. pos.y -= 3;
  1856. pos.x++;
  1857. }
  1858. return guards;
  1859. }
  1860. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1861. {
  1862. return gs->map->guardingCreaturePositions[pos.x][pos.y][pos.z];
  1863. }
  1864. void CGameState::updateRumor()
  1865. {
  1866. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1867. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1868. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1869. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1870. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1871. int rumorId = -1, rumorExtra = -1;
  1872. auto & rand = getRandomGenerator();
  1873. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1874. do
  1875. {
  1876. switch(rumor.type)
  1877. {
  1878. case RumorState::TYPE_SPECIAL:
  1879. {
  1880. SThievesGuildInfo tgi;
  1881. obtainPlayersStats(tgi, 20);
  1882. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1883. if(rumorId == RumorState::RUMOR_GRAIL)
  1884. {
  1885. rumorExtra = getTile(map->grailPos)->terType;
  1886. break;
  1887. }
  1888. std::vector<PlayerColor> players = {};
  1889. switch(rumorId)
  1890. {
  1891. case RumorState::RUMOR_OBELISKS:
  1892. players = tgi.obelisks[0];
  1893. break;
  1894. case RumorState::RUMOR_ARTIFACTS:
  1895. players = tgi.artifacts[0];
  1896. break;
  1897. case RumorState::RUMOR_ARMY:
  1898. players = tgi.army[0];
  1899. break;
  1900. case RumorState::RUMOR_INCOME:
  1901. players = tgi.income[0];
  1902. break;
  1903. }
  1904. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1905. break;
  1906. }
  1907. case RumorState::TYPE_MAP:
  1908. // Makes sure that map rumors only used if there enough rumors too choose from
  1909. if(map->rumors.size() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1910. {
  1911. rumorId = rand.nextInt(map->rumors.size() - 1);
  1912. break;
  1913. }
  1914. else
  1915. rumor.type = RumorState::TYPE_RAND;
  1916. case RumorState::TYPE_RAND:
  1917. do
  1918. {
  1919. rumorId = rand.nextInt(VLC->generaltexth->tavernRumors.size() - 1);
  1920. }
  1921. while(!VLC->generaltexth->tavernRumors[rumorId].length());
  1922. break;
  1923. }
  1924. }
  1925. while(!rumor.update(rumorId, rumorExtra));
  1926. }
  1927. bool CGameState::isVisible(int3 pos, PlayerColor player)
  1928. {
  1929. if(player == PlayerColor::NEUTRAL)
  1930. return false;
  1931. if(player.isSpectator())
  1932. return true;
  1933. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  1934. }
  1935. bool CGameState::isVisible( const CGObjectInstance *obj, boost::optional<PlayerColor> player )
  1936. {
  1937. if(!player)
  1938. return true;
  1939. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1940. if (player == obj->tempOwner)
  1941. return true;
  1942. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1943. return false;
  1944. //object is visible when at least one blocked tile is visible
  1945. for(int fy=0; fy < obj->getHeight(); ++fy)
  1946. {
  1947. for(int fx=0; fx < obj->getWidth(); ++fx)
  1948. {
  1949. int3 pos = obj->pos + int3(-fx, -fy, 0);
  1950. if ( map->isInTheMap(pos) &&
  1951. obj->coveringAt(pos.x, pos.y) &&
  1952. isVisible(pos, *player))
  1953. return true;
  1954. }
  1955. }
  1956. return false;
  1957. }
  1958. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1959. {
  1960. const TerrainTile * pom = &map->getTile(dst);
  1961. return map->checkForVisitableDir(src, pom, dst);
  1962. }
  1963. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(PlayerColor player) const
  1964. {
  1965. const std::string & messageWonSelf = VLC->generaltexth->allTexts[659];
  1966. const std::string & messageWonOther = VLC->generaltexth->allTexts[5];
  1967. const std::string & messageLostSelf = VLC->generaltexth->allTexts[7];
  1968. const std::string & messageLostOther = VLC->generaltexth->allTexts[8];
  1969. auto evaluateEvent = [=](const EventCondition & condition)
  1970. {
  1971. return this->checkForVictory(player, condition);
  1972. };
  1973. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1974. //cheater or tester, but has entered the code...
  1975. if (p->enteredWinningCheatCode)
  1976. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1977. if (p->enteredLosingCheatCode)
  1978. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1979. for (const TriggeredEvent & event : map->triggeredEvents)
  1980. {
  1981. if (event.trigger.test(evaluateEvent))
  1982. {
  1983. if (event.effect.type == EventEffect::VICTORY)
  1984. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1985. if (event.effect.type == EventEffect::DEFEAT)
  1986. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1987. }
  1988. }
  1989. if (checkForStandardLoss(player))
  1990. {
  1991. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1992. }
  1993. return EVictoryLossCheckResult();
  1994. }
  1995. bool CGameState::checkForVictory(PlayerColor player, const EventCondition & condition) const
  1996. {
  1997. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1998. switch (condition.condition)
  1999. {
  2000. case EventCondition::STANDARD_WIN:
  2001. {
  2002. return player == checkForStandardWin();
  2003. }
  2004. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  2005. {
  2006. for(auto & elem : p->heroes)
  2007. if(elem->hasArt(condition.objectType))
  2008. return true;
  2009. return false;
  2010. }
  2011. case EventCondition::HAVE_CREATURES:
  2012. {
  2013. //check if in players armies there is enough creatures
  2014. int total = 0; //creature counter
  2015. for(size_t i = 0; i < map->objects.size(); i++)
  2016. {
  2017. const CArmedInstance *ai = nullptr;
  2018. if(map->objects[i]
  2019. && map->objects[i]->tempOwner == player //object controlled by player
  2020. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  2021. {
  2022. for(auto & elem : ai->Slots()) //iterate through army
  2023. if(elem.second->type->idNumber == condition.objectType) //it's searched creature
  2024. total += elem.second->count;
  2025. }
  2026. }
  2027. return total >= condition.value;
  2028. }
  2029. case EventCondition::HAVE_RESOURCES:
  2030. {
  2031. return p->resources[condition.objectType] >= condition.value;
  2032. }
  2033. case EventCondition::HAVE_BUILDING:
  2034. {
  2035. if (condition.object) // specific town
  2036. {
  2037. const CGTownInstance *t = static_cast<const CGTownInstance *>(condition.object);
  2038. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  2039. }
  2040. else // any town
  2041. {
  2042. for (const CGTownInstance * t : p->towns)
  2043. {
  2044. if (t->hasBuilt(BuildingID(condition.objectType)))
  2045. return true;
  2046. }
  2047. return false;
  2048. }
  2049. }
  2050. case EventCondition::DESTROY:
  2051. {
  2052. if (condition.object) // mode A - destroy specific object of this type
  2053. {
  2054. if (auto hero = dynamic_cast<const CGHeroInstance*>(condition.object))
  2055. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  2056. else
  2057. return getObj(condition.object->id) == nullptr;
  2058. }
  2059. else
  2060. {
  2061. for(auto & elem : map->objects) // mode B - destroy all objects of this type
  2062. {
  2063. if(elem && elem->ID == condition.objectType)
  2064. return false;
  2065. }
  2066. return true;
  2067. }
  2068. }
  2069. case EventCondition::CONTROL:
  2070. {
  2071. // list of players that need to control object to fulfull condition
  2072. // NOTE: cgameinfocallback specified explicitly in order to get const version
  2073. auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  2074. if (condition.object) // mode A - flag one specific object, like town
  2075. {
  2076. return team.count(condition.object->tempOwner) != 0;
  2077. }
  2078. else
  2079. {
  2080. for(auto & elem : map->objects) // mode B - flag all objects of this type
  2081. {
  2082. //check not flagged objs
  2083. if ( elem && elem->ID == condition.objectType && team.count(elem->tempOwner) == 0 )
  2084. return false;
  2085. }
  2086. return true;
  2087. }
  2088. }
  2089. case EventCondition::TRANSPORT:
  2090. {
  2091. const CGTownInstance *t = static_cast<const CGTownInstance *>(condition.object);
  2092. if((t->visitingHero && t->visitingHero->hasArt(condition.objectType))
  2093. || (t->garrisonHero && t->garrisonHero->hasArt(condition.objectType)))
  2094. {
  2095. return true;
  2096. }
  2097. return false;
  2098. }
  2099. case EventCondition::DAYS_PASSED:
  2100. {
  2101. return gs->day > condition.value;
  2102. }
  2103. case EventCondition::IS_HUMAN:
  2104. {
  2105. return p->human ? condition.value == 1 : condition.value == 0;
  2106. }
  2107. case EventCondition::DAYS_WITHOUT_TOWN:
  2108. {
  2109. if (p->daysWithoutCastle)
  2110. return p->daysWithoutCastle.get() >= condition.value;
  2111. else
  2112. return false;
  2113. }
  2114. case EventCondition::CONST_VALUE:
  2115. {
  2116. return condition.value; // just convert to bool
  2117. }
  2118. case EventCondition::HAVE_0:
  2119. {
  2120. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2121. //TODO: support new condition format
  2122. return false;
  2123. }
  2124. case EventCondition::HAVE_BUILDING_0:
  2125. {
  2126. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2127. //TODO: support new condition format
  2128. return false;
  2129. }
  2130. case EventCondition::DESTROY_0:
  2131. {
  2132. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2133. //TODO: support new condition format
  2134. return false;
  2135. }
  2136. default:
  2137. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  2138. return false;
  2139. }
  2140. }
  2141. PlayerColor CGameState::checkForStandardWin() const
  2142. {
  2143. //std victory condition is:
  2144. //all enemies lost
  2145. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  2146. TeamID winnerTeam = TeamID::NO_TEAM;
  2147. for(auto & elem : players)
  2148. {
  2149. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  2150. {
  2151. if(supposedWinner == PlayerColor::NEUTRAL)
  2152. {
  2153. //first player remaining ingame - candidate for victory
  2154. supposedWinner = elem.second.color;
  2155. winnerTeam = elem.second.team;
  2156. }
  2157. else if(winnerTeam != elem.second.team)
  2158. {
  2159. //current candidate has enemy remaining in game -> no vicotry
  2160. return PlayerColor::NEUTRAL;
  2161. }
  2162. }
  2163. }
  2164. return supposedWinner;
  2165. }
  2166. bool CGameState::checkForStandardLoss( PlayerColor player ) const
  2167. {
  2168. //std loss condition is: player lost all towns and heroes
  2169. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  2170. return !p.heroes.size() && !p.towns.size();
  2171. }
  2172. struct statsHLP
  2173. {
  2174. typedef std::pair< PlayerColor, si64 > TStat;
  2175. //converts [<player's color, value>] to vec[place] -> platers
  2176. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  2177. {
  2178. std::sort(stats.begin(), stats.end(), statsHLP());
  2179. //put first element
  2180. std::vector< std::vector<PlayerColor> > ret;
  2181. std::vector<PlayerColor> tmp;
  2182. tmp.push_back( stats[0].first );
  2183. ret.push_back( tmp );
  2184. //the rest of elements
  2185. for(int g=1; g<stats.size(); ++g)
  2186. {
  2187. if(stats[g].second == stats[g-1].second)
  2188. {
  2189. (ret.end()-1)->push_back( stats[g].first );
  2190. }
  2191. else
  2192. {
  2193. //create next occupied rank
  2194. std::vector<PlayerColor> tmp;
  2195. tmp.push_back(stats[g].first);
  2196. ret.push_back(tmp);
  2197. }
  2198. }
  2199. return ret;
  2200. }
  2201. bool operator()(const TStat & a, const TStat & b) const
  2202. {
  2203. return a.second > b.second;
  2204. }
  2205. static const CGHeroInstance * findBestHero(CGameState * gs, PlayerColor color)
  2206. {
  2207. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2208. if(!h.size())
  2209. return nullptr;
  2210. //best hero will be that with highest exp
  2211. int best = 0;
  2212. for(int b=1; b<h.size(); ++b)
  2213. {
  2214. if(h[b]->exp > h[best]->exp)
  2215. {
  2216. best = b;
  2217. }
  2218. }
  2219. return h[best];
  2220. }
  2221. //calculates total number of artifacts that belong to given player
  2222. static int getNumberOfArts(const PlayerState * ps)
  2223. {
  2224. int ret = 0;
  2225. for(auto h : ps->heroes)
  2226. {
  2227. ret += h->artifactsInBackpack.size() + h->artifactsWorn.size();
  2228. }
  2229. return ret;
  2230. }
  2231. // get total strength of player army
  2232. static si64 getArmyStrength(const PlayerState * ps)
  2233. {
  2234. si64 str = 0;
  2235. for(auto h : ps->heroes)
  2236. {
  2237. if(!h->inTownGarrison) //original h3 behavior
  2238. str += h->getArmyStrength();
  2239. }
  2240. return str;
  2241. }
  2242. // get total gold income
  2243. static int getIncome(const PlayerState * ps)
  2244. {
  2245. int totalIncome = 0;
  2246. const CGObjectInstance * heroOrTown = nullptr;
  2247. //Heroes can produce gold as well - skill, specialty or arts
  2248. for(auto & h : ps->heroes)
  2249. {
  2250. totalIncome += h->valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ESTATES));
  2251. totalIncome += h->valOfBonuses(Selector::typeSubtype(Bonus::GENERATE_RESOURCE, Res::GOLD));
  2252. if(!heroOrTown)
  2253. heroOrTown = h;
  2254. }
  2255. //Add town income of all towns
  2256. for(auto & t : ps->towns)
  2257. {
  2258. totalIncome += t->dailyIncome()[Res::GOLD];
  2259. if(!heroOrTown)
  2260. heroOrTown = t;
  2261. }
  2262. /// FIXME: Dirty dirty hack
  2263. /// Stats helper need some access to gamestate.
  2264. std::vector<const CGObjectInstance *> ownedObjects;
  2265. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  2266. {
  2267. if(obj && obj->tempOwner == ps->color)
  2268. ownedObjects.push_back(obj);
  2269. }
  2270. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  2271. /// I'm really need to find out about callback interface design...
  2272. for(auto object : ownedObjects)
  2273. {
  2274. //Mines
  2275. if ( object->ID == Obj::MINE )
  2276. {
  2277. const CGMine *mine = dynamic_cast<const CGMine*>(object);
  2278. assert(mine);
  2279. if (mine->producedResource == Res::GOLD)
  2280. totalIncome += mine->producedQuantity;
  2281. }
  2282. }
  2283. return totalIncome;
  2284. }
  2285. };
  2286. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2287. {
  2288. auto playerInactive = [&](PlayerColor color)
  2289. {
  2290. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  2291. };
  2292. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2293. { \
  2294. std::vector< std::pair< PlayerColor, si64 > > stats; \
  2295. for(auto g = players.begin(); g != players.end(); ++g) \
  2296. { \
  2297. if(playerInactive(g->second.color)) \
  2298. continue; \
  2299. std::pair< PlayerColor, si64 > stat; \
  2300. stat.first = g->second.color; \
  2301. stat.second = VAL_GETTER; \
  2302. stats.push_back(stat); \
  2303. } \
  2304. tgi.FIELD = statsHLP::getRank(stats); \
  2305. }
  2306. for(auto & elem : players)
  2307. {
  2308. if(!playerInactive(elem.second.color))
  2309. tgi.playerColors.push_back(elem.second.color);
  2310. }
  2311. if(level >= 0) //num of towns & num of heroes
  2312. {
  2313. //num of towns
  2314. FILL_FIELD(numOfTowns, g->second.towns.size())
  2315. //num of heroes
  2316. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2317. }
  2318. if(level >= 1) //best hero's portrait
  2319. {
  2320. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2321. {
  2322. if(playerInactive(g->second.color))
  2323. continue;
  2324. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2325. InfoAboutHero iah;
  2326. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  2327. iah.army.clear();
  2328. tgi.colorToBestHero[g->second.color] = iah;
  2329. }
  2330. }
  2331. if(level >= 2) //gold
  2332. {
  2333. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2334. }
  2335. if(level >= 2) //wood & ore
  2336. {
  2337. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2338. }
  2339. if(level >= 3) //mercury, sulfur, crystal, gems
  2340. {
  2341. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2342. }
  2343. if(level >= 3) //obelisks found
  2344. {
  2345. auto getObeliskVisited = [](TeamID t)
  2346. {
  2347. if(CGObelisk::visited.count(t))
  2348. return CGObelisk::visited[t];
  2349. else
  2350. return ui8(0);
  2351. };
  2352. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  2353. }
  2354. if(level >= 4) //artifacts
  2355. {
  2356. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2357. }
  2358. if(level >= 4) //army strength
  2359. {
  2360. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2361. }
  2362. if(level >= 5) //income
  2363. {
  2364. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  2365. }
  2366. if(level >= 2) //best hero's stats
  2367. {
  2368. //already set in lvl 1 handling
  2369. }
  2370. if(level >= 3) //personality
  2371. {
  2372. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2373. {
  2374. if(playerInactive(g->second.color)) //do nothing for neutral player
  2375. continue;
  2376. if(g->second.human)
  2377. {
  2378. tgi.personality[g->second.color] = EAiTactic::NONE;
  2379. }
  2380. else //AI
  2381. {
  2382. tgi.personality[g->second.color] = map->players[g->second.color.getNum()].aiTactic;
  2383. }
  2384. }
  2385. }
  2386. if(level >= 4) //best creature
  2387. {
  2388. //best creatures belonging to player (highest AI value)
  2389. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2390. {
  2391. if(playerInactive(g->second.color)) //do nothing for neutral player
  2392. continue;
  2393. int bestCre = -1; //best creature's ID
  2394. for(auto & elem : g->second.heroes)
  2395. {
  2396. for(auto it = elem->Slots().begin(); it != elem->Slots().end(); ++it)
  2397. {
  2398. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2399. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2400. {
  2401. bestCre = toCmp;
  2402. }
  2403. }
  2404. }
  2405. tgi.bestCreature[g->second.color] = bestCre;
  2406. }
  2407. }
  2408. #undef FILL_FIELD
  2409. }
  2410. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2411. {
  2412. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2413. for ( auto i = players.cbegin() ; i != players.cend();i++)
  2414. for(auto j = i->second.availableHeroes.cbegin(); j != i->second.availableHeroes.cend(); j++)
  2415. if(*j)
  2416. pool.erase((**j).subID);
  2417. return pool;
  2418. }
  2419. void CGameState::buildBonusSystemTree()
  2420. {
  2421. buildGlobalTeamPlayerTree();
  2422. attachArmedObjects();
  2423. for(CGTownInstance *t : map->towns)
  2424. {
  2425. t->deserializationFix();
  2426. }
  2427. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2428. // are provided on initializing / deserializing
  2429. }
  2430. void CGameState::deserializationFix()
  2431. {
  2432. buildGlobalTeamPlayerTree();
  2433. attachArmedObjects();
  2434. }
  2435. void CGameState::buildGlobalTeamPlayerTree()
  2436. {
  2437. for(auto k=teams.begin(); k!=teams.end(); ++k)
  2438. {
  2439. TeamState *t = &k->second;
  2440. t->attachTo(&globalEffects);
  2441. for(PlayerColor teamMember : k->second.players)
  2442. {
  2443. PlayerState *p = getPlayer(teamMember);
  2444. assert(p);
  2445. p->attachTo(t);
  2446. }
  2447. }
  2448. }
  2449. void CGameState::attachArmedObjects()
  2450. {
  2451. for(CGObjectInstance *obj : map->objects)
  2452. {
  2453. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2454. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2455. }
  2456. }
  2457. void CGameState::giveHeroArtifact(CGHeroInstance *h, ArtifactID aid)
  2458. {
  2459. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2460. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2461. map->addNewArtifactInstance(ai);
  2462. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2463. }
  2464. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  2465. {
  2466. std::set<HeroTypeID> ret;
  2467. for(int i = 0; i < map->allowedHeroes.size(); i++)
  2468. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  2469. ret.insert(HeroTypeID(i));
  2470. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2471. {
  2472. if(hero->type)
  2473. ret -= hero->type->ID;
  2474. else
  2475. ret -= HeroTypeID(hero->subID);
  2476. }
  2477. for(auto obj : map->objects) //prisons
  2478. if(obj && obj->ID == Obj::PRISON)
  2479. ret -= HeroTypeID(obj->subID);
  2480. return ret;
  2481. }
  2482. std::vector<CGameState::CampaignHeroReplacement> CGameState::generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes)
  2483. {
  2484. std::vector<CampaignHeroReplacement> campaignHeroReplacements;
  2485. //selecting heroes by type
  2486. for(auto obj : map->objects)
  2487. {
  2488. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2489. {
  2490. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2491. if(heroPlaceholder->subID != 0xFF) //select by type
  2492. {
  2493. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [heroPlaceholder](CGHeroInstance * hero)
  2494. {
  2495. return hero->subID == heroPlaceholder->subID;
  2496. });
  2497. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  2498. {
  2499. auto hero = *it;
  2500. crossoverHeroes.removeHeroFromBothLists(hero);
  2501. campaignHeroReplacements.push_back(CampaignHeroReplacement(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id));
  2502. }
  2503. }
  2504. }
  2505. }
  2506. //selecting heroes by power
  2507. range::sort(crossoverHeroes.heroesFromPreviousScenario, [](const CGHeroInstance * a, const CGHeroInstance * b)
  2508. {
  2509. return a->getHeroStrength() > b->getHeroStrength();
  2510. }); //sort, descending strength
  2511. // sort hero placeholders descending power
  2512. std::vector<CGHeroPlaceholder *> heroPlaceholders;
  2513. for(auto obj : map->objects)
  2514. {
  2515. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2516. {
  2517. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2518. if(heroPlaceholder->subID == 0xFF) //select by power
  2519. {
  2520. heroPlaceholders.push_back(heroPlaceholder);
  2521. }
  2522. }
  2523. }
  2524. range::sort(heroPlaceholders, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  2525. {
  2526. return a->power > b->power;
  2527. });
  2528. for(int i = 0; i < heroPlaceholders.size(); ++i)
  2529. {
  2530. auto heroPlaceholder = heroPlaceholders[i];
  2531. if(crossoverHeroes.heroesFromPreviousScenario.size() > i)
  2532. {
  2533. auto hero = crossoverHeroes.heroesFromPreviousScenario[i];
  2534. campaignHeroReplacements.push_back(CampaignHeroReplacement(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id));
  2535. }
  2536. }
  2537. return campaignHeroReplacements;
  2538. }
  2539. void CGameState::replaceHeroesPlaceholders(const std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements)
  2540. {
  2541. for(auto campaignHeroReplacement : campaignHeroReplacements)
  2542. {
  2543. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder*>(getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  2544. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  2545. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  2546. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  2547. heroToPlace->pos = heroPlaceholder->pos;
  2548. heroToPlace->type = VLC->heroh->heroes[heroToPlace->subID];
  2549. for(auto &&i : heroToPlace->stacks)
  2550. i.second->type = VLC->creh->creatures[i.second->getCreatureID()];
  2551. auto fixArtifact = [&](CArtifactInstance * art)
  2552. {
  2553. art->artType = VLC->arth->artifacts[art->artType->id];
  2554. gs->map->artInstances.push_back(art);
  2555. art->id = ArtifactInstanceID(gs->map->artInstances.size() - 1);
  2556. };
  2557. for(auto &&i : heroToPlace->artifactsWorn)
  2558. fixArtifact(i.second.artifact);
  2559. for(auto &&i : heroToPlace->artifactsInBackpack)
  2560. fixArtifact(i.artifact);
  2561. map->heroesOnMap.push_back(heroToPlace);
  2562. map->objects[heroToPlace->id.getNum()] = heroToPlace;
  2563. map->addBlockVisTiles(heroToPlace);
  2564. scenarioOps->campState->getCurrentScenario().placedCrossoverHeroes.push_back(heroToPlace);
  2565. }
  2566. }
  2567. bool CGameState::isUsedHero(HeroTypeID hid) const
  2568. {
  2569. return getUsedHero(hid);
  2570. }
  2571. CGHeroInstance * CGameState::getUsedHero(HeroTypeID hid) const
  2572. {
  2573. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2574. {
  2575. if(hero->type && hero->type->ID == hid)
  2576. {
  2577. return hero;
  2578. }
  2579. }
  2580. for(auto obj : map->objects) //prisons
  2581. {
  2582. if(obj && obj->ID == Obj::PRISON )
  2583. {
  2584. auto hero = dynamic_cast<CGHeroInstance *>(obj.get());
  2585. assert(hero);
  2586. if ( hero->type && hero->type->ID == hid )
  2587. return hero;
  2588. }
  2589. }
  2590. return nullptr;
  2591. }
  2592. PlayerState::PlayerState()
  2593. : color(-1), human(false), enteredWinningCheatCode(false),
  2594. enteredLosingCheatCode(false), status(EPlayerStatus::INGAME)
  2595. {
  2596. setNodeType(PLAYER);
  2597. }
  2598. PlayerState::PlayerState(PlayerState && other):
  2599. CBonusSystemNode(std::move(other)),
  2600. color(other.color),
  2601. human(other.human),
  2602. team(other.team),
  2603. resources(other.resources),
  2604. enteredWinningCheatCode(other.enteredWinningCheatCode),
  2605. enteredLosingCheatCode(other.enteredLosingCheatCode),
  2606. status(other.status),
  2607. daysWithoutCastle(other.daysWithoutCastle)
  2608. {
  2609. std::swap(visitedObjects, other.visitedObjects);
  2610. std::swap(heroes, other.heroes);
  2611. std::swap(towns, other.towns);
  2612. std::swap(availableHeroes, other.availableHeroes);
  2613. std::swap(dwellings, other.dwellings);
  2614. std::swap(quests, other.quests);
  2615. }
  2616. std::string PlayerState::nodeName() const
  2617. {
  2618. return "Player " + (color.getNum() < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color.getNum()] : boost::lexical_cast<std::string>(color));
  2619. }
  2620. bool RumorState::update(int id, int extra)
  2621. {
  2622. if(vstd::contains(last, type))
  2623. {
  2624. if(last[type].first != id)
  2625. {
  2626. last[type].first = id;
  2627. last[type].second = extra;
  2628. }
  2629. else
  2630. return false;
  2631. }
  2632. else
  2633. last[type] = std::make_pair(id, extra);
  2634. return true;
  2635. }
  2636. InfoAboutArmy::InfoAboutArmy():
  2637. owner(PlayerColor::NEUTRAL)
  2638. {}
  2639. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2640. {
  2641. initFromArmy(Army, detailed);
  2642. }
  2643. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2644. {
  2645. army = ArmyDescriptor(Army, detailed);
  2646. owner = Army->tempOwner;
  2647. name = Army->getObjectName();
  2648. }
  2649. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2650. {
  2651. vstd::clear_pointer(details);
  2652. InfoAboutArmy::operator = (iah);
  2653. details = (iah.details ? new Details(*iah.details) : nullptr);
  2654. hclass = iah.hclass;
  2655. portrait = iah.portrait;
  2656. }
  2657. InfoAboutHero::InfoAboutHero():
  2658. details(nullptr),
  2659. hclass(nullptr),
  2660. portrait(-1)
  2661. {}
  2662. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2663. InfoAboutArmy()
  2664. {
  2665. assign(iah);
  2666. }
  2667. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, InfoAboutHero::EInfoLevel infoLevel)
  2668. : details(nullptr),
  2669. hclass(nullptr),
  2670. portrait(-1)
  2671. {
  2672. initFromHero(h, infoLevel);
  2673. }
  2674. InfoAboutHero::~InfoAboutHero()
  2675. {
  2676. vstd::clear_pointer(details);
  2677. }
  2678. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2679. {
  2680. assign(iah);
  2681. return *this;
  2682. }
  2683. void InfoAboutHero::initFromHero(const CGHeroInstance *h, InfoAboutHero::EInfoLevel infoLevel)
  2684. {
  2685. vstd::clear_pointer(details);
  2686. if(!h)
  2687. return;
  2688. bool detailed = ( (infoLevel == EInfoLevel::DETAILED) || (infoLevel == EInfoLevel::INBATTLE) );
  2689. initFromArmy(h, detailed);
  2690. hclass = h->type->heroClass;
  2691. name = h->name;
  2692. portrait = h->portrait;
  2693. if(detailed)
  2694. {
  2695. //include details about hero
  2696. details = new Details();
  2697. details->luck = h->LuckVal();
  2698. details->morale = h->MoraleVal();
  2699. details->mana = h->mana;
  2700. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2701. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2702. {
  2703. details->primskills[i] = h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i));
  2704. }
  2705. if (infoLevel == EInfoLevel::INBATTLE)
  2706. details->manaLimit = h->manaLimit();
  2707. else
  2708. details->manaLimit = -1; //we do not want to leak max mana info outside battle so set to meaningless value
  2709. }
  2710. }
  2711. InfoAboutTown::InfoAboutTown():
  2712. details(nullptr),
  2713. tType(nullptr),
  2714. built(0),
  2715. fortLevel(0)
  2716. {
  2717. }
  2718. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed):
  2719. details(nullptr),
  2720. tType(nullptr),
  2721. built(0),
  2722. fortLevel(0)
  2723. {
  2724. initFromTown(t, detailed);
  2725. }
  2726. InfoAboutTown::~InfoAboutTown()
  2727. {
  2728. vstd::clear_pointer(details);
  2729. }
  2730. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2731. {
  2732. initFromArmy(t, detailed);
  2733. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2734. built = t->builded;
  2735. fortLevel = t->fortLevel();
  2736. name = t->name;
  2737. tType = t->town;
  2738. vstd::clear_pointer(details);
  2739. if(detailed)
  2740. {
  2741. //include details about hero
  2742. details = new Details();
  2743. TResources income = t->dailyIncome();
  2744. details->goldIncome = income[Res::GOLD];
  2745. details->customRes = t->hasBuilt(BuildingID::RESOURCE_SILO);
  2746. details->hallLevel = t->hallLevel();
  2747. details->garrisonedHero = t->garrisonHero;
  2748. }
  2749. }
  2750. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2751. : isDetailed(detailed)
  2752. {
  2753. for(auto & elem : army->Slots())
  2754. {
  2755. if(detailed)
  2756. (*this)[elem.first] = *elem.second;
  2757. else
  2758. (*this)[elem.first] = CStackBasicDescriptor(elem.second->type, elem.second->getQuantityID());
  2759. }
  2760. }
  2761. ArmyDescriptor::ArmyDescriptor()
  2762. : isDetailed(false)
  2763. {
  2764. }
  2765. int ArmyDescriptor::getStrength() const
  2766. {
  2767. ui64 ret = 0;
  2768. if(isDetailed)
  2769. {
  2770. for(auto & elem : *this)
  2771. ret += elem.second.type->AIValue * elem.second.count;
  2772. }
  2773. else
  2774. {
  2775. for(auto & elem : *this)
  2776. ret += elem.second.type->AIValue * CCreature::estimateCreatureCount(elem.second.count);
  2777. }
  2778. return ret;
  2779. }
  2780. TeamState::TeamState()
  2781. {
  2782. setNodeType(TEAM);
  2783. }
  2784. TeamState::TeamState(TeamState && other):
  2785. CBonusSystemNode(std::move(other)),
  2786. id(other.id)
  2787. {
  2788. std::swap(players, other.players);
  2789. std::swap(fogOfWarMap, other.fogOfWarMap);
  2790. }
  2791. CRandomGenerator & CGameState::getRandomGenerator()
  2792. {
  2793. return rand;
  2794. }