2
0

CGameState.cpp 130 KB

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