CGameState.cpp 92 KB

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