CGameState.cpp 87 KB

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