CGameState.cpp 87 KB

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