CGameState.cpp 86 KB

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