CGameState.cpp 99 KB

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