CGameState.cpp 87 KB

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