CGameState.cpp 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939
  1. #define VCMI_DLL
  2. #include "../hch/CCampaignHandler.h"
  3. #include <algorithm>
  4. #include <queue>
  5. #include <fstream>
  6. #include "CGameState.h"
  7. #include <boost/random/linear_congruential.hpp>
  8. #include "../hch/CDefObjInfoHandler.h"
  9. #include "../hch/CArtHandler.h"
  10. #include "../hch/CBuildingHandler.h"
  11. #include "../hch/CGeneralTextHandler.h"
  12. #include "../hch/CTownHandler.h"
  13. #include "../hch/CSpellHandler.h"
  14. #include "../hch/CHeroHandler.h"
  15. #include "../hch/CObjectHandler.h"
  16. #include "../hch/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. boost::rand48 ran;
  32. class CGObjectInstance;
  33. #ifdef min
  34. #undef min
  35. #endif
  36. #ifdef max
  37. #undef max
  38. #endif
  39. /*
  40. * CGameState.cpp, part of VCMI engine
  41. *
  42. * Authors: listed in file AUTHORS in main folder
  43. *
  44. * License: GNU General Public License v2.0 or later
  45. * Full text of license available in license.txt file, in main folder
  46. *
  47. */
  48. void foofoofoo()
  49. {
  50. //never called function to force instantation of templates
  51. int *ccc = NULL;
  52. registerTypes((CISer<CConnection>&)*ccc);
  53. registerTypes((COSer<CConnection>&)*ccc);
  54. registerTypes((CSaveFile&)*ccc);
  55. registerTypes((CLoadFile&)*ccc);
  56. registerTypes((CTypeList&)*ccc);
  57. }
  58. class CBaseForGSApply
  59. {
  60. public:
  61. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  62. virtual ~CBaseForGSApply(){};
  63. };
  64. template <typename T> class CApplyOnGS : public CBaseForGSApply
  65. {
  66. public:
  67. void applyOnGS(CGameState *gs, void *pack) const
  68. {
  69. T *ptr = static_cast<T*>(pack);
  70. while(!gs->mx->try_lock())
  71. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  72. ptr->applyGs(gs);
  73. gs->mx->unlock();
  74. }
  75. };
  76. class CGSApplier
  77. {
  78. public:
  79. std::map<ui16,CBaseForGSApply*> apps;
  80. CGSApplier()
  81. {
  82. registerTypes2(*this);
  83. }
  84. ~CGSApplier()
  85. {
  86. std::map<ui16,CBaseForGSApply*>::iterator iter;
  87. for(iter = apps.begin(); iter != apps.end(); iter++)
  88. delete iter->second;
  89. }
  90. template<typename T> void registerType(const T * t=NULL)
  91. {
  92. ui16 ID = typeList.registerType(t);
  93. apps[ID] = new CApplyOnGS<T>;
  94. }
  95. } *applierGs = NULL;
  96. class IObjectCaller
  97. {
  98. public:
  99. virtual void preInit()=0;
  100. virtual void postInit()=0;
  101. };
  102. template <typename T>
  103. class CObjectCaller : public IObjectCaller
  104. {
  105. public:
  106. void preInit()
  107. {
  108. T::preInit();
  109. }
  110. void postInit()
  111. {
  112. T::postInit();
  113. }
  114. };
  115. class CObjectCallersHandler
  116. {
  117. public:
  118. std::vector<IObjectCaller*> apps;
  119. template<typename T> void registerType(const T * t=NULL)
  120. {
  121. apps.push_back(new CObjectCaller<T>);
  122. }
  123. CObjectCallersHandler()
  124. {
  125. registerTypes1(*this);
  126. }
  127. ~CObjectCallersHandler()
  128. {
  129. for (size_t i = 0; i < apps.size(); i++)
  130. delete apps[i];
  131. }
  132. void preInit()
  133. {
  134. for (size_t i = 0; i < apps.size(); i++)
  135. apps[i]->preInit();
  136. }
  137. void postInit()
  138. {
  139. for (size_t i = 0; i < apps.size(); i++)
  140. apps[i]->postInit();
  141. }
  142. } *objCaller = NULL;
  143. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  144. {
  145. int type = txt.first, ser = txt.second;
  146. if(type == ART_NAMES)
  147. {
  148. dst = VLC->arth->artifacts[ser]->Name();
  149. }
  150. else if(type == CRE_PL_NAMES)
  151. {
  152. dst = VLC->creh->creatures[ser]->namePl;
  153. }
  154. else if(type == MINE_NAMES)
  155. {
  156. dst = VLC->generaltexth->mines[ser].first;
  157. }
  158. else if(type == MINE_EVNTS)
  159. {
  160. dst = VLC->generaltexth->mines[ser].second;
  161. }
  162. else if(type == SPELL_NAME)
  163. {
  164. dst = VLC->spellh->spells[ser].name;
  165. }
  166. else if(type == CRE_SING_NAMES)
  167. {
  168. dst = VLC->creh->creatures[ser]->nameSing;
  169. }
  170. else if(type == ART_DESCR)
  171. {
  172. dst = VLC->arth->artifacts[ser]->Description();
  173. }
  174. else
  175. {
  176. std::vector<std::string> *vec;
  177. switch(type)
  178. {
  179. case GENERAL_TXT:
  180. vec = &VLC->generaltexth->allTexts;
  181. break;
  182. case XTRAINFO_TXT:
  183. vec = &VLC->generaltexth->xtrainfo;
  184. break;
  185. case OBJ_NAMES:
  186. vec = &VLC->generaltexth->names;
  187. break;
  188. case RES_NAMES:
  189. vec = &VLC->generaltexth->restypes;
  190. break;
  191. case ARRAY_TXT:
  192. vec = &VLC->generaltexth->arraytxt;
  193. break;
  194. case CREGENS:
  195. vec = &VLC->generaltexth->creGens;
  196. break;
  197. case CREGENS4:
  198. vec = &VLC->generaltexth->creGens4;
  199. break;
  200. case ADVOB_TXT:
  201. vec = &VLC->generaltexth->advobtxt;
  202. break;
  203. case ART_EVNTS:
  204. vec = &VLC->generaltexth->artifEvents;
  205. break;
  206. case SEC_SKILL_NAME:
  207. vec = &VLC->generaltexth->skillName;
  208. break;
  209. case COLOR:
  210. vec = &VLC->generaltexth->capColors;
  211. break;
  212. }
  213. dst = (*vec)[ser];
  214. }
  215. }
  216. DLL_EXPORT void MetaString::toString(std::string &dst) const
  217. {
  218. size_t exSt = 0, loSt = 0, nums = 0;
  219. dst.clear();
  220. for(size_t i=0;i<message.size();++i)
  221. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  222. switch(message[i])
  223. {
  224. case TEXACT_STRING:
  225. dst += exactStrings[exSt++];
  226. break;
  227. case TLOCAL_STRING:
  228. {
  229. std::string hlp;
  230. getLocalString(localStrings[loSt++], hlp);
  231. dst += hlp;
  232. }
  233. break;
  234. case TNUMBER:
  235. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  236. break;
  237. case TREPLACE_ESTRING:
  238. dst.replace (dst.find("%s"), 2, exactStrings[exSt++]);
  239. break;
  240. case TREPLACE_LSTRING:
  241. {
  242. std::string hlp;
  243. getLocalString(localStrings[loSt++], hlp);
  244. dst.replace (dst.find("%s"), 2, hlp);
  245. }
  246. break;
  247. case TREPLACE_NUMBER:
  248. dst.replace (dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  249. break;
  250. default:
  251. tlog1 << "MetaString processing error!\n";
  252. break;
  253. }
  254. }
  255. }
  256. DLL_EXPORT std::string MetaString::buildList () const
  257. ///used to handle loot from creature bank
  258. {
  259. size_t exSt = 0, loSt = 0, nums = 0;
  260. std::string lista;
  261. for (int i = 0; i < message.size(); ++i)
  262. {
  263. if (i > 0 && message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING)
  264. {
  265. if (exSt == exactStrings.size() - 1)
  266. lista += VLC->generaltexth->allTexts[141]; //" and "
  267. else
  268. lista += ", ";
  269. }
  270. switch (message[i])
  271. {
  272. case TEXACT_STRING:
  273. lista += exactStrings[exSt++];
  274. break;
  275. case TLOCAL_STRING:
  276. {
  277. std::string hlp;
  278. getLocalString (localStrings[loSt++], hlp);
  279. lista += hlp;
  280. }
  281. break;
  282. case TNUMBER:
  283. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  284. break;
  285. case TREPLACE_ESTRING:
  286. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  287. break;
  288. case TREPLACE_LSTRING:
  289. {
  290. std::string hlp;
  291. getLocalString (localStrings[loSt++], hlp);
  292. lista.replace (lista.find("%s"), 2, hlp);
  293. }
  294. break;
  295. case TREPLACE_NUMBER:
  296. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  297. break;
  298. default:
  299. tlog1 << "MetaString processing error!\n";
  300. }
  301. }
  302. return lista;
  303. }
  304. void MetaString::addReplacement(const CStackInstance &stack)
  305. {
  306. assert(stack.count); //valid count
  307. assert(stack.type); //valid type
  308. if (stack.count == 1)
  309. addReplacement (CRE_SING_NAMES, stack.type->idNumber);
  310. else
  311. addReplacement (CRE_PL_NAMES, stack.type->idNumber);
  312. }
  313. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  314. {
  315. CGObjectInstance * nobj;
  316. switch(id)
  317. {
  318. case HEROI_TYPE: //hero
  319. {
  320. CGHeroInstance * nobj = new CGHeroInstance();
  321. nobj->pos = pos;
  322. nobj->tempOwner = owner;
  323. nobj->subID = subid;
  324. //nobj->initHero(ran);
  325. return nobj;
  326. }
  327. case TOWNI_TYPE: //town
  328. nobj = new CGTownInstance;
  329. break;
  330. default: //rest of objects
  331. nobj = new CGObjectInstance;
  332. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  333. break;
  334. }
  335. nobj->ID = id;
  336. nobj->subID = subid;
  337. if(!nobj->defInfo)
  338. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  339. nobj->pos = pos;
  340. //nobj->state = NULL;//new CLuaObjectScript();
  341. nobj->tempOwner = owner;
  342. nobj->defInfo->id = id;
  343. nobj->defInfo->subid = subid;
  344. //assigning defhandler
  345. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  346. return nobj;
  347. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  348. return nobj;
  349. }
  350. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  351. {
  352. for(unsigned int g=0; g<stacks.size(); ++g)
  353. {
  354. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  355. return stacks[g];
  356. }
  357. return NULL;
  358. }
  359. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  360. {
  361. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  362. }
  363. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  364. {
  365. for(unsigned int g=0; g<stacks.size(); ++g)
  366. {
  367. if(stacks[g]->position == tileID
  368. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  369. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  370. {
  371. if(!onlyAlive || stacks[g]->alive())
  372. {
  373. return stacks[g];
  374. }
  375. }
  376. }
  377. return NULL;
  378. }
  379. const CStack * BattleInfo::getStackT(int tileID, bool onlyAlive) const
  380. {
  381. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  382. }
  383. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  384. {
  385. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  386. //removing accessibility for side columns of hexes
  387. for(int v = 0; v < BFIELD_SIZE; ++v)
  388. {
  389. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  390. accessibility[v] = false;
  391. }
  392. for(unsigned int g=0; g<stacks.size(); ++g)
  393. {
  394. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  395. continue;
  396. accessibility[stacks[g]->position] = false;
  397. if(stacks[g]->doubleWide()) //if it's a double hex creature
  398. {
  399. if(stacks[g]->attackerOwned)
  400. accessibility[stacks[g]->position-1] = false;
  401. else
  402. accessibility[stacks[g]->position+1] = false;
  403. }
  404. }
  405. //obstacles
  406. for(unsigned int b=0; b<obstacles.size(); ++b)
  407. {
  408. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  409. for(unsigned int c=0; c<blocked.size(); ++c)
  410. {
  411. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  412. accessibility[blocked[c]] = false;
  413. }
  414. }
  415. //walls
  416. if(siege > 0)
  417. {
  418. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  419. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  420. {
  421. accessibility[permanentlyLocked[b]] = false;
  422. }
  423. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  424. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  425. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  426. {
  427. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  428. {
  429. accessibility[lockedIfNotDestroyed[b].second] = false;
  430. }
  431. }
  432. //gate
  433. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  434. {
  435. accessibility[95] = accessibility[96] = false; //block gate's hexes
  436. }
  437. }
  438. //occupyability
  439. if(addOccupiable && twoHex)
  440. {
  441. std::set<int> rem; //tiles to unlock
  442. for(int h=0; h<BFIELD_HEIGHT; ++h)
  443. {
  444. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  445. {
  446. int hex = h * BFIELD_WIDTH + w;
  447. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  448. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  449. )
  450. rem.insert(hex);
  451. }
  452. }
  453. occupyable = rem;
  454. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  455. {
  456. accessibility[*it] = true;
  457. }*/
  458. }
  459. }
  460. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  461. {
  462. if(flying && !lastPos)
  463. return true;
  464. if(twoHex)
  465. {
  466. //if given hex is accessible and appropriate adjacent one is free too
  467. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  468. }
  469. else
  470. {
  471. return accessibility[hex];
  472. }
  473. }
  474. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  475. {
  476. //inits
  477. for(int b=0; b<BFIELD_SIZE; ++b)
  478. predecessor[b] = -1;
  479. for(int g=0; g<BFIELD_SIZE; ++g)
  480. dists[g] = 100000000;
  481. std::queue< std::pair<int, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  482. hexq.push(std::make_pair(start, true));
  483. dists[hexq.front().first] = 0;
  484. int curNext = -1; //for bfs loop only (helper var)
  485. while(!hexq.empty()) //bfs loop
  486. {
  487. std::pair<int, bool> curHex = hexq.front();
  488. std::vector<int> neighbours = neighbouringTiles(curHex.first);
  489. hexq.pop();
  490. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  491. {
  492. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  493. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  494. if( dists[curHex.first]+1 >= dists[curNext] )
  495. continue;
  496. if(accessible && curHex.second)
  497. {
  498. hexq.push(std::make_pair(curNext, true));
  499. dists[curNext] = dists[curHex.first] + 1;
  500. }
  501. else if(fillPredecessors && !(accessible && !curHex.second))
  502. {
  503. hexq.push(std::make_pair(curNext, false));
  504. dists[curNext] = dists[curHex.first] + 1;
  505. }
  506. predecessor[curNext] = curHex.first;
  507. }
  508. }
  509. };
  510. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  511. {
  512. std::vector<int> ret;
  513. bool ac[BFIELD_SIZE];
  514. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  515. if(s->position < 0) //turrets
  516. return std::vector<int>();
  517. std::set<int> occupyable;
  518. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, addOccupiable, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  519. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  520. makeBFS(s->position, ac, pr, dist, s->doubleWide(), s->attackerOwned, s->hasBonusOfType(Bonus::FLYING), false);
  521. if(s->doubleWide())
  522. {
  523. if(!addOccupiable)
  524. {
  525. std::vector<int> rem;
  526. for(int b=0; b<BFIELD_SIZE; ++b)
  527. {
  528. //don't take into account most left and most right columns of hexes
  529. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  530. continue;
  531. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  532. {
  533. rem.push_back(b);
  534. }
  535. }
  536. for(unsigned int g=0; g<rem.size(); ++g)
  537. {
  538. ac[rem[g]] = false;
  539. }
  540. //removing accessibility for side hexes
  541. for(int v=0; v<BFIELD_SIZE; ++v)
  542. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  543. ac[v] = false;
  544. }
  545. }
  546. for (int i=0; i < BFIELD_SIZE ; ++i) {
  547. if(
  548. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->doubleWide(), s->attackerOwned, s->hasBonusOfType(Bonus::FLYING), true) ) )//we can reach it
  549. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  550. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  551. )
  552. {
  553. ret.push_back(i);
  554. }
  555. }
  556. return ret;
  557. }
  558. bool BattleInfo::isStackBlocked(int ID)
  559. {
  560. CStack *our = getStack(ID);
  561. if(our->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  562. return false;
  563. for(unsigned int i=0; i<stacks.size();i++)
  564. {
  565. if( !stacks[i]->alive()
  566. || stacks[i]->owner==our->owner
  567. )
  568. continue; //we omit dead and allied stacks
  569. if(stacks[i]->doubleWide())
  570. {
  571. if( mutualPosition(stacks[i]->position, our->position) >= 0
  572. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  573. return true;
  574. }
  575. else
  576. {
  577. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  578. return true;
  579. }
  580. }
  581. return false;
  582. }
  583. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  584. {
  585. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  586. return 0;
  587. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  588. return 1;
  589. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  590. return 5;
  591. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  592. return 2;
  593. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  594. return 4;
  595. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  596. return 3;
  597. return -1;
  598. }
  599. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  600. {
  601. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  602. std::vector<int> ret;
  603. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  604. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  605. CHECK_AND_PUSH(hex - 1);
  606. CHECK_AND_PUSH(hex + 1);
  607. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  608. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  609. #undef CHECK_AND_PUSH
  610. return ret;
  611. }
  612. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  613. {
  614. int predecessor[BFIELD_SIZE]; //for getting the Path
  615. int dist[BFIELD_SIZE]; //calculated distances
  616. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  617. if(predecessor[dest] == -1) //cannot reach destination
  618. {
  619. return std::make_pair(std::vector<int>(), 0);
  620. }
  621. //making the Path
  622. std::vector<int> path;
  623. int curElem = dest;
  624. while(curElem != start)
  625. {
  626. path.push_back(curElem);
  627. curElem = predecessor[curElem];
  628. }
  629. return std::make_pair(path, dist[dest]);
  630. }
  631. CStack::CStack(const CStackInstance *base, int O, int I, bool AO, int S)
  632. : CStackInstance(*base), ID(I), owner(O), slot(S), attackerOwned(AO), position(-1),
  633. counterAttacks(1)
  634. {
  635. baseAmount = base->count;
  636. firstHPleft = valOfBonuses(Bonus::STACK_HEALTH);
  637. shots = type->shots;
  638. counterAttacks += valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  639. //alive state indication
  640. state.insert(ALIVE);
  641. }
  642. ui32 CStack::Speed( int turn /*= 0*/ ) const
  643. {
  644. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  645. return 0;
  646. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  647. int percentBonus = 0;
  648. BOOST_FOREACH(const Bonus &b, bonuses)
  649. {
  650. if(b.type == Bonus::STACKS_SPEED)
  651. {
  652. percentBonus += b.additionalInfo;
  653. }
  654. }
  655. speed = ((100 + percentBonus) * speed)/100;
  656. //bind effect check
  657. if(getEffect(72))
  658. {
  659. return 0;
  660. }
  661. return speed;
  662. }
  663. const CStack::StackEffect * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  664. {
  665. for (unsigned int i=0; i< effects.size(); i++)
  666. if(effects[i].id == id)
  667. if(!turn || effects[i].turnsRemain > turn)
  668. return &effects[i];
  669. return NULL;
  670. }
  671. ui8 CStack::howManyEffectsSet(ui16 id) const
  672. {
  673. ui8 ret = 0;
  674. for (unsigned int i=0; i< effects.size(); i++)
  675. if(effects[i].id == id) //effect found
  676. {
  677. ++ret;
  678. }
  679. return ret;
  680. }
  681. bool CStack::willMove(int turn /*= 0*/) const
  682. {
  683. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  684. && !moved(turn)
  685. && canMove(turn);
  686. }
  687. bool CStack::canMove( int turn /*= 0*/ ) const
  688. {
  689. return alive()
  690. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  691. }
  692. bool CStack::moved( int turn /*= 0*/ ) const
  693. {
  694. if(!turn)
  695. return vstd::contains(state, MOVED);
  696. else
  697. return false;
  698. }
  699. bool CStack::doubleWide() const
  700. {
  701. return type->doubleWide;
  702. }
  703. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available, const CHeroClass *bannedClass /*= NULL*/) const
  704. {
  705. CGHeroInstance *ret = NULL;
  706. if(player<0 || player>=PLAYER_LIMIT)
  707. {
  708. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  709. return NULL;
  710. }
  711. std::vector<CGHeroInstance *> pool;
  712. if(native)
  713. {
  714. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  715. {
  716. if(pavailable.find(i->first)->second & 1<<player
  717. && i->second->type->heroType/2 == town->typeID)
  718. {
  719. pool.push_back(i->second); //get all avaliable heroes
  720. }
  721. }
  722. if(!pool.size())
  723. {
  724. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  725. return pickHeroFor(false, player, town, available);
  726. }
  727. else
  728. {
  729. ret = pool[rand()%pool.size()];
  730. }
  731. }
  732. else
  733. {
  734. int sum=0, r;
  735. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  736. {
  737. if(pavailable.find(i->first)->second & 1<<player
  738. && !bannedClass || i->second->type->heroClass != bannedClass)
  739. {
  740. pool.push_back(i->second);
  741. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  742. }
  743. }
  744. if(!pool.size())
  745. {
  746. tlog1 << "There are no heroes available for player " << player<<"!\n";
  747. return NULL;
  748. }
  749. r = rand()%sum;
  750. for (unsigned int i=0; i<pool.size(); i++)
  751. {
  752. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  753. if(r < 0)
  754. {
  755. ret = pool[i];
  756. break;
  757. }
  758. }
  759. if(!ret)
  760. ret = pool.back();
  761. }
  762. available.erase(ret->subID);
  763. return ret;
  764. }
  765. //void CGameState::apply(CPack * pack)
  766. //{
  767. // while(!mx->try_lock())
  768. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  769. // //applyNL(pack);
  770. // mx->unlock();
  771. //}
  772. int CGameState::pickHero(int owner)
  773. {
  774. int h=-1;
  775. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  776. return h;
  777. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  778. int i=0;
  779. do //try to find free hero of our faction
  780. {
  781. i++;
  782. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  783. } while( map->getHero(h) && i<175);
  784. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  785. {
  786. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  787. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  788. if(!map->getHero(j))
  789. h=j;
  790. }
  791. return h;
  792. }
  793. CGHeroInstance *CGameState::getHero(int objid)
  794. {
  795. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  796. return NULL;
  797. return static_cast<CGHeroInstance *>(map->objects[objid]);
  798. }
  799. const CGHeroInstance * CGameState::getHero( int objid ) const
  800. {
  801. return (const_cast<CGameState *>(this))->getHero(objid);
  802. }
  803. CGTownInstance *CGameState::getTown(int objid)
  804. {
  805. if(objid<0 || objid>=map->objects.size())
  806. return NULL;
  807. CGObjectInstance *obj = map->objects[objid];
  808. if(obj->ID != TOWNI_TYPE)
  809. return NULL;
  810. return static_cast<CGTownInstance *>(obj);
  811. }
  812. const CGTownInstance * CGameState::getTown( int objid ) const
  813. {
  814. return (const_cast<CGameState *>(this))->getTown(objid);
  815. }
  816. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  817. {
  818. switch(obj->ID)
  819. {
  820. case 65: //random artifact //how the hell use IGameCallback for this?
  821. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  822. case 66: //random treasure artifact
  823. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE));
  824. case 67: //random minor artifact
  825. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MINOR));
  826. case 68: //random major artifact
  827. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MAJOR));
  828. case 69: //random relic artifact
  829. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_RELIC));
  830. case 70: //random hero
  831. {
  832. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  833. }
  834. case 71: //random monster
  835. {
  836. int r;
  837. do
  838. {
  839. r = ran()%197;
  840. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  841. return std::pair<int,int>(54,r);
  842. }
  843. case 72: //random monster lvl1
  844. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  845. case 73: //random monster lvl2
  846. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  847. case 74: //random monster lvl3
  848. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  849. case 75: //random monster lvl4
  850. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  851. case 76: //random resource
  852. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  853. case 77: //random town
  854. {
  855. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  856. f;
  857. if(align>PLAYER_LIMIT-1)//same as owner / random
  858. {
  859. if(obj->tempOwner > PLAYER_LIMIT-1)
  860. f = -1; //random
  861. else
  862. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  863. }
  864. else
  865. {
  866. f = scenarioOps->getIthPlayersSettings(align).castle;
  867. }
  868. if(f<0) f = ran()%VLC->townh->towns.size();
  869. return std::pair<int,int>(TOWNI_TYPE,f);
  870. }
  871. case 162: //random monster lvl5
  872. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  873. case 163: //random monster lvl6
  874. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  875. case 164: //random monster lvl7
  876. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  877. case 216: //random dwelling
  878. {
  879. int faction = ran()%F_NUMBER;
  880. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  881. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(dwl->info);
  882. if (info->asCastle)
  883. {
  884. for(unsigned int i=0;i<map->objects.size();i++)
  885. {
  886. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  887. {
  888. randomizeObject(map->objects[i]); //we have to randomize the castle first
  889. faction = map->objects[i]->subID;
  890. break;
  891. }
  892. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  893. {
  894. faction = map->objects[i]->subID;
  895. break;
  896. }
  897. }
  898. }
  899. else
  900. {
  901. while((!(info->castles[0]&(1<<faction))))
  902. {
  903. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  904. break;
  905. faction = ran()%F_NUMBER;
  906. }
  907. }
  908. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  909. int cid = VLC->townh->towns[faction].basicCreatures[level];
  910. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  911. if(VLC->objh->cregens[i]==cid)
  912. return std::pair<int,int>(17,i);
  913. tlog3 << "Cannot find a dwelling for creature "<< cid << std::endl;
  914. return std::pair<int,int>(17,0);
  915. delete dwl->info;
  916. dwl->info = NULL;
  917. }
  918. case 217:
  919. {
  920. int faction = ran()%F_NUMBER;
  921. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  922. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(dwl->info);
  923. if (info->asCastle)
  924. {
  925. for(unsigned int i=0;i<map->objects.size();i++)
  926. {
  927. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  928. {
  929. randomizeObject(map->objects[i]); //we have to randomize the castle first
  930. faction = map->objects[i]->subID;
  931. break;
  932. }
  933. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  934. {
  935. faction = map->objects[i]->subID;
  936. break;
  937. }
  938. }
  939. }
  940. else
  941. {
  942. while((!(info->castles[0]&(1<<faction))))
  943. {
  944. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  945. break;
  946. faction = ran()%F_NUMBER;
  947. }
  948. }
  949. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  950. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  951. if(VLC->objh->cregens[i]==cid)
  952. return std::pair<int,int>(17,i);
  953. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  954. return std::pair<int,int>(17,0);
  955. delete dwl->info;
  956. dwl->info = NULL;
  957. }
  958. case 218:
  959. {
  960. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  961. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(dwl->info);
  962. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  963. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  964. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  965. if(VLC->objh->cregens[i]==cid)
  966. return std::pair<int,int>(17,i);
  967. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  968. return std::pair<int,int>(17,0);
  969. delete dwl->info;
  970. dwl->info = NULL;
  971. }
  972. }
  973. return std::pair<int,int>(-1,-1);
  974. }
  975. void CGameState::randomizeObject(CGObjectInstance *cur)
  976. {
  977. std::pair<int,int> ran = pickObject(cur);
  978. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  979. {
  980. if(cur->ID==TOWNI_TYPE) //town - set def
  981. {
  982. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  983. t->town = &VLC->townh->towns[t->subID];
  984. if(t->hasCapitol())
  985. t->defInfo = capitols[t->subID];
  986. else if(t->hasFort())
  987. t->defInfo = forts[t->subID];
  988. else
  989. t->defInfo = villages[t->subID];
  990. }
  991. return;
  992. }
  993. else if(ran.first==HEROI_TYPE)//special code for hero
  994. {
  995. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  996. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  997. cur->ID = ran.first;
  998. h->portrait = cur->subID = ran.second;
  999. h->type = VLC->heroh->heroes[ran.second];
  1000. h->randomizeArmy(h->type->heroType/2);
  1001. map->heroes.push_back(h);
  1002. return; //TODO: maybe we should do something with definfo?
  1003. }
  1004. else if(ran.first==TOWNI_TYPE)//special code for town
  1005. {
  1006. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1007. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1008. cur->ID = ran.first;
  1009. cur->subID = ran.second;
  1010. t->town = &VLC->townh->towns[ran.second];
  1011. if(t->hasCapitol())
  1012. t->defInfo = capitols[t->subID];
  1013. else if(t->hasFort())
  1014. t->defInfo = forts[t->subID];
  1015. else
  1016. t->defInfo = villages[t->subID];
  1017. t->randomizeArmy(t->subID);
  1018. map->towns.push_back(t);
  1019. return;
  1020. }
  1021. //we have to replace normal random object
  1022. cur->ID = ran.first;
  1023. cur->subID = ran.second;
  1024. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1025. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1026. if(!cur->defInfo)
  1027. {
  1028. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1029. return;
  1030. }
  1031. map->addBlockVisTiles(cur);
  1032. }
  1033. int CGameState::getDate(int mode) const
  1034. {
  1035. int temp;
  1036. switch (mode)
  1037. {
  1038. case 0: //day number
  1039. return day;
  1040. break;
  1041. case 1: //day of week
  1042. temp = (day)%7;
  1043. if (temp)
  1044. return temp;
  1045. else return 7;
  1046. break;
  1047. case 2: //current week
  1048. temp = ((day-1)/7)+1;
  1049. if (!(temp%4))
  1050. return 4;
  1051. else
  1052. return (temp%4);
  1053. break;
  1054. case 3: //current month
  1055. return ((day-1)/28)+1;
  1056. break;
  1057. }
  1058. return 0;
  1059. }
  1060. CGameState::CGameState()
  1061. {
  1062. mx = new boost::shared_mutex();
  1063. map = NULL;
  1064. curB = NULL;
  1065. scenarioOps = NULL;
  1066. applierGs = new CGSApplier;
  1067. objCaller = new CObjectCallersHandler;
  1068. campaign = NULL;
  1069. }
  1070. CGameState::~CGameState()
  1071. {
  1072. delete mx;
  1073. delete map;
  1074. delete curB;
  1075. //delete scenarioOps;
  1076. delete applierGs;
  1077. delete objCaller;
  1078. }
  1079. void CGameState::init( StartInfo * si, ui32 checksum, int Seed )
  1080. {
  1081. switch(si->mode)
  1082. {
  1083. case 0:
  1084. map = new Mapa(si->mapname);
  1085. for (int i=0; i<144; ++i) //yes, 144
  1086. {
  1087. if (map->allowedArtifact[i])
  1088. VLC->arth->allowedArtifacts.push_back(VLC->arth->artifacts[i]);
  1089. }
  1090. break;
  1091. case 2:
  1092. campaign = new CCampaignState();
  1093. campaign->initNewCampaign(*si);
  1094. std::string &mapContent = campaign->camp->mapPieces[si->whichMapInCampaign];
  1095. map = new Mapa();
  1096. map->initFromBytes((const unsigned char*)mapContent.c_str());
  1097. for (int i=0; i<144; ++i)
  1098. {
  1099. if (map->allowedArtifact[i])
  1100. VLC->arth->allowedArtifacts.push_back(VLC->arth->artifacts[i]);
  1101. }
  1102. break;
  1103. }
  1104. tlog0 << "Map loaded!" << std::endl;
  1105. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  1106. if(checksum)
  1107. {
  1108. tlog0 << "\tServer checksum for " << si->mapname <<": "<< checksum << std::endl;
  1109. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  1110. if(map->checksum != checksum)
  1111. {
  1112. tlog1 << "Wrong map checksum!!!" << std::endl;
  1113. throw std::string("Wrong checksum");
  1114. }
  1115. }
  1116. day = 0;
  1117. seed = Seed;
  1118. ran.seed((boost::int32_t)seed);
  1119. scenarioOps = si;
  1120. loadTownDInfos();
  1121. //pick grail location
  1122. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  1123. {
  1124. if(!map->grailRadious) //radius not given -> anywhere on map
  1125. map->grailRadious = map->width * 2;
  1126. std::vector<int3> allowedPos;
  1127. // add all not blocked tiles in range
  1128. for (int i = 0; i < map->width ; i++)
  1129. {
  1130. for (int j = 0; j < map->height ; j++)
  1131. {
  1132. for (int k = 0; k <= map->twoLevel ; k++)
  1133. {
  1134. const TerrainTile &t = map->terrain[i][j][k];
  1135. if(!t.blocked
  1136. && !t.visitable
  1137. && t.tertype != TerrainTile::water
  1138. && t.tertype != TerrainTile::rock
  1139. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  1140. allowedPos.push_back(int3(i,j,k));
  1141. }
  1142. }
  1143. }
  1144. //remove tiles with holes
  1145. for(unsigned int no=0; no<map->objects.size(); ++no)
  1146. if(map->objects[no]->ID == 124)
  1147. allowedPos -= map->objects[no]->pos;
  1148. if(allowedPos.size())
  1149. map->grailPos = allowedPos[ran() % allowedPos.size()];
  1150. else
  1151. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  1152. }
  1153. //picking random factions for players
  1154. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1155. {
  1156. if(scenarioOps->playerInfos[i].castle==-1)
  1157. {
  1158. int f;
  1159. do
  1160. {
  1161. f = ran()%F_NUMBER;
  1162. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1163. scenarioOps->playerInfos[i].castle = f;
  1164. }
  1165. }
  1166. //randomizing objects
  1167. for(unsigned int no=0; no<map->objects.size(); ++no)
  1168. {
  1169. randomizeObject(map->objects[no]);
  1170. if(map->objects[no]->ID==EVENTI_TYPE)
  1171. {
  1172. map->objects[no]->defInfo->handler=NULL;
  1173. }
  1174. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1175. }
  1176. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1177. /*********give starting hero****************************************/
  1178. for(int i=0;i<PLAYER_LIMIT;i++)
  1179. {
  1180. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1181. {
  1182. int3 hpos = map->players[i].posOfMainTown;
  1183. hpos.x+=1;// hpos.y+=1;
  1184. int j;
  1185. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1186. if(scenarioOps->playerInfos[j].color == i)
  1187. break;
  1188. if(j == scenarioOps->playerInfos.size())
  1189. continue;
  1190. int h=pickHero(i);
  1191. if(scenarioOps->playerInfos[j].hero == -1)
  1192. scenarioOps->playerInfos[j].hero = h;
  1193. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1194. nnn->id = map->objects.size();
  1195. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1196. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1197. {
  1198. if(map->towns[o]->pos == hpos)
  1199. {
  1200. map->towns[o]->visitingHero = nnn;
  1201. nnn->visitedTown = map->towns[o];
  1202. nnn->inTownGarrison = false;
  1203. break;
  1204. }
  1205. }
  1206. nnn->initHero();
  1207. map->heroes.push_back(nnn);
  1208. map->objects.push_back(nnn);
  1209. map->addBlockVisTiles(nnn);
  1210. }
  1211. }
  1212. /*********creating players entries in gs****************************************/
  1213. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1214. {
  1215. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1216. ins.second.color=ins.first;
  1217. ins.second.serial=i;
  1218. ins.second.human = scenarioOps->playerInfos[i].human;
  1219. players.insert(ins);
  1220. }
  1221. /******************RESOURCES****************************************************/
  1222. //TODO: computer player should receive other amount of resource than player (depending on difficulty)
  1223. std::vector<int> startres;
  1224. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1225. int k;
  1226. for (int j=0;j<scenarioOps->difficulty;j++)
  1227. {
  1228. tis >> k;
  1229. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1230. tis>>k;
  1231. }
  1232. tis >> k;
  1233. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1234. {
  1235. tis >> k;
  1236. startres.push_back(k);
  1237. }
  1238. tis.close();
  1239. tis.clear();
  1240. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1241. {
  1242. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1243. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1244. (*i).second.resources[x] = startres[x];
  1245. }
  1246. /*************************HEROES************************************************/
  1247. std::set<int> hids; //hero ids to create pool
  1248. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1249. if(map->allowedHeroes[i])
  1250. hids.insert(i);
  1251. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1252. {
  1253. if (map->heroes[i]->getOwner()<0)
  1254. {
  1255. tlog2 << "Warning - hero with uninitialized owner!\n";
  1256. continue;
  1257. }
  1258. CGHeroInstance * vhi = (map->heroes[i]);
  1259. vhi->initHero();
  1260. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1261. hids.erase(vhi->subID);
  1262. }
  1263. for (unsigned int i=0; i<map->objects.size();i++) //prisons
  1264. {
  1265. if (map->objects[i]->ID == 62)
  1266. hids.erase(map->objects[i]->subID);
  1267. }
  1268. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1269. {
  1270. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1271. continue;
  1272. map->predefinedHeroes[i]->initHero();
  1273. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1274. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1275. hids.erase(map->predefinedHeroes[i]->subID);
  1276. }
  1277. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1278. {
  1279. CGHeroInstance * vhi = new CGHeroInstance();
  1280. vhi->initHero(hid);
  1281. hpool.heroesPool[hid] = vhi;
  1282. hpool.pavailable[hid] = 0xff;
  1283. }
  1284. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1285. {
  1286. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1287. }
  1288. /*************************FOG**OF**WAR******************************************/
  1289. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1290. {
  1291. k->second.fogOfWarMap.resize(map->width);
  1292. for(int g=0; g<map->width; ++g)
  1293. k->second.fogOfWarMap[g].resize(map->height);
  1294. for(int g=-0; g<map->width; ++g)
  1295. for(int h=0; h<map->height; ++h)
  1296. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1297. for(int g=0; g<map->width; ++g)
  1298. for(int h=0; h<map->height; ++h)
  1299. for(int v=0; v<map->twoLevel+1; ++v)
  1300. k->second.fogOfWarMap[g][h][v] = 0;
  1301. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1302. {
  1303. if(obj->tempOwner != k->first) continue; //not a flagged object
  1304. std::set<int3> tiles;
  1305. obj->getSightTiles(tiles);
  1306. BOOST_FOREACH(int3 tile, tiles)
  1307. {
  1308. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1309. }
  1310. }
  1311. //starting bonus
  1312. if(si->playerInfos[k->second.serial].bonus==brandom)
  1313. si->playerInfos[k->second.serial].bonus = ran()%3;
  1314. switch(si->playerInfos[k->second.serial].bonus)
  1315. {
  1316. case bgold:
  1317. k->second.resources[6] += 500 + (ran()%6)*100;
  1318. break;
  1319. case bresource:
  1320. {
  1321. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1322. if(res == 127)
  1323. {
  1324. k->second.resources[0] += 5 + ran()%6;
  1325. k->second.resources[2] += 5 + ran()%6;
  1326. }
  1327. else
  1328. {
  1329. k->second.resources[res] += 3 + ran()%4;
  1330. }
  1331. break;
  1332. }
  1333. case bartifact:
  1334. {
  1335. if(!k->second.heroes.size())
  1336. {
  1337. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1338. break;
  1339. }
  1340. CArtifact *toGive;
  1341. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1342. CGHeroInstance *hero = k->second.heroes[0];
  1343. std::vector<ui16>::iterator slot = vstd::findFirstNot (hero->artifWorn, toGive->possibleSlots);
  1344. if(slot!=toGive->possibleSlots.end())
  1345. {
  1346. VLC->arth->equipArtifact(hero->artifWorn, *slot, toGive->id, &hero->bonuses);
  1347. }
  1348. else
  1349. hero->giveArtifact(toGive->id);
  1350. }
  1351. }
  1352. }
  1353. /****************************TOWNS************************************************/
  1354. for (unsigned int i=0;i<map->towns.size();i++)
  1355. {
  1356. CGTownInstance * vti =(map->towns[i]);
  1357. if(!vti->town)
  1358. vti->town = &VLC->townh->towns[vti->subID];
  1359. if (vti->name.length()==0) // if town hasn't name we draw it
  1360. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1361. //init buildings
  1362. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1363. {
  1364. vti->builtBuildings.erase(-50);
  1365. vti->builtBuildings.insert(10);
  1366. vti->builtBuildings.insert(5);
  1367. vti->builtBuildings.insert(30);
  1368. if(ran()%2)
  1369. vti->builtBuildings.insert(31);
  1370. }
  1371. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==3)
  1372. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  1373. //init hordes
  1374. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1375. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1376. {
  1377. vti->builtBuildings.erase(-31-i);//remove old ID
  1378. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1379. {
  1380. vti->builtBuildings.insert(18);//add it
  1381. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1382. vti->builtBuildings.insert(19);//add it as well
  1383. }
  1384. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1385. {
  1386. vti->builtBuildings.insert(24);
  1387. if (vstd::contains(vti->builtBuildings,(37+i)))
  1388. vti->builtBuildings.insert(25);
  1389. }
  1390. }
  1391. //init spells
  1392. vti->spells.resize(SPELL_LEVELS);
  1393. CSpell *s;
  1394. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1395. {
  1396. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1397. vti->spells[s->level-1].push_back(s->id);
  1398. vti->possibleSpells -= s->id;
  1399. }
  1400. while(vti->possibleSpells.size())
  1401. {
  1402. ui32 total=0, sel=-1;
  1403. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1404. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1405. int r = (total)? ran()%total : -1;
  1406. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1407. {
  1408. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1409. if(r<0)
  1410. {
  1411. sel = ps;
  1412. break;
  1413. }
  1414. }
  1415. if(sel<0)
  1416. sel=0;
  1417. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1418. vti->spells[s->level-1].push_back(s->id);
  1419. vti->possibleSpells -= s->id;
  1420. }
  1421. if(vti->getOwner() != 255)
  1422. getPlayer(vti->getOwner())->towns.push_back(vti);
  1423. }
  1424. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1425. {
  1426. if(k->first==-1 || k->first==255)
  1427. continue;
  1428. //init visiting and garrisoned heroes
  1429. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1430. {
  1431. CGHeroInstance *h = k->second.heroes[l];
  1432. for(unsigned int m=0; m<k->second.towns.size();m++)
  1433. {
  1434. CGTownInstance *t = k->second.towns[m];
  1435. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1436. if(vistile == h->pos || h->pos==t->pos)
  1437. {
  1438. t->visitingHero = h;
  1439. h->visitedTown = t;
  1440. h->inTownGarrison = false;
  1441. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1442. {
  1443. map->removeBlockVisTiles(h);
  1444. h->pos.x -= 1;
  1445. map->addBlockVisTiles(h);
  1446. }
  1447. break;
  1448. }
  1449. }
  1450. }
  1451. }
  1452. for(unsigned int i=0; i<map->defy.size(); i++)
  1453. {
  1454. map->defy[i]->serial = i;
  1455. }
  1456. objCaller->preInit();
  1457. for(unsigned int i=0; i<map->objects.size(); i++)
  1458. {
  1459. map->objects[i]->initObj();
  1460. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1461. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1462. }
  1463. objCaller->postInit();
  1464. }
  1465. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1466. {
  1467. return true;
  1468. }
  1469. bool CGameState::battleCanFlee(int player)
  1470. {
  1471. if(!curB) //there is no battle
  1472. return false;
  1473. if(curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1474. || curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE))
  1475. return false;
  1476. return true;
  1477. }
  1478. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1479. {
  1480. if(!curB)
  1481. return -1;
  1482. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1483. {
  1484. if((curB->stacks[g]->position == pos
  1485. || (curB->stacks[g]->doubleWide()
  1486. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1487. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1488. ))
  1489. && (!onlyAlive || curB->stacks[g]->alive())
  1490. )
  1491. return curB->stacks[g]->ID;
  1492. }
  1493. return -1;
  1494. }
  1495. int CGameState::battleGetBattlefieldType(int3 tile)
  1496. {
  1497. if(tile==int3() && curB)
  1498. tile = curB->tile;
  1499. else if(tile==int3() && !curB)
  1500. return -1;
  1501. const std::vector <CGObjectInstance*> & objs = map->objects;
  1502. for(int g=0; g<objs.size(); ++g)
  1503. {
  1504. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1505. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1506. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1507. ) //look only for objects covering given tile
  1508. continue;
  1509. switch(objs[g]->ID)
  1510. {
  1511. case 222: //clover field
  1512. return 19;
  1513. case 21: case 223: //cursed ground
  1514. return 22;
  1515. case 224: //evil fog
  1516. return 20;
  1517. case 225: //favourable winds
  1518. return 21;
  1519. case 226: //fiery fields
  1520. return 14;
  1521. case 227: //holy ground
  1522. return 18;
  1523. case 228: //lucid pools
  1524. return 17;
  1525. case 229: //magic clouds
  1526. return 16;
  1527. case 46: case 230: //magic plains
  1528. return 9;
  1529. case 231: //rocklands
  1530. return 15;
  1531. }
  1532. }
  1533. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1534. {
  1535. case TerrainTile::dirt:
  1536. return rand()%3+3;
  1537. case TerrainTile::sand:
  1538. return 2; //TODO: coast support
  1539. case TerrainTile::grass:
  1540. return rand()%2+6;
  1541. case TerrainTile::snow:
  1542. return rand()%2+10;
  1543. case TerrainTile::swamp:
  1544. return 13;
  1545. case TerrainTile::rough:
  1546. return 23;
  1547. case TerrainTile::subterranean:
  1548. return 12;
  1549. case TerrainTile::lava:
  1550. return 8;
  1551. case TerrainTile::water:
  1552. return 25;
  1553. case TerrainTile::rock:
  1554. return 15;
  1555. default:
  1556. return -1;
  1557. }
  1558. }
  1559. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1560. {
  1561. if(!curB)
  1562. return NULL;
  1563. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  1564. }
  1565. UpgradeInfo CGameState::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
  1566. {
  1567. UpgradeInfo ret;
  1568. const CCreature *base = obj->getCreature(stackPos);
  1569. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1570. {
  1571. const CGTownInstance * t;
  1572. if(obj->ID == TOWNI_TYPE)
  1573. t = static_cast<const CGTownInstance *>(obj);
  1574. else
  1575. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1576. for(std::set<si32>::const_iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1577. {
  1578. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1579. {
  1580. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1581. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1582. {
  1583. ret.newID.push_back(nid);
  1584. ret.cost.push_back(std::set<std::pair<int,int> >());
  1585. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1586. {
  1587. int dif = VLC->creh->creatures[nid]->cost[j] - base->cost[j];
  1588. if(dif)
  1589. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1590. }
  1591. }
  1592. }
  1593. }//end for
  1594. }
  1595. //TODO: check if hero ability makes some upgrades possible
  1596. if(ret.newID.size())
  1597. ret.oldID = base->idNumber;
  1598. return ret;
  1599. }
  1600. void CGameState::loadTownDInfos()
  1601. {
  1602. for(int i=0;i<F_NUMBER;i++)
  1603. {
  1604. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1605. forts[i] = VLC->dobjinfo->castles[i];
  1606. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1607. }
  1608. }
  1609. void CGameState::getNeighbours( const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand )
  1610. {
  1611. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1612. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1613. vec.clear();
  1614. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1615. {
  1616. const int3 hlp = tile + dirs[i];
  1617. if(!map->isInTheMap(hlp))
  1618. continue;
  1619. const TerrainTile &hlpt = map->getTile(hlp);
  1620. //we cannot visit things from blocked tiles
  1621. if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1622. {
  1623. continue;
  1624. }
  1625. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1626. && hlpt.tertype != TerrainTile::rock)
  1627. {
  1628. vec.push_back(hlp);
  1629. }
  1630. }
  1631. }
  1632. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1633. {
  1634. if(src == dest) //same tile
  1635. return 0;
  1636. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1637. &d = map->terrain[dest.x][dest.y][dest.z];
  1638. //get basic cost
  1639. int ret = h->getTileCost(d,s);
  1640. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1641. {
  1642. bool freeFlying = h->getBonusesCount(Selector::typeSybtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1643. if(!freeFlying)
  1644. {
  1645. ret *= 1.4f; //40% penalty for movement over blocked tile
  1646. }
  1647. }
  1648. else if (d.tertype == TerrainTile::water)
  1649. {
  1650. if (!h->boat && h->getBonusesCount(Selector::typeSybtype(Bonus::WATER_WALKING, 1)) > 0)
  1651. {
  1652. ret *= 1.4f; //40% penalty for water walking
  1653. }
  1654. }
  1655. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1656. {
  1657. int old = ret;
  1658. ret *= 1.414213;
  1659. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1660. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1661. {
  1662. return remainingMovePoints;
  1663. }
  1664. }
  1665. int left = remainingMovePoints-ret;
  1666. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1667. {
  1668. std::vector<int3> vec;
  1669. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water);
  1670. for(size_t i=0; i < vec.size(); i++)
  1671. {
  1672. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1673. if(fcost <= left)
  1674. {
  1675. return ret;
  1676. }
  1677. }
  1678. ret = remainingMovePoints;
  1679. }
  1680. return ret;
  1681. }
  1682. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  1683. {
  1684. std::set<int> used;
  1685. used.insert(ID);
  1686. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  1687. while(true)
  1688. {
  1689. size_t noloop=0;
  1690. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  1691. {
  1692. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  1693. {
  1694. used.insert(*i);
  1695. for(
  1696. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  1697. j!=VLC->townh->requirements[t->subID][*i].end();
  1698. j++)
  1699. {
  1700. reqs.insert(*j);//creating full list of requirements
  1701. }
  1702. }
  1703. else
  1704. {
  1705. noloop++;
  1706. }
  1707. }
  1708. if(noloop==reqs.size())
  1709. break;
  1710. }
  1711. return reqs;
  1712. }
  1713. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1714. {
  1715. int ret = 7; //allowed by default
  1716. if(t->builded >= MAX_BUILDING_PER_TURN)
  1717. ret = 5; //building limit
  1718. //checking resources
  1719. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1720. if(!pom)
  1721. return 8;
  1722. // if(pom->Name().size()==0||pom->resources.size()==0)
  1723. // return 2;//TODO: why does this happen?
  1724. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1725. {
  1726. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1727. ret = 6; //lack of res
  1728. }
  1729. //checking for requirements
  1730. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  1731. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  1732. {
  1733. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1734. ret = 8; //lack of requirements - cannot build
  1735. }
  1736. //can we build it?
  1737. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1738. ret = 2; //forbidden
  1739. if(ID == 13) //capitol
  1740. {
  1741. for(unsigned int in = 0; in < map->towns.size(); in++)
  1742. {
  1743. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1744. {
  1745. ret = 0; //no more than one capitol
  1746. break;
  1747. }
  1748. }
  1749. }
  1750. else if(ID == 6) //shipyard
  1751. {
  1752. int3 t1(t->pos + int3(-1,3,0)),
  1753. t2(t->pos + int3(-3,3,0));
  1754. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1755. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1756. ret = 1; //lack of water
  1757. }
  1758. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1759. ret = 4;
  1760. return ret;
  1761. }
  1762. void CGameState::apply(CPack *pack)
  1763. {
  1764. ui16 typ = typeList.getTypeID(pack);
  1765. assert(typ >= 0);
  1766. applierGs->apps[typ]->applyOnGS(this,pack);
  1767. }
  1768. PlayerState * CGameState::getPlayer( ui8 color, bool verbose )
  1769. {
  1770. if(vstd::contains(players,color))
  1771. {
  1772. return &players[color];
  1773. }
  1774. else
  1775. {
  1776. if(verbose)
  1777. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1778. return NULL;
  1779. }
  1780. }
  1781. const PlayerState * CGameState::getPlayer( ui8 color, bool verbose ) const
  1782. {
  1783. return (const_cast<CGameState *>(this))->getPlayer(color, verbose);
  1784. }
  1785. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1786. {
  1787. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1788. return false;
  1789. int3 hpos = hero->getPosition(false);
  1790. bool flying = false; //hero is under flying effect TODO
  1791. bool waterWalking = false; //hero is on land and can walk on water TODO
  1792. bool onLand = map->getTile(hpos).tertype != TerrainTile::water;
  1793. // tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1794. //
  1795. // if (!hero->canWalkOnSea())
  1796. // blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1797. // else
  1798. // blockLandSea = boost::logic::indeterminate;
  1799. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1800. //graph initialization
  1801. std::vector< std::vector<CPathNode> > graph;
  1802. graph.resize(map->width);
  1803. for(size_t i=0; i<graph.size(); ++i)
  1804. {
  1805. graph[i].resize(map->height);
  1806. for(size_t j=0; j<graph[i].size(); ++j)
  1807. {
  1808. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1809. CPathNode &node = graph[i][j];
  1810. node.accessible = !tinfo->blocked;
  1811. node.dist = -1;
  1812. node.theNodeBefore = NULL;
  1813. node.visited = false;
  1814. node.coord.x = i;
  1815. node.coord.y = j;
  1816. node.coord.z = dest.z;
  1817. if(!tinfo->entrableTerrain(onLand, flying || waterWalking)
  1818. || !FoW[i][j][src.z] //tile is covered by the FoW
  1819. )
  1820. {
  1821. node.accessible = false;
  1822. }
  1823. }
  1824. }
  1825. //Special rules for the destination tile
  1826. {
  1827. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1828. CPathNode &d = graph[dest.x][dest.y];
  1829. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1830. if(t->visitable)
  1831. {
  1832. d.accessible = true; //for allowing visiting objects
  1833. }
  1834. if(onLand && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1835. {
  1836. size_t i = 0;
  1837. for(; i < t->visitableObjects.size(); i++)
  1838. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1839. break;
  1840. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1841. }
  1842. else if(!onLand && t->tertype != TerrainTile::water) //hero is moving by water
  1843. {
  1844. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1845. }
  1846. }
  1847. //graph initialized
  1848. //initial tile - set cost on 0 and add to the queue
  1849. graph[src.x][src.y].dist = 0;
  1850. std::queue<CPathNode> mq;
  1851. mq.push(graph[src.x][src.y]);
  1852. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1853. std::vector<int3> neighbours;
  1854. neighbours.reserve(8);
  1855. while(!mq.empty())
  1856. {
  1857. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1858. mq.pop();
  1859. if (cp.coord == dest) //it's destination tile
  1860. {
  1861. if (cp.dist < curDist) //that path is better than previous one
  1862. curDist = cp.dist;
  1863. continue;
  1864. }
  1865. else
  1866. {
  1867. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1868. continue;
  1869. }
  1870. //add accessible neighbouring nodes to the queue
  1871. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate);
  1872. for(unsigned int i=0; i < neighbours.size(); i++)
  1873. {
  1874. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1875. if(dp.accessible)
  1876. {
  1877. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1878. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1879. {
  1880. dp.dist = cp.dist + cost;
  1881. dp.theNodeBefore = &cp;
  1882. mq.push(dp);
  1883. }
  1884. }
  1885. }
  1886. }
  1887. CPathNode *curNode = &graph[dest.x][dest.y];
  1888. if(!curNode->theNodeBefore) //destination is not accessible
  1889. return false;
  1890. //fill ret with found path
  1891. ret.nodes.clear();
  1892. while(curNode->coord != graph[src.x][src.y].coord)
  1893. {
  1894. ret.nodes.push_back(*curNode);
  1895. curNode = curNode->theNodeBefore;
  1896. }
  1897. ret.nodes.push_back(graph[src.x][src.y]);
  1898. return true;
  1899. }
  1900. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1901. {
  1902. assert(hero);
  1903. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1904. if(src.x < 0)
  1905. src = hero->getPosition(false);
  1906. if(movement < 0)
  1907. movement = hero->movement;
  1908. out.hero = hero;
  1909. out.hpos = src;
  1910. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1911. {
  1912. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1913. return;
  1914. }
  1915. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1916. if (!hero->canWalkOnSea())
  1917. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1918. else
  1919. onLand = boost::logic::indeterminate;
  1920. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1921. bool flying = hero->hasBonusOfType(Bonus::FLYING_MOVEMENT);
  1922. bool waterWalk = hero->hasBonusOfType(Bonus::WATER_WALKING);
  1923. //graph initialization
  1924. CGPathNode ***graph = out.nodes;
  1925. for(size_t i=0; i < out.sizes.x; ++i)
  1926. {
  1927. for(size_t j=0; j < out.sizes.y; ++j)
  1928. {
  1929. for(size_t k=0; k < out.sizes.z; ++k)
  1930. {
  1931. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1932. CGPathNode &node = graph[i][j][k];
  1933. node.accessible = (tinfo->blocked ? CGPathNode::FLYABLE : CGPathNode::ACCESSIBLE);
  1934. if(!flying && node.accessible == CGPathNode::FLYABLE)
  1935. {
  1936. node.accessible = CGPathNode::BLOCKED;
  1937. }
  1938. node.turns = 0xff;
  1939. node.moveRemains = 0;
  1940. node.coord.x = i;
  1941. node.coord.y = j;
  1942. node.coord.z = k;
  1943. node.land = tinfo->tertype != TerrainTile::water;
  1944. node.theNodeBefore = NULL;
  1945. if((onLand || indeterminate(onLand)) && !node.land)//it's sea and we cannot walk on sea
  1946. {
  1947. if (waterWalk || flying)
  1948. {
  1949. node.accessible = CGPathNode::FLYABLE;
  1950. }
  1951. else
  1952. {
  1953. node.accessible = CGPathNode::BLOCKED;
  1954. }
  1955. }
  1956. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1957. || !onLand && node.land //it's land and we cannot walk on land (complementary condition is handled above)
  1958. || !FoW[i][j][k] //tile is covered by the FoW
  1959. )
  1960. {
  1961. node.accessible = CGPathNode::BLOCKED;
  1962. }
  1963. else if(tinfo->visitable)
  1964. {
  1965. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1966. {
  1967. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  1968. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  1969. {
  1970. node.accessible = CGPathNode::ACCESSIBLE;
  1971. }
  1972. else if(obj->blockVisit)
  1973. {
  1974. node.accessible = CGPathNode::BLOCKVIS;
  1975. break;
  1976. }
  1977. else if(obj->ID != EVENTI_TYPE) //pathfinder should ignore placed events
  1978. {
  1979. node.accessible = CGPathNode::VISITABLE;
  1980. }
  1981. }
  1982. }
  1983. else if (map->isInTheMap(guardingCreaturePosition(int3(i, j, k)))
  1984. && tinfo->blockingObjects.size() == 0)
  1985. {
  1986. // Monster close by; blocked visit for battle.
  1987. node.accessible = CGPathNode::BLOCKVIS;
  1988. }
  1989. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  1990. {
  1991. size_t i = 0;
  1992. for(; i < tinfo->visitableObjects.size(); i++)
  1993. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1994. break;
  1995. if(i < tinfo->visitableObjects.size())
  1996. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  1997. }
  1998. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  1999. {
  2000. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  2001. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  2002. }
  2003. }
  2004. }
  2005. }
  2006. //graph initialized
  2007. //initial tile - set cost on 0 and add to the queue
  2008. graph[src.x][src.y][src.z].turns = 0;
  2009. graph[src.x][src.y][src.z].moveRemains = movement;
  2010. std::queue<CGPathNode*> mq;
  2011. mq.push(&graph[src.x][src.y][src.z]);
  2012. //ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  2013. std::vector<int3> neighbours;
  2014. neighbours.reserve(8);
  2015. while(!mq.empty())
  2016. {
  2017. CGPathNode *cp = mq.front();
  2018. mq.pop();
  2019. const int3 guardPosition = guardingCreaturePosition(cp->coord);
  2020. const bool guardedPosition = (guardPosition != int3(-1, -1, -1) && cp->coord != src);
  2021. const TerrainTile &ct = map->getTile(cp->coord);
  2022. int movement = cp->moveRemains, turn = cp->turns;
  2023. if(!movement)
  2024. {
  2025. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2026. turn++;
  2027. }
  2028. //add accessible neighbouring nodes to the queue
  2029. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate);
  2030. for(unsigned int i=0; i < neighbours.size(); i++)
  2031. {
  2032. int moveAtNextTile = movement;
  2033. int turnAtNextTile = turn;
  2034. const int3 &n = neighbours[i]; //current neighbor
  2035. CGPathNode & dp = graph[n.x][n.y][n.z];
  2036. if( !checkForVisitableDir(cp->coord, dp.coord)
  2037. || !checkForVisitableDir(dp.coord, cp->coord)
  2038. || dp.accessible == CGPathNode::BLOCKED )
  2039. {
  2040. continue;
  2041. }
  2042. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  2043. int remains = movement - cost;
  2044. if(remains < 0)
  2045. {
  2046. //occurs rarely, when hero with low movepoints tries to go leave the road
  2047. turnAtNextTile++;
  2048. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2049. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2050. remains = moveAtNextTile - cost;
  2051. }
  2052. const bool neighborIsGuard = guardingCreaturePosition(cp->coord) == dp.coord;
  2053. if((dp.turns==0xff //we haven't been here before
  2054. || dp.turns > turnAtNextTile
  2055. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  2056. && (!guardedPosition || neighborIsGuard)) // Can step into tile of guard
  2057. {
  2058. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  2059. dp.moveRemains = remains;
  2060. dp.turns = turnAtNextTile;
  2061. dp.theNodeBefore = cp;
  2062. const bool guardedNeighbor = guardingCreaturePosition(dp.coord) != int3(-1, -1, -1);
  2063. //const bool positionIsGuard = guardingCreaturePosition(cp->coord) == cp->coord; //can this be true? hero never passes from monster tile...
  2064. if (dp.accessible == CGPathNode::ACCESSIBLE || dp.accessible == CGPathNode::FLYABLE
  2065. || (guardedNeighbor && !guardedPosition)) // Can step into a hostile tile once.
  2066. {
  2067. mq.push(&dp);
  2068. }
  2069. }
  2070. } //neighbours loop
  2071. } //queue loop
  2072. }
  2073. /**
  2074. * Tells if the tile is guarded by a monster as well as the position
  2075. * of the monster that will attack on it.
  2076. *
  2077. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  2078. * the monster guarding the tile.
  2079. */
  2080. int3 CGameState::guardingCreaturePosition (int3 pos) const
  2081. {
  2082. const int3 originalPos = pos;
  2083. // Give monster at position priority.
  2084. if (!map->isInTheMap(pos))
  2085. return int3(-1, -1, -1);
  2086. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  2087. if (posTile.visitable)
  2088. {
  2089. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  2090. {
  2091. if(obj->blockVisit)
  2092. {
  2093. if (obj->ID == 54) // Monster
  2094. return pos;
  2095. else
  2096. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  2097. }
  2098. }
  2099. }
  2100. // See if there are any monsters adjacent.
  2101. pos -= int3(1, 1, 0); // Start with top left.
  2102. for (int dx = 0; dx < 3; dx++)
  2103. {
  2104. for (int dy = 0; dy < 3; dy++)
  2105. {
  2106. if (map->isInTheMap(pos))
  2107. {
  2108. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  2109. if (tile.visitable)
  2110. {
  2111. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  2112. {
  2113. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  2114. {
  2115. return pos;
  2116. }
  2117. }
  2118. }
  2119. }
  2120. pos.y++;
  2121. }
  2122. pos.y -= 3;
  2123. pos.x++;
  2124. }
  2125. return int3(-1, -1, -1);
  2126. }
  2127. bool CGameState::isVisible(int3 pos, int player)
  2128. {
  2129. if(player == 255) //neutral player
  2130. return false;
  2131. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  2132. }
  2133. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2134. {
  2135. if(player == 255) //neutral player
  2136. return false;
  2137. //object is visible when at least one blocked tile is visible
  2138. for(int fx=0; fx<8; ++fx)
  2139. {
  2140. for(int fy=0; fy<6; ++fy)
  2141. {
  2142. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2143. if(map->isInTheMap(pos)
  2144. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2145. && isVisible(pos, player) )
  2146. return true;
  2147. }
  2148. }
  2149. return false;
  2150. }
  2151. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2152. {
  2153. const TerrainTile * pom = &map->getTile(dst);
  2154. return checkForVisitableDir(src, pom, dst);
  2155. }
  2156. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2157. {
  2158. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2159. {
  2160. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2161. continue;
  2162. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2163. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2164. {
  2165. return false;
  2166. }
  2167. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2168. {
  2169. return false;
  2170. }
  2171. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2172. {
  2173. return false;
  2174. }
  2175. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2176. {
  2177. return false;
  2178. }
  2179. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2180. {
  2181. return false;
  2182. }
  2183. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2184. {
  2185. return false;
  2186. }
  2187. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2188. {
  2189. return false;
  2190. }
  2191. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2192. {
  2193. return false;
  2194. }
  2195. }
  2196. return true;
  2197. }
  2198. std::pair<ui32, ui32> BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2199. {
  2200. float additiveBonus=1.0f, multBonus=1.0f,
  2201. minDmg = attacker->type->damageMin * attacker->count,
  2202. maxDmg = attacker->type->damageMax * attacker->count;
  2203. if(attacker->type->idNumber == 149) //arrow turret
  2204. {
  2205. switch(attacker->position)
  2206. {
  2207. case -2: //keep
  2208. minDmg = 15;
  2209. maxDmg = 15;
  2210. break;
  2211. case -3: case -4: //turrets
  2212. minDmg = 7.5f;
  2213. maxDmg = 7.5f;
  2214. break;
  2215. }
  2216. }
  2217. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->type->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2218. { //minDmg and maxDmg are multiplied by hero attack + 1
  2219. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2220. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2221. }
  2222. int attackDefenceDifference = 0;
  2223. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  2224. {
  2225. float multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f;
  2226. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  2227. }
  2228. else
  2229. {
  2230. attackDefenceDifference = attacker->Attack();
  2231. }
  2232. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  2233. {
  2234. float multDefenceReduction = (100.0f - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0f;
  2235. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  2236. }
  2237. else
  2238. {
  2239. attackDefenceDifference -= defender->Defense();
  2240. }
  2241. //calculating total attack/defense skills modifier
  2242. if(shooting) //precision handling (etc.)
  2243. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)).totalValue();
  2244. else //bloodlust handling (etc.)
  2245. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)).totalValue();
  2246. if(attacker->getEffect(55)) //slayer handling
  2247. {
  2248. std::vector<int> affectedIds;
  2249. int spLevel = attacker->getEffect(55)->level;
  2250. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  2251. {
  2252. BOOST_FOREACH(const Bonus &b, VLC->creh->creatures[g]->bonuses)
  2253. {
  2254. if ( (b.type == Bonus::KING3 && spLevel >= 3) || //expert
  2255. (b.type == Bonus::KING2 && spLevel >= 2) || //adv +
  2256. (b.type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  2257. {
  2258. affectedIds.push_back(g);
  2259. break;
  2260. }
  2261. }
  2262. }
  2263. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2264. {
  2265. if(defender->type->idNumber == affectedIds[g])
  2266. {
  2267. attackDefenceDifference += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2268. break;
  2269. }
  2270. }
  2271. }
  2272. //bonus from attack/defense skills
  2273. if(attackDefenceDifference < 0) //decreasing dmg
  2274. {
  2275. float dec = 0.025f * (-attackDefenceDifference);
  2276. if(dec > 0.7f)
  2277. {
  2278. multBonus *= 0.3f; //1.0 - 0.7
  2279. }
  2280. else
  2281. {
  2282. multBonus *= 1.0f - dec;
  2283. }
  2284. }
  2285. else //increasing dmg
  2286. {
  2287. float inc = 0.05f * attackDefenceDifference;
  2288. if(inc > 4.0f)
  2289. {
  2290. additiveBonus += 4.0f;
  2291. }
  2292. else
  2293. {
  2294. additiveBonus += inc;
  2295. }
  2296. }
  2297. //applying jousting bonus
  2298. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  2299. additiveBonus += charge * 0.05f;
  2300. //handling secondary abilities and artifacts giving premies to them
  2301. if(attackerHero)
  2302. {
  2303. if(shooting)
  2304. {
  2305. switch(attackerHero->getSecSkillLevel(1)) //archery
  2306. {
  2307. case 1: //basic
  2308. additiveBonus += 0.1f;
  2309. break;
  2310. case 2: //advanced
  2311. additiveBonus += 0.25f;
  2312. break;
  2313. case 3: //expert
  2314. additiveBonus += 0.5f;
  2315. break;
  2316. }
  2317. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  2318. {
  2319. //apply artifact premy to archery
  2320. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2321. }
  2322. }
  2323. else
  2324. {
  2325. switch(attackerHero->getSecSkillLevel(22)) //offense
  2326. {
  2327. case 1: //basic
  2328. additiveBonus += 0.1f;
  2329. break;
  2330. case 2: //advanced
  2331. additiveBonus += 0.2f;
  2332. break;
  2333. case 3: //expert
  2334. additiveBonus += 0.3f;
  2335. break;
  2336. }
  2337. }
  2338. }
  2339. if(defendingHero)
  2340. {
  2341. switch(defendingHero->getSecSkillLevel(23)) //armorer
  2342. {
  2343. case 1: //basic
  2344. multBonus *= 0.95f;
  2345. break;
  2346. case 2: //advanced
  2347. multBonus *= 0.9f;
  2348. break;
  2349. case 3: //expert
  2350. multBonus *= 0.85f;
  2351. break;
  2352. }
  2353. }
  2354. //handling hate effect
  2355. if( attacker->hasBonusOfType(Bonus::HATE, defender->type->idNumber) )
  2356. additiveBonus += 0.5f;
  2357. //luck bonus
  2358. if (lucky)
  2359. {
  2360. additiveBonus += 1.0f;
  2361. }
  2362. //handling spell effects
  2363. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2364. {
  2365. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2366. }
  2367. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2368. {
  2369. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2370. }
  2371. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2372. {
  2373. multBonus *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2374. }
  2375. class HLP
  2376. {
  2377. public:
  2378. static bool hasAdvancedAirShield(const CStack * stack)
  2379. {
  2380. for(int g=0; g<stack->effects.size(); ++g)
  2381. {
  2382. if (stack->effects[g].id == 28 && stack->effects[g].level >= 2)
  2383. {
  2384. return true;
  2385. }
  2386. }
  2387. return false;
  2388. }
  2389. };
  2390. //wall / distance penalty + advanced air shield
  2391. if (shooting && !NBonus::hasOfType(attackerHero, Bonus::NO_SHOTING_PENALTY) && (
  2392. hasDistancePenalty(attacker->ID, defender->position) || hasWallPenalty(attacker->ID, defender->position) ||
  2393. HLP::hasAdvancedAirShield(defender) )
  2394. )
  2395. {
  2396. multBonus *= 0.5;
  2397. }
  2398. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  2399. {
  2400. multBonus *= 0.5;
  2401. }
  2402. minDmg *= additiveBonus * multBonus;
  2403. maxDmg *= additiveBonus * multBonus;
  2404. std::pair<ui32, ui32> returnedVal;
  2405. if(attacker->getEffect(42)) //curse handling (rest)
  2406. {
  2407. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2408. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  2409. }
  2410. else if(attacker->getEffect(41)) //bless handling
  2411. {
  2412. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2413. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  2414. }
  2415. else
  2416. {
  2417. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  2418. }
  2419. //damage cannot be less than 1
  2420. amax(returnedVal.first, 1);
  2421. amax(returnedVal.second, 1);
  2422. return returnedVal;
  2423. }
  2424. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2425. {
  2426. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky);
  2427. if(range.first != range.second)
  2428. {
  2429. int valuesToAverage[10];
  2430. int howManyToAv = std::min<ui32>(10, attacker->count);
  2431. for (int g=0; g<howManyToAv; ++g)
  2432. {
  2433. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  2434. }
  2435. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  2436. }
  2437. else
  2438. return range.first;
  2439. }
  2440. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2441. {
  2442. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2443. {
  2444. const CStack * const st = stacks[i];
  2445. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  2446. amax(killed, 0);
  2447. if(killed)
  2448. casualties[!st->attackerOwned][st->type->idNumber] += killed;
  2449. }
  2450. }
  2451. si8 CGameState::battleMaxSpellLevel()
  2452. {
  2453. if(!curB) //there is not battle
  2454. {
  2455. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2456. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2457. }
  2458. si8 levelLimit = SPELL_LEVELS;
  2459. const CGHeroInstance *h1 = curB->heroes[0];
  2460. if(h1)
  2461. {
  2462. for(std::list<Bonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2463. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2464. amin(levelLimit, i->val);
  2465. }
  2466. const CGHeroInstance *h2 = curB->heroes[1];
  2467. if(h2)
  2468. {
  2469. for(std::list<Bonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2470. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2471. amin(levelLimit, i->val);
  2472. }
  2473. return levelLimit;
  2474. }
  2475. std::set<CStack*> BattleInfo::getAttackedCreatures( const CSpell * s, int skillLevel, ui8 attackerOwner, int destinationTile )
  2476. {
  2477. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  2478. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2479. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2480. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2481. {
  2482. for(int it=0; it<stacks.size(); ++it)
  2483. {
  2484. if((s->id == 24 && !stacks[it]->type->isUndead()) //death ripple
  2485. || (s->id == 25 && stacks[it]->type->isUndead()) //destroy undead
  2486. || (s->id == 26) //Armageddon
  2487. )
  2488. {
  2489. if(stacks[it]->alive())
  2490. attackedCres.insert(stacks[it]);
  2491. }
  2492. }
  2493. }
  2494. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2495. || VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  2496. {
  2497. if(skillLevel < 3) /*not expert */
  2498. {
  2499. CStack * st = getStackT(destinationTile, onlyAlive);
  2500. if(st)
  2501. attackedCres.insert(st);
  2502. }
  2503. else
  2504. {
  2505. for(int it=0; it<stacks.size(); ++it)
  2506. {
  2507. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2508. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == attackerOwner)
  2509. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != attackerOwner )
  2510. )
  2511. {
  2512. if(!onlyAlive || stacks[it]->alive())
  2513. attackedCres.insert(stacks[it]);
  2514. }
  2515. }
  2516. } //if(caster->getSpellSchoolLevel(s) < 3)
  2517. }
  2518. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2519. {
  2520. CStack * st = getStackT(destinationTile, onlyAlive);
  2521. if(st)
  2522. attackedCres.insert(st);
  2523. }
  2524. else //custom range from attackedHexes
  2525. {
  2526. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2527. {
  2528. CStack * st = getStackT(*it, onlyAlive);
  2529. if(st)
  2530. attackedCres.insert(st);
  2531. }
  2532. }
  2533. return attackedCres;
  2534. }
  2535. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower )
  2536. {
  2537. if(!caster) //TODO: something better
  2538. return std::max(5, usedSpellPower);
  2539. switch(spell->id)
  2540. {
  2541. case 56: //frenzy
  2542. return 1;
  2543. default: //other spells
  2544. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  2545. }
  2546. }
  2547. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2548. {
  2549. CStack * ret = new CStack(&base, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2550. //native terrain bonuses
  2551. int faction = ret->type->faction;
  2552. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2553. {
  2554. ret->bonuses.push_back(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE));
  2555. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE));
  2556. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE));
  2557. }
  2558. ret->position = position;
  2559. return ret;
  2560. }
  2561. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2562. {
  2563. ui32 ret = caster->getSpellCost(sp);
  2564. //checking for friendly stacks reducing cost of the spell and
  2565. //enemy stacks increasing it
  2566. si32 manaReduction = 0;
  2567. si32 manaIncrease = 0;
  2568. for(int g=0; g<stacks.size(); ++g)
  2569. {
  2570. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  2571. {
  2572. amin(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  2573. }
  2574. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  2575. {
  2576. amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  2577. }
  2578. }
  2579. return ret + manaReduction + manaIncrease;
  2580. }
  2581. int BattleInfo::hexToWallPart(int hex) const
  2582. {
  2583. if(siege == 0) //there is no battle!
  2584. return -1;
  2585. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2586. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2587. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7)};
  2588. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2589. {
  2590. if(attackable[g].first == hex)
  2591. return attackable[g].second;
  2592. }
  2593. return -1; //not found!
  2594. }
  2595. int BattleInfo::lineToWallHex( int line ) const
  2596. {
  2597. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  2598. return lineToHex[line];
  2599. }
  2600. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2601. {
  2602. bool ac[BFIELD_SIZE];
  2603. std::set<int> occupyable;
  2604. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest->ID);
  2605. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2606. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  2607. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2608. for(int g=0; g<BFIELD_SIZE; ++g)
  2609. {
  2610. const CStack * atG = getStackT(g);
  2611. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2612. continue;
  2613. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2614. {
  2615. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2616. continue;
  2617. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2618. }
  2619. }
  2620. if(stackPairs.size() > 0)
  2621. {
  2622. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2623. minimalPairs.push_back(stackPairs[0]);
  2624. for(int b=1; b<stackPairs.size(); ++b)
  2625. {
  2626. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2627. {
  2628. minimalPairs.clear();
  2629. minimalPairs.push_back(stackPairs[b]);
  2630. }
  2631. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2632. {
  2633. minimalPairs.push_back(stackPairs[b]);
  2634. }
  2635. }
  2636. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2637. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2638. }
  2639. return std::make_pair<const CStack * , int>(NULL, -1);
  2640. }
  2641. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  2642. {
  2643. ui32 ret = 0; //value to return
  2644. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  2645. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  2646. static std::map <int, int> dmgMultipliers = boost::assign::map_list_of(15, 10)(16, 20)(17, 25)(18, 75)(20, 10)(21, 10)(22, 10)(23, 10)(24, 5)(25, 10)(26, 50)(77, 10);
  2647. //check if spell really does damage - if not, return 0
  2648. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  2649. return 0;
  2650. ret = usedSpellPower * dmgMultipliers[sp->id];
  2651. ret += sp->powers[spellSchoolLevel];
  2652. //applying sorcerery secondary skill
  2653. if(caster)
  2654. {
  2655. switch(caster->getSecSkillLevel(25))
  2656. {
  2657. case 1: //basic
  2658. ret *= 1.05f;
  2659. break;
  2660. case 2: //advanced
  2661. ret *= 1.1f;
  2662. break;
  2663. case 3: //expert
  2664. ret *= 1.15f;
  2665. break;
  2666. }
  2667. }
  2668. //applying hero bonuses
  2669. if(sp->air && caster && caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY) != 0)
  2670. {
  2671. ret *= (100.0f + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  2672. }
  2673. else if(sp->fire && caster && caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY) != 0)
  2674. {
  2675. ret *= (100.0f + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  2676. }
  2677. else if(sp->water && caster && caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY) != 0)
  2678. {
  2679. ret *= (100.0f + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  2680. }
  2681. else if(sp->earth && caster && caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY) != 0)
  2682. {
  2683. ret *= (100.0f + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  2684. }
  2685. //affected creature-specific part
  2686. if(affectedCreature)
  2687. {
  2688. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2689. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  2690. {
  2691. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  2692. ret /= 100;
  2693. }
  2694. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  2695. {
  2696. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  2697. ret /= 100;
  2698. }
  2699. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  2700. {
  2701. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  2702. ret /= 100;
  2703. }
  2704. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  2705. {
  2706. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  2707. ret /= 100;
  2708. }
  2709. //general spell dmg reduction
  2710. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  2711. {
  2712. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  2713. ret /= 100;
  2714. }
  2715. //dmg increasing
  2716. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  2717. {
  2718. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  2719. ret /= 100;
  2720. }
  2721. }
  2722. return ret;
  2723. }
  2724. bool CGameState::battleCanShoot(int ID, int dest)
  2725. {
  2726. if(!curB)
  2727. return false;
  2728. const CStack *our = curB->getStack(ID),
  2729. *dst = curB->getStackT(dest);
  2730. if(!our || !dst) return false;
  2731. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  2732. if(our->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  2733. return false;
  2734. if(our->type->idNumber == 145 && dst) //catapult cannot attack creatures
  2735. return false;
  2736. if(our->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  2737. && our->owner != dst->owner
  2738. && dst->alive()
  2739. && (!curB->isStackBlocked(ID) || NBonus::hasOfType(ourHero, Bonus::FREE_SHOOTING))
  2740. && our->shots
  2741. )
  2742. return true;
  2743. return false;
  2744. }
  2745. int CGameState::victoryCheck( ui8 player ) const
  2746. {
  2747. const PlayerState *p = getPlayer(player);
  2748. if(map->victoryCondition.condition == winStandard || map->victoryCondition.allowNormalVictory)
  2749. if(player == checkForStandardWin())
  2750. return -1;
  2751. if(p->human || map->victoryCondition.appliesToAI)
  2752. {
  2753. switch(map->victoryCondition.condition)
  2754. {
  2755. case artifact:
  2756. //check if any hero has winning artifact
  2757. for(size_t i = 0; i < p->heroes.size(); i++)
  2758. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  2759. return 1;
  2760. break;
  2761. case gatherTroop:
  2762. {
  2763. //check if in players armies there is enough creatures
  2764. int total = 0; //creature counter
  2765. for(size_t i = 0; i < map->objects.size(); i++)
  2766. {
  2767. const CArmedInstance *ai = NULL;
  2768. if(map->objects[i]
  2769. && map->objects[i]->tempOwner == player //object controlled by player
  2770. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i]))) //contains army
  2771. {
  2772. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  2773. if(i->second.type->idNumber == map->victoryCondition.ID) //it's searched creature
  2774. total += i->second.count;
  2775. }
  2776. }
  2777. if(total >= map->victoryCondition.count)
  2778. return 1;
  2779. }
  2780. break;
  2781. case gatherResource:
  2782. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  2783. return 1;
  2784. break;
  2785. case buildCity:
  2786. {
  2787. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2788. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  2789. return 1;
  2790. }
  2791. break;
  2792. case buildGrail:
  2793. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  2794. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  2795. && t->tempOwner == player
  2796. && vstd::contains(t->builtBuildings, 26))
  2797. return 1;
  2798. break;
  2799. case beatHero:
  2800. if(map->victoryCondition.obj->tempOwner >= PLAYER_LIMIT) //target hero not present on map
  2801. return 1;
  2802. break;
  2803. case captureCity:
  2804. {
  2805. if(map->victoryCondition.obj->tempOwner == player)
  2806. return 1;
  2807. }
  2808. break;
  2809. case beatMonster:
  2810. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  2811. return 1;
  2812. break;
  2813. case takeDwellings:
  2814. for(size_t i = 0; i < map->objects.size(); i++)
  2815. {
  2816. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2817. {
  2818. switch(map->objects[i]->ID)
  2819. {
  2820. case 17: case 18: case 19: case 20: //dwellings
  2821. case 216: case 217: case 218:
  2822. return 0; //found not flagged dwelling - player not won
  2823. }
  2824. }
  2825. }
  2826. return 1;
  2827. break;
  2828. case takeMines:
  2829. for(size_t i = 0; i < map->objects.size(); i++)
  2830. {
  2831. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2832. {
  2833. switch(map->objects[i]->ID)
  2834. {
  2835. case 53: case 220:
  2836. return 0; //found not flagged mine - player not won
  2837. }
  2838. }
  2839. }
  2840. return 1;
  2841. break;
  2842. case transportItem:
  2843. {
  2844. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2845. if(t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID)
  2846. || t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID))
  2847. {
  2848. return 1;
  2849. }
  2850. }
  2851. break;
  2852. }
  2853. }
  2854. return 0;
  2855. }
  2856. ui8 CGameState::checkForStandardWin() const
  2857. {
  2858. //std victory condition is:
  2859. //all enemies lost
  2860. ui8 supposedWinner = 255, winnerTeam = 255;
  2861. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  2862. {
  2863. if(i->second.status == PlayerState::INGAME && i->first < PLAYER_LIMIT)
  2864. {
  2865. if(supposedWinner == 255)
  2866. {
  2867. //first player remaining ingame - candidate for victory
  2868. supposedWinner = i->second.color;
  2869. winnerTeam = map->players[supposedWinner].team;
  2870. }
  2871. else if(winnerTeam != map->players[i->second.color].team)
  2872. {
  2873. //current candidate has enemy remaining in game -> no vicotry
  2874. return 255;
  2875. }
  2876. }
  2877. }
  2878. return supposedWinner;
  2879. }
  2880. bool CGameState::checkForStandardLoss( ui8 player ) const
  2881. {
  2882. //std loss condition is: player lost all towns and heroes
  2883. const PlayerState &p = *getPlayer(player);
  2884. return !p.heroes.size() && !p.towns.size();
  2885. }
  2886. struct statsHLP
  2887. {
  2888. typedef std::pair< ui8, si64 > TStat;
  2889. //converts [<player's color, value>] to vec[place] -> platers
  2890. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  2891. {
  2892. std::sort(stats.begin(), stats.end(), statsHLP());
  2893. //put first element
  2894. std::vector< std::list<ui8> > ret;
  2895. std::list<ui8> tmp;
  2896. tmp.push_back( stats[0].first );
  2897. ret.push_back( tmp );
  2898. //the rest of elements
  2899. for(int g=1; g<stats.size(); ++g)
  2900. {
  2901. if(stats[g].second == stats[g-1].second)
  2902. {
  2903. (ret.end()-1)->push_back( stats[g].first );
  2904. }
  2905. else
  2906. {
  2907. //create next occupied rank
  2908. std::list<ui8> tmp;
  2909. tmp.push_back(stats[g].first);
  2910. ret.push_back(tmp);
  2911. }
  2912. }
  2913. return ret;
  2914. }
  2915. bool operator()(const TStat & a, const TStat & b) const
  2916. {
  2917. return a.second > b.second;
  2918. }
  2919. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2920. {
  2921. std::vector<CGHeroInstance *> &h = gs->players[color].heroes;
  2922. if(!h.size())
  2923. return NULL;
  2924. //best hero will be that with highest exp
  2925. int best = 0;
  2926. for(int b=1; b<h.size(); ++b)
  2927. {
  2928. if(h[b]->exp > h[best]->exp)
  2929. {
  2930. best = b;
  2931. }
  2932. }
  2933. return h[best];
  2934. }
  2935. //calculates total number of artifacts that belong to given player
  2936. static int getNumberOfArts(const PlayerState * ps)
  2937. {
  2938. int ret = 0;
  2939. for(int g=0; g<ps->heroes.size(); ++g)
  2940. {
  2941. ret += ps->heroes[g]->artifacts.size() + ps->heroes[g]->artifWorn.size();
  2942. }
  2943. return ret;
  2944. }
  2945. };
  2946. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2947. {
  2948. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2949. { \
  2950. std::vector< std::pair< ui8, si64 > > stats; \
  2951. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  2952. { \
  2953. if(g->second.color == 255) \
  2954. continue; \
  2955. std::pair< ui8, si64 > stat; \
  2956. stat.first = g->second.color; \
  2957. stat.second = VAL_GETTER; \
  2958. stats.push_back(stat); \
  2959. } \
  2960. tgi.FIELD = statsHLP::getRank(stats); \
  2961. }
  2962. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2963. {
  2964. if(g->second.color != 255)
  2965. tgi.playerColors.push_back(g->second.color);
  2966. }
  2967. if(level >= 1) //num of towns & num of heroes
  2968. {
  2969. //num of towns
  2970. FILL_FIELD(numOfTowns, g->second.towns.size())
  2971. //num of heroes
  2972. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2973. //best hero's portrait
  2974. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2975. {
  2976. if(g->second.color == 255)
  2977. continue;
  2978. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2979. InfoAboutHero iah;
  2980. iah.initFromHero(best, level >= 8);
  2981. iah.army.clear();
  2982. tgi.colorToBestHero[g->second.color] = iah;
  2983. }
  2984. }
  2985. if(level >= 2) //gold
  2986. {
  2987. FILL_FIELD(gold, g->second.resources[6])
  2988. }
  2989. if(level >= 2) //wood & ore
  2990. {
  2991. FILL_FIELD(woodOre, g->second.resources[0] + g->second.resources[1])
  2992. }
  2993. if(level >= 3) //mercury, sulfur, crystal, gems
  2994. {
  2995. FILL_FIELD(mercSulfCrystGems, g->second.resources[2] + g->second.resources[3] + g->second.resources[4] + g->second.resources[5])
  2996. }
  2997. if(level >= 4) //obelisks found
  2998. {
  2999. //TODO
  3000. }
  3001. if(level >= 5) //artifacts
  3002. {
  3003. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  3004. }
  3005. if(level >= 6) //army strength
  3006. {
  3007. //TODO
  3008. }
  3009. if(level >= 7) //income
  3010. {
  3011. //TODO
  3012. }
  3013. if(level >= 8) //best hero's stats
  3014. {
  3015. //already set in lvl 1 handling
  3016. }
  3017. if(level >= 9) //personality
  3018. {
  3019. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3020. {
  3021. if(g->second.color == 255) //do nothing for neutral player
  3022. continue;
  3023. if(g->second.human)
  3024. {
  3025. tgi.personality[g->second.color] = -1;
  3026. }
  3027. else //AI
  3028. {
  3029. tgi.personality[g->second.color] = map->players[g->second.serial].AITactic;
  3030. }
  3031. }
  3032. }
  3033. if(level >= 10) //best creature
  3034. {
  3035. //best creatures belonging to player (highest AI value)
  3036. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3037. {
  3038. if(g->second.color == 255) //do nothing for neutral player
  3039. continue;
  3040. int bestCre = -1; //best creature's ID
  3041. for(int b=0; b<g->second.heroes.size(); ++b)
  3042. {
  3043. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  3044. {
  3045. int toCmp = it->second.type->idNumber; //ID of creature we should compare with the best one
  3046. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  3047. {
  3048. bestCre = toCmp;
  3049. }
  3050. }
  3051. }
  3052. tgi.bestCreature[g->second.color] = bestCre;
  3053. }
  3054. }
  3055. #undef FILL_FIELD
  3056. }
  3057. int CGameState::lossCheck( ui8 player ) const
  3058. {
  3059. const PlayerState *p = getPlayer(player);
  3060. //if(map->lossCondition.typeOfLossCon == lossStandard)
  3061. if(checkForStandardLoss(player))
  3062. return -1;
  3063. if(p->human) //special loss condition applies only to human player
  3064. {
  3065. switch(map->lossCondition.typeOfLossCon)
  3066. {
  3067. case lossCastle:
  3068. {
  3069. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  3070. assert(t);
  3071. if(t->tempOwner != player)
  3072. return 1;
  3073. }
  3074. break;
  3075. case lossHero:
  3076. {
  3077. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  3078. assert(h);
  3079. if(h->tempOwner != player)
  3080. return 1;
  3081. }
  3082. break;
  3083. case timeExpires:
  3084. if(map->lossCondition.timeLimit < day)
  3085. return 1;
  3086. break;
  3087. }
  3088. }
  3089. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  3090. return 2;
  3091. return false;
  3092. }
  3093. std::map<ui32,CGHeroInstance *> CGameState::unusedHeroesFromPool()
  3094. {
  3095. std::map<ui32,CGHeroInstance *> pool = hpool.heroesPool;
  3096. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  3097. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  3098. if(*j)
  3099. pool.erase((**j).subID);
  3100. return pool;
  3101. }
  3102. const CStack * BattleInfo::getNextStack() const
  3103. {
  3104. std::vector<const CStack *> hlp;
  3105. getStackQueue(hlp, 1, -1);
  3106. if(hlp.size())
  3107. return hlp[0];
  3108. else
  3109. return NULL;
  3110. }
  3111. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  3112. {
  3113. const CStack *ret = NULL;
  3114. unsigned i, //fastest stack
  3115. j; //fastest stack of the other side
  3116. for(i = 0; i < st.size(); i++)
  3117. if(st[i])
  3118. break;
  3119. //no stacks left
  3120. if(i == st.size())
  3121. return NULL;
  3122. const CStack *fastest = st[i], *other = NULL;
  3123. int bestSpeed = fastest->Speed(turn);
  3124. if(fastest->attackerOwned != curside)
  3125. {
  3126. ret = fastest;
  3127. }
  3128. else
  3129. {
  3130. for(j = i + 1; j < st.size(); j++)
  3131. {
  3132. if(!st[j]) continue;
  3133. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  3134. break;
  3135. }
  3136. if(j >= st.size())
  3137. {
  3138. ret = fastest;
  3139. }
  3140. else
  3141. {
  3142. other = st[j];
  3143. if(other->Speed(turn) != bestSpeed)
  3144. ret = fastest;
  3145. else
  3146. ret = other;
  3147. }
  3148. }
  3149. assert(ret);
  3150. if(ret == fastest)
  3151. st[i] = NULL;
  3152. else
  3153. st[j] = NULL;
  3154. curside = ret->attackerOwned;
  3155. return ret;
  3156. }
  3157. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  3158. {
  3159. //we'll split creatures with remaining movement to 4 parts
  3160. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  3161. int toMove = 0; //how many stacks still has move
  3162. const CStack *active = getStack(activeStack);
  3163. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  3164. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  3165. {
  3166. out.push_back(active);
  3167. if(out.size() == howMany)
  3168. return;
  3169. }
  3170. for(unsigned int i=0; i<stacks.size(); ++i)
  3171. {
  3172. const CStack * const s = stacks[i];
  3173. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  3174. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  3175. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  3176. {
  3177. continue;
  3178. }
  3179. int p = -1; //in which phase this tack will move?
  3180. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  3181. {
  3182. if(vstd::contains(s->state, HAD_MORALE))
  3183. p = 2;
  3184. else
  3185. p = 3;
  3186. }
  3187. else if(s->type->idNumber == 145 || s->type->idNumber == 149) //catapult and turrets are first
  3188. {
  3189. p = 0;
  3190. }
  3191. else
  3192. {
  3193. p = 1;
  3194. }
  3195. phase[p].push_back(s);
  3196. toMove++;
  3197. }
  3198. for(int i = 0; i < 4; i++)
  3199. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  3200. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  3201. out.push_back(phase[0][i]);
  3202. if(out.size() == howMany)
  3203. return;
  3204. if(lastMoved == -1)
  3205. {
  3206. if(active)
  3207. {
  3208. if(out.size() && out.front() == active)
  3209. lastMoved = active->attackerOwned;
  3210. else
  3211. lastMoved = active->attackerOwned;
  3212. }
  3213. else
  3214. {
  3215. lastMoved = 0;
  3216. }
  3217. }
  3218. int pi = 1;
  3219. while(out.size() < howMany)
  3220. {
  3221. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  3222. if(!hlp)
  3223. {
  3224. pi++;
  3225. if(pi > 3)
  3226. {
  3227. //if(turn != 2)
  3228. getStackQueue(out, howMany, turn + 1, lastMoved);
  3229. return;
  3230. }
  3231. }
  3232. else
  3233. {
  3234. out.push_back(hlp);
  3235. }
  3236. }
  3237. }
  3238. si8 BattleInfo::hasDistancePenalty( int stackID, int destHex )
  3239. {
  3240. const CStack * stack = getStack(stackID);
  3241. int distance = std::abs(destHex % BFIELD_WIDTH - stack->position % BFIELD_WIDTH);
  3242. //I hope it's approximately correct
  3243. return distance > 8 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  3244. }
  3245. si8 BattleInfo::sameSideOfWall(int pos1, int pos2)
  3246. {
  3247. int wallInStackLine = lineToWallHex(pos1/BFIELD_WIDTH);
  3248. int wallInDestLine = lineToWallHex(pos2/BFIELD_WIDTH);
  3249. bool stackLeft = pos1 < wallInStackLine;
  3250. bool destLeft = pos2 < wallInDestLine;
  3251. return stackLeft != destLeft;
  3252. }
  3253. si8 BattleInfo::hasWallPenalty( int stackID, int destHex )
  3254. {
  3255. if (siege == 0)
  3256. {
  3257. return false;
  3258. }
  3259. const CStack * stack = getStack(stackID);
  3260. if (stack->hasBonusOfType(Bonus::NO_WALL_PENALTY));
  3261. {
  3262. return false;
  3263. }
  3264. return !sameSideOfWall(stack->position, destHex);
  3265. }
  3266. si8 BattleInfo::canTeleportTo(int stackID, int destHex, int telportLevel)
  3267. {
  3268. bool ac[BFIELD_SIZE];
  3269. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  3270. std::set<int> occupyable;
  3271. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, false, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  3272. if (siege && telportLevel < 2) //check for wall
  3273. {
  3274. return ac[destHex] && sameSideOfWall(s->position, destHex);
  3275. }
  3276. else
  3277. {
  3278. return ac[destHex];
  3279. }
  3280. }
  3281. void BattleInfo::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  3282. {
  3283. CBonusSystemNode::getBonuses(out, selector, root);
  3284. const CStack *dest = dynamic_cast<const CStack*>(root);
  3285. if (!dest)
  3286. return;
  3287. //TODO: make it in clean way
  3288. if(Selector::matchesType(selector, Bonus::MORALE) || Selector::matchesType(selector, Bonus::LUCK))
  3289. {
  3290. BOOST_FOREACH(const CStack *s, stacks)
  3291. {
  3292. if(s->owner == dest->owner)
  3293. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ALLIED_ARMY), this);
  3294. else
  3295. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ENEMY_ARMY), this);
  3296. }
  3297. }
  3298. }
  3299. int3 CPath::startPos() const
  3300. {
  3301. return nodes[nodes.size()-1].coord;
  3302. }
  3303. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  3304. {
  3305. if (mode==0)
  3306. {
  3307. for (unsigned int i=0;i<nodes.size();i++)
  3308. {
  3309. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3310. }
  3311. }
  3312. }
  3313. int3 CPath::endPos() const
  3314. {
  3315. return nodes[0].coord;
  3316. }
  3317. CGPathNode::CGPathNode()
  3318. :coord(-1,-1,-1)
  3319. {
  3320. accessible = 0;
  3321. land = 0;
  3322. moveRemains = 0;
  3323. turns = 255;
  3324. theNodeBefore = NULL;
  3325. }
  3326. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  3327. {
  3328. out.nodes.clear();
  3329. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  3330. if(!curnode->theNodeBefore || curnode->accessible == CGPathNode::FLYABLE)
  3331. return false;
  3332. //we'll transform number of turns to conform the rule that hero cannot stop on blocked tile
  3333. bool transition01 = false;
  3334. while(curnode)
  3335. {
  3336. CGPathNode cpn = *curnode;
  3337. if(transition01)
  3338. {
  3339. if (curnode->accessible == CGPathNode::ACCESSIBLE)
  3340. {
  3341. transition01 = false;
  3342. }
  3343. else if (curnode->accessible == CGPathNode::FLYABLE)
  3344. {
  3345. cpn.turns = 1;
  3346. }
  3347. }
  3348. if(curnode->turns == 1 && curnode->theNodeBefore->turns == 0)
  3349. {
  3350. transition01 = true;
  3351. }
  3352. curnode = curnode->theNodeBefore;
  3353. out.nodes.push_back(cpn);
  3354. }
  3355. return true;
  3356. }
  3357. CPathsInfo::CPathsInfo( const int3 &Sizes )
  3358. :sizes(Sizes)
  3359. {
  3360. hero = NULL;
  3361. nodes = new CGPathNode**[sizes.x];
  3362. for(int i = 0; i < sizes.x; i++)
  3363. {
  3364. nodes[i] = new CGPathNode*[sizes.y];
  3365. for (int j = 0; j < sizes.y; j++)
  3366. {
  3367. nodes[i][j] = new CGPathNode[sizes.z];
  3368. }
  3369. }
  3370. }
  3371. CPathsInfo::~CPathsInfo()
  3372. {
  3373. for(int i = 0; i < sizes.x; i++)
  3374. {
  3375. for (int j = 0; j < sizes.y; j++)
  3376. {
  3377. delete [] nodes[i][j];
  3378. }
  3379. delete [] nodes[i];
  3380. }
  3381. delete [] nodes;
  3382. }
  3383. int3 CGPath::startPos() const
  3384. {
  3385. return nodes[nodes.size()-1].coord;
  3386. }
  3387. int3 CGPath::endPos() const
  3388. {
  3389. return nodes[0].coord;
  3390. }
  3391. void CGPath::convert( ui8 mode )
  3392. {
  3393. if(mode==0)
  3394. {
  3395. for(unsigned int i=0;i<nodes.size();i++)
  3396. {
  3397. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3398. }
  3399. }
  3400. }
  3401. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  3402. {
  3403. switch(phase)
  3404. {
  3405. case 0: //catapult moves after turrets
  3406. return a->type->idNumber < b->type->idNumber; //catapult is 145 and turrets are 149
  3407. //TODO? turrets order
  3408. case 1: //fastest first, upper slot first
  3409. {
  3410. int as = a->Speed(turn), bs = b->Speed(turn);
  3411. if(as != bs)
  3412. return as > bs;
  3413. else
  3414. return a->slot < b->slot;
  3415. }
  3416. case 2: //fastest last, upper slot first
  3417. //TODO: should be replaced with order of receiving morale!
  3418. case 3: //fastest last, upper slot first
  3419. {
  3420. int as = a->Speed(turn), bs = b->Speed(turn);
  3421. if(as != bs)
  3422. return as < bs;
  3423. else
  3424. return a->slot < b->slot;
  3425. }
  3426. default:
  3427. assert(0);
  3428. return false;
  3429. }
  3430. }
  3431. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  3432. {
  3433. phase = Phase;
  3434. turn = Turn;
  3435. }
  3436. PlayerState::PlayerState()
  3437. : color(-1), currentSelection(0xffffffff), status(INGAME), daysWithoutCastle(0)
  3438. {
  3439. }
  3440. void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  3441. {
  3442. /*
  3443. for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); ++it)
  3444. {
  3445. if (*it != root)
  3446. (*it)->getParents(out, root);
  3447. }
  3448. for (std::vector<CGTownInstance *>::const_iterator it = towns.begin(); it != towns.end(); ++it)
  3449. {
  3450. if (*it != root)
  3451. (*it)->getParents(out, root);
  3452. }
  3453. */
  3454. //TODO - dwellings
  3455. }
  3456. void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  3457. {//temporary
  3458. //CBonusSystemNode::getBonuses(out, selector, root);
  3459. }
  3460. InfoAboutHero::InfoAboutHero()
  3461. {
  3462. details = NULL;
  3463. hclass = NULL;
  3464. portrait = -1;
  3465. }
  3466. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  3467. {
  3468. assign(iah);
  3469. }
  3470. InfoAboutHero::~InfoAboutHero()
  3471. {
  3472. delete details;
  3473. }
  3474. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  3475. {
  3476. if(!h) return;
  3477. owner = h->tempOwner;
  3478. hclass = h->type->heroClass;
  3479. name = h->name;
  3480. portrait = h->portrait;
  3481. army = h->getArmy();
  3482. if(detailed)
  3483. {
  3484. //include details about hero
  3485. details = new Details;
  3486. details->luck = h->LuckVal();
  3487. details->morale = h->MoraleVal();
  3488. details->mana = h->mana;
  3489. details->primskills.resize(PRIMARY_SKILLS);
  3490. for (int i = 0; i < PRIMARY_SKILLS ; i++)
  3491. {
  3492. details->primskills[i] = h->getPrimSkillLevel(i);
  3493. }
  3494. }
  3495. else
  3496. {
  3497. //hide info about hero stacks counts using descriptives names ids
  3498. for(TSlots::const_iterator i = army.Slots().begin(); i != army.Slots().end(); ++i)
  3499. {
  3500. army.setStackCount(i->first, i->second.getQuantityID()+1);
  3501. }
  3502. }
  3503. }
  3504. void InfoAboutHero::assign( const InfoAboutHero & iah )
  3505. {
  3506. army = iah.army;
  3507. details = (iah.details ? new Details(*iah.details) : NULL);
  3508. hclass = iah.hclass;
  3509. name = iah.name;
  3510. owner = iah.owner;
  3511. portrait = iah.portrait;
  3512. }
  3513. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  3514. {
  3515. assign(iah);
  3516. return *this;
  3517. }
  3518. void CCampaignState::initNewCampaign( const StartInfo &si )
  3519. {
  3520. assert(si.mode == 2);
  3521. campaignName = si.mapname;
  3522. currentMap = si.whichMapInCampaign;
  3523. camp = CCampaignHandler::getCampaign(campaignName, true); //TODO lod???
  3524. for (ui8 i = 0; i < camp->mapPieces.size(); i++)
  3525. mapsRemaining.push_back(i);
  3526. }