CGameState.cpp 85 KB

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