CGameState.cpp 84 KB

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