CGameState.cpp 85 KB

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