CGameState.cpp 82 KB

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