CGameState.cpp 84 KB

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