CGameState.cpp 98 KB

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