CGameState.cpp 92 KB

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