CGameState.cpp 92 KB

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