CGameState.cpp 82 KB

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