CGameState.cpp 80 KB

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