CGameState.cpp 87 KB

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