CGameState.cpp 99 KB

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