2
0

CGameState.cpp 80 KB

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