CGameState.cpp 95 KB

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