CGameState.cpp 81 KB

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