CGameState.cpp 81 KB

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