CGameHandler.cpp 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034
  1. #include "stdafx.h"
  2. #include "../lib/CCampaignHandler.h"
  3. #include "../StartInfo.h"
  4. #include "../lib/CArtHandler.h"
  5. #include "../lib/CBuildingHandler.h"
  6. #include "../lib/CDefObjInfoHandler.h"
  7. #include "../lib/CHeroHandler.h"
  8. #include "../lib/CObjectHandler.h"
  9. #include "../lib/CSpellHandler.h"
  10. #include "../lib/CGeneralTextHandler.h"
  11. #include "../lib/CTownHandler.h"
  12. #include "../lib/CCreatureHandler.h"
  13. #include "../lib/CGameState.h"
  14. #include "../lib/BattleState.h"
  15. #include "../lib/CondSh.h"
  16. #include "../lib/NetPacks.h"
  17. #include "../lib/VCMI_Lib.h"
  18. #include "../lib/map.h"
  19. #include "../lib/VCMIDirs.h"
  20. #include "../client/CSoundBase.h"
  21. #include "CGameHandler.h"
  22. /*
  23. * CGameHandler.cpp, part of VCMI engine
  24. *
  25. * Authors: listed in file AUTHORS in main folder
  26. *
  27. * License: GNU General Public License v2.0 or later
  28. * Full text of license available in license.txt file, in main folder
  29. *
  30. */
  31. #undef DLL_EXPORT
  32. #define DLL_EXPORT
  33. #include "../lib/RegisterTypes.cpp"
  34. #ifndef _MSC_VER
  35. #include <boost/thread/xtime.hpp>
  36. #endif
  37. extern bool end2;
  38. #ifdef min
  39. #undef min
  40. #endif
  41. #ifdef max
  42. #undef max
  43. #endif
  44. #define COMPLAIN_RET_IF(cond, txt) do {if(cond){complain(txt); return;}} while(0)
  45. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  46. #define NEW_ROUND BattleNextRound bnr;\
  47. bnr.round = gs->curB->round + 1;\
  48. sendAndApply(&bnr);
  49. CondSh<bool> battleMadeAction;
  50. CondSh<BattleResult *> battleResult(NULL);
  51. std::ptrdiff_t randomizer (ptrdiff_t i) {return rand();}
  52. std::ptrdiff_t (*p_myrandom)(std::ptrdiff_t) = randomizer;
  53. template <typename T> class CApplyOnGH;
  54. class CBaseForGHApply
  55. {
  56. public:
  57. virtual bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  58. virtual ~CBaseForGHApply(){}
  59. template<typename U> static CBaseForGHApply *getApplier(const U * t=NULL)
  60. {
  61. return new CApplyOnGH<U>;
  62. }
  63. };
  64. template <typename T> class CApplyOnGH : public CBaseForGHApply
  65. {
  66. public:
  67. bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  68. {
  69. T *ptr = static_cast<T*>(pack);
  70. ptr->c = c;
  71. return ptr->applyGh(gh);
  72. }
  73. };
  74. static CApplier<CBaseForGHApply> *applier = NULL;
  75. CMP_stack cmpst ;
  76. static inline double distance(int3 a, int3 b)
  77. {
  78. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  79. }
  80. static void giveExp(BattleResult &r)
  81. {
  82. r.exp[0] = 0;
  83. r.exp[1] = 0;
  84. for(std::map<ui32,si32>::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  85. {
  86. r.exp[r.winner] += VLC->creh->creatures[i->first]->valOfBonuses(Bonus::STACK_HEALTH) * i->second;
  87. }
  88. }
  89. PlayerStatus PlayerStatuses::operator[](ui8 player)
  90. {
  91. boost::unique_lock<boost::mutex> l(mx);
  92. if(players.find(player) != players.end())
  93. {
  94. return players[player];
  95. }
  96. else
  97. {
  98. throw std::string("No such player!");
  99. }
  100. }
  101. void PlayerStatuses::addPlayer(ui8 player)
  102. {
  103. boost::unique_lock<boost::mutex> l(mx);
  104. players[player];
  105. }
  106. bool PlayerStatuses::hasQueries(ui8 player)
  107. {
  108. boost::unique_lock<boost::mutex> l(mx);
  109. if(players.find(player) != players.end())
  110. {
  111. return players[player].queries.size();
  112. }
  113. else
  114. {
  115. throw std::string("No such player!");
  116. }
  117. }
  118. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  119. {
  120. boost::unique_lock<boost::mutex> l(mx);
  121. if(players.find(player) != players.end())
  122. {
  123. return players[player].*flag;
  124. }
  125. else
  126. {
  127. throw std::string("No such player!");
  128. }
  129. }
  130. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  131. {
  132. boost::unique_lock<boost::mutex> l(mx);
  133. if(players.find(player) != players.end())
  134. {
  135. players[player].*flag = val;
  136. }
  137. else
  138. {
  139. throw std::string("No such player!");
  140. }
  141. cv.notify_all();
  142. }
  143. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  144. {
  145. boost::unique_lock<boost::mutex> l(mx);
  146. if(players.find(player) != players.end())
  147. {
  148. players[player].queries.insert(id);
  149. }
  150. else
  151. {
  152. throw std::string("No such player!");
  153. }
  154. cv.notify_all();
  155. }
  156. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  157. {
  158. boost::unique_lock<boost::mutex> l(mx);
  159. if(players.find(player) != players.end())
  160. {
  161. players[player].queries.erase(id);
  162. }
  163. else
  164. {
  165. throw std::string("No such player!");
  166. }
  167. cv.notify_all();
  168. }
  169. template <typename T>
  170. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  171. {
  172. fun(args[which]);
  173. }
  174. void CGameHandler::levelUpHero(int ID, int skill)
  175. {
  176. changeSecSkill(ID, skill, 1, 0);
  177. levelUpHero(ID);
  178. }
  179. void CGameHandler::levelUpHero(int ID)
  180. {
  181. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID].get());
  182. if (hero->exp < VLC->heroh->reqExp(hero->level+1)) // no more level-ups
  183. return;
  184. //give prim skill
  185. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  186. int r = rand()%100, pom=0, x=0;
  187. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  188. for(;x<PRIMARY_SKILLS;x++)
  189. {
  190. pom += hero->type->heroClass->primChance[x].*g;
  191. if(r<pom)
  192. break;
  193. }
  194. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  195. SetPrimSkill sps;
  196. sps.id = ID;
  197. sps.which = x;
  198. sps.abs = false;
  199. sps.val = 1;
  200. sendAndApply(&sps);
  201. HeroLevelUp hlu;
  202. hlu.heroid = ID;
  203. hlu.primskill = x;
  204. hlu.level = hero->level+1;
  205. //picking sec. skills for choice
  206. std::set<int> basicAndAdv, expert, none;
  207. for(int i=0;i<SKILL_QUANTITY;i++)
  208. if (isAllowed(2,i))
  209. none.insert(i);
  210. for(unsigned i=0;i<hero->secSkills.size();i++)
  211. {
  212. if(hero->secSkills[i].second < 3)
  213. basicAndAdv.insert(hero->secSkills[i].first);
  214. else
  215. expert.insert(hero->secSkills[i].first);
  216. none.erase(hero->secSkills[i].first);
  217. }
  218. //first offered skill
  219. if(basicAndAdv.size())
  220. {
  221. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);//upgrade existing
  222. hlu.skills.push_back(s);
  223. basicAndAdv.erase(s);
  224. }
  225. else if(none.size() && hero->secSkills.size() < hero->type->heroClass->skillLimit)
  226. {
  227. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //give new skill
  228. none.erase(hlu.skills.back());
  229. }
  230. //second offered skill
  231. if(none.size() && hero->secSkills.size() < hero->type->heroClass->skillLimit) //hero have free skill slot
  232. {
  233. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  234. }
  235. else if(basicAndAdv.size())
  236. {
  237. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //upgrade existing
  238. }
  239. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  240. {
  241. boost::function<void(ui32)> callback = boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::levelUpHero,this,ID,_1)),_1));
  242. applyAndAsk(&hlu,hero->tempOwner,callback); //call levelUpHero when client responds
  243. }
  244. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  245. {
  246. sendAndApply(&hlu);
  247. levelUpHero(ID, hlu.skills.back());
  248. }
  249. else //apply and send info
  250. {
  251. sendAndApply(&hlu);
  252. levelUpHero(ID);
  253. }
  254. }
  255. void CGameHandler::changePrimSkill(int ID, int which, si64 val, bool abs)
  256. {
  257. SetPrimSkill sps;
  258. sps.id = ID;
  259. sps.which = which;
  260. sps.abs = abs;
  261. sps.val = val;
  262. sendAndApply(&sps);
  263. if(which==4) //only for exp - hero may level up
  264. {
  265. levelUpHero(ID);
  266. }
  267. }
  268. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  269. {
  270. SetSecSkill sss;
  271. sss.id = ID;
  272. sss.which = which;
  273. sss.val = val;
  274. sss.abs = abs;
  275. sendAndApply(&sss);
  276. if(which == 7) //Wisdom
  277. {
  278. const CGHeroInstance *h = getHero(ID);
  279. if(h && h->visitedTown)
  280. giveSpells(h->visitedTown, h);
  281. }
  282. }
  283. void CGameHandler::startBattle( const CArmedInstance *armies[2], int3 tile, const CGHeroInstance *heroes[2], bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town /*= NULL*/ )
  284. {
  285. battleEndCallback = new boost::function<void(BattleResult*)>(cb);
  286. bEndArmy1 = armies[0];
  287. bEndArmy2 = armies[1];
  288. {
  289. setupBattle(tile, armies, heroes, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  290. }
  291. runBattle();
  292. }
  293. void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  294. {
  295. BattleResultsApplied resultsApplied;
  296. resultsApplied.player1 = bEndArmy1->tempOwner;
  297. resultsApplied.player2 = bEndArmy2->tempOwner;
  298. //unblock engaged players
  299. if(bEndArmy1->tempOwner<PLAYER_LIMIT)
  300. states.setFlag(bEndArmy1->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  301. if(bEndArmy2 && bEndArmy2->tempOwner<PLAYER_LIMIT)
  302. states.setFlag(bEndArmy2->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  303. //end battle, remove all info, free memory
  304. giveExp(*battleResult.data);
  305. if (hero1)
  306. battleResult.data->exp[0] *= (100+hero1->getSecSkillLevel(CGHeroInstance::LEARNING)*5)/100.0f;//sholar skill
  307. if (hero2)
  308. battleResult.data->exp[1] *= (100+hero2->getSecSkillLevel(CGHeroInstance::LEARNING)*5)/100.0f;
  309. ui8 sides[2];
  310. sides[0] = gs->curB->side1;
  311. sides[1] = gs->curB->side2;
  312. ui8 loser = sides[!battleResult.data->winner];
  313. CasualtiesAfterBattle cab1(bEndArmy1, gs->curB), cab2(bEndArmy2, gs->curB); //calculate casualties before deleting battle
  314. sendAndApply(battleResult.data);
  315. cab1.takeFromArmy(this); cab2.takeFromArmy(this); //take casualties after battle is deleted
  316. //if one hero has lost we will erase him
  317. if(battleResult.data->winner!=0 && hero1)
  318. {
  319. RemoveObject ro(hero1->id);
  320. sendAndApply(&ro);
  321. }
  322. if(battleResult.data->winner!=1 && hero2)
  323. {
  324. RemoveObject ro(hero2->id);
  325. sendAndApply(&ro);
  326. }
  327. //give exp
  328. if(battleResult.data->exp[0] && hero1)
  329. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  330. if(battleResult.data->exp[1] && hero2)
  331. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  332. sendAndApply(&resultsApplied);
  333. if(battleEndCallback && *battleEndCallback) //TODO: object interaction after level dialog is handled
  334. {
  335. (*battleEndCallback)(battleResult.data);
  336. delete battleEndCallback;
  337. battleEndCallback = 0;
  338. }
  339. // Necromancy if applicable.
  340. const CGHeroInstance *winnerHero = battleResult.data->winner != 0 ? hero2 : hero1;
  341. const CGHeroInstance *loserHero = battleResult.data->winner != 0 ? hero1 : hero2;
  342. if (winnerHero)
  343. {
  344. CStackBasicDescriptor raisedStack = winnerHero->calculateNecromancy(*battleResult.data);
  345. // Give raised units to winner and show dialog, if any were raised.
  346. if (raisedStack.type)
  347. {
  348. TSlot slot = winnerHero->getSlotFor(raisedStack.type);
  349. if (slot != -1)
  350. {
  351. winnerHero->showNecromancyDialog(raisedStack);
  352. addToSlot(StackLocation(winnerHero, slot), raisedStack.type, raisedStack.count);
  353. }
  354. }
  355. }
  356. if(visitObjectAfterVictory && winnerHero == hero1)
  357. {
  358. visitObjectOnTile(*getTile(winnerHero->getPosition()), winnerHero);
  359. }
  360. visitObjectAfterVictory = false;
  361. winLoseHandle(1<<sides[0] | 1<<sides[1]); //handle victory/loss of engaged players
  362. int result = battleResult.get()->result;
  363. if(result == 1 || result == 2) //loser has escaped or surrendered
  364. {
  365. SetAvailableHeroes sah;
  366. sah.player = loser;
  367. sah.hid[0] = loserHero->subID;
  368. if(result == 1) //retreat
  369. {
  370. sah.army[0] = new CCreatureSet();
  371. sah.army[0]->addToSlot(0, VLC->creh->nameToID[loserHero->type->refTypeStack[0]],1);
  372. }
  373. if(const CGHeroInstance *another = getPlayerState(loser)->availableHeroes[1])
  374. sah.hid[1] = another->subID;
  375. else
  376. sah.hid[1] = -1;
  377. sendAndApply(&sah);
  378. }
  379. delete battleResult.data;
  380. }
  381. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, const CStack *def)
  382. {
  383. bsa.killedAmount = bsa.damageAmount / def->MaxHealth();
  384. unsigned damageFirst = bsa.damageAmount % def->MaxHealth();
  385. if( def->firstHPleft <= damageFirst )
  386. {
  387. bsa.killedAmount++;
  388. bsa.newHP = def->firstHPleft + def->MaxHealth() - damageFirst;
  389. }
  390. else
  391. {
  392. bsa.newHP = def->firstHPleft - damageFirst;
  393. }
  394. if(def->count <= bsa.killedAmount) //stack killed
  395. {
  396. bsa.newAmount = 0;
  397. bsa.flags |= 1;
  398. bsa.killedAmount = def->count; //we cannot kill more creatures than we have
  399. }
  400. else
  401. {
  402. bsa.newAmount = def->count - bsa.killedAmount;
  403. }
  404. }
  405. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance)
  406. {
  407. bat.bsa.clear();
  408. bat.stackAttacking = att->ID;
  409. bat.bsa.push_back(BattleStackAttacked());
  410. BattleStackAttacked *bsa = &bat.bsa.back();
  411. bsa->stackAttacked = def->ID;
  412. bsa->attackerID = att->ID;
  413. int attackerLuck = att->LuckVal();
  414. const CGHeroInstance * h0 = gs->curB->heroes[0],
  415. * h1 = gs->curB->heroes[1];
  416. bool noLuck = false;
  417. if(h0 && NBonus::hasOfType(h0, Bonus::BLOCK_LUCK) ||
  418. h1 && NBonus::hasOfType(h1, Bonus::BLOCK_LUCK))
  419. {
  420. noLuck = true;
  421. }
  422. if(!noLuck && attackerLuck > 0 && rand()%24 < attackerLuck) //TODO?: negative luck option?
  423. {
  424. bsa->damageAmount *= 2;
  425. bat.flags |= 4;
  426. }
  427. bsa->damageAmount = gs->curB->calculateDmg(att, def, gs->battleGetOwner(att->ID), gs->battleGetOwner(def->ID), bat.shot(), distance, bat.lucky());//counting dealt damage
  428. int dmg = bsa->damageAmount;
  429. prepareAttacked(*bsa, def);
  430. //life drain handling
  431. if (att->hasBonusOfType(Bonus::LIFE_DRAIN))
  432. {
  433. StacksHealedOrResurrected shi;
  434. shi.lifeDrain = true;
  435. shi.drainedFrom = def->ID;
  436. StacksHealedOrResurrected::HealInfo hi;
  437. hi.stackID = att->ID;
  438. hi.healedHP = std::min<int>(dmg, att->MaxHealth() - att->firstHPleft + att->MaxHealth() * (att->baseAmount - att->count) );
  439. hi.lowLevelResurrection = false;
  440. shi.healedStacks.push_back(hi);
  441. if (hi.healedHP > 0)
  442. {
  443. bsa->healedStacks.push_back(shi);
  444. }
  445. }
  446. else
  447. {
  448. }
  449. //fire shield handling
  450. if ( !bat.shot() && def->hasBonusOfType(Bonus::FIRE_SHIELD) && !bsa->killed() )
  451. {
  452. bat.bsa.push_back(BattleStackAttacked());
  453. BattleStackAttacked *bsa = &bat.bsa.back();
  454. bsa->stackAttacked = att->ID;
  455. bsa->attackerID = def->ID;
  456. bsa->flags |= 2;
  457. bsa->effect = 11;
  458. bsa->damageAmount = (dmg * def->valOfBonuses(Bonus::FIRE_SHIELD)) / 100;
  459. prepareAttacked(*bsa, att);
  460. }
  461. }
  462. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  463. {
  464. srand(time(NULL));
  465. CPack *pack = NULL;
  466. try
  467. {
  468. while(1)//server should never shut connection first //was: while(!end2)
  469. {
  470. {
  471. boost::unique_lock<boost::mutex> lock(*c.rmx);
  472. c >> pack; //get the package
  473. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  474. }
  475. int packType = typeList.getTypeID(pack); //get the id of type
  476. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  477. if(apply)
  478. {
  479. bool result = apply->applyOnGH(this,&c,pack);
  480. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  481. //send confirmation that we've applied the package
  482. if(pack->type != 6000) //WORKAROUND - not confirm query replies TODO: reconsider
  483. {
  484. PackageApplied applied;
  485. applied.result = result;
  486. applied.packType = packType;
  487. {
  488. boost::unique_lock<boost::mutex> lock(*c.wmx);
  489. c << &applied;
  490. }
  491. }
  492. }
  493. else
  494. {
  495. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  496. }
  497. delete pack;
  498. pack = NULL;
  499. }
  500. }
  501. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  502. {
  503. assert(!c.connected); //make sure that connection has been marked as broken
  504. tlog1 << e.what() << std::endl;
  505. end2 = true;
  506. }
  507. HANDLE_EXCEPTION(end2 = true);
  508. tlog1 << "Ended handling connection\n";
  509. }
  510. int CGameHandler::moveStack(int stack, int dest)
  511. {
  512. int ret = 0;
  513. CStack *curStack = gs->curB->getStack(stack),
  514. *stackAtEnd = gs->curB->getStackT(dest);
  515. assert(curStack);
  516. assert(dest < BFIELD_SIZE);
  517. //initing necessary tables
  518. bool accessibility[BFIELD_SIZE];
  519. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  520. for(int b=0; b<BFIELD_SIZE; ++b)
  521. {
  522. accessibility[b] = false;
  523. }
  524. for(int g=0; g<accessible.size(); ++g)
  525. {
  526. accessibility[accessible[g]] = true;
  527. }
  528. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  529. if(!stackAtEnd && curStack->doubleWide() && !accessibility[dest])
  530. {
  531. if(curStack->attackerOwned)
  532. {
  533. if(accessibility[dest+1])
  534. dest+=1;
  535. }
  536. else
  537. {
  538. if(accessibility[dest-1])
  539. dest-=1;
  540. }
  541. }
  542. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  543. return 0;
  544. bool accessibilityWithOccupyable[BFIELD_SIZE];
  545. std::vector<int> accOc = gs->curB->getAccessibility(curStack->ID, true);
  546. for(int b=0; b<BFIELD_SIZE; ++b)
  547. {
  548. accessibilityWithOccupyable[b] = false;
  549. }
  550. for(int g=0; g<accOc.size(); ++g)
  551. {
  552. accessibilityWithOccupyable[accOc[g]] = true;
  553. }
  554. //if(dists[dest] > curStack->creature->speed && !(stackAtEnd && dists[dest] == curStack->creature->speed+1)) //we can attack a stack if we can go to adjacent hex
  555. // return false;
  556. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibilityWithOccupyable, curStack->hasBonusOfType(Bonus::FLYING), curStack->doubleWide(), curStack->attackerOwned);
  557. ret = path.second;
  558. if(curStack->hasBonusOfType(Bonus::FLYING))
  559. {
  560. if(path.second <= curStack->Speed() && path.first.size() > 0)
  561. {
  562. //inform clients about move
  563. BattleStackMoved sm;
  564. sm.stack = curStack->ID;
  565. sm.tile = path.first[0];
  566. sm.distance = path.second;
  567. sm.ending = true;
  568. sm.teleporting = false;
  569. sendAndApply(&sm);
  570. }
  571. }
  572. else //for non-flying creatures
  573. {
  574. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  575. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  576. {
  577. //inform clients about move
  578. BattleStackMoved sm;
  579. sm.stack = curStack->ID;
  580. sm.tile = path.first[v];
  581. sm.distance = path.second;
  582. sm.ending = v==tilesToMove;
  583. sm.teleporting = false;
  584. sendAndApply(&sm);
  585. }
  586. }
  587. return ret;
  588. }
  589. CGameHandler::CGameHandler(void)
  590. {
  591. QID = 1;
  592. gs = NULL;
  593. IObjectInterface::cb = this;
  594. applier = new CApplier<CBaseForGHApply>;
  595. registerTypes3(*applier);
  596. visitObjectAfterVictory = false;
  597. }
  598. CGameHandler::~CGameHandler(void)
  599. {
  600. delete applier;
  601. applier = NULL;
  602. delete gs;
  603. }
  604. void CGameHandler::init(StartInfo *si, int Seed)
  605. {
  606. gs = new CGameState();
  607. tlog0 << "Gamestate created!" << std::endl;
  608. gs->init(si, 0, Seed);
  609. tlog0 << "Gamestate initialized!" << std::endl;
  610. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  611. states.addPlayer(i->first);
  612. }
  613. static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  614. {
  615. return *a < *b;
  616. }
  617. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false, bool clear = false)
  618. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  619. if (forced || town->creatures[CREATURES_PER_TOWN].second.empty())//we need to change creature
  620. {
  621. SetAvailableCreatures ssi;
  622. ssi.tid = town->id;
  623. ssi.creatures = town->creatures;
  624. ssi.creatures[CREATURES_PER_TOWN].second.clear();//remove old one
  625. const std::vector<ConstTransitivePtr<CGDwelling> > &dwellings = gs->getPlayer(town->tempOwner)->dwellings;
  626. if (dwellings.empty())//no dwellings - just remove
  627. {
  628. sendAndApply(&ssi);
  629. return;
  630. }
  631. ui32 dwellpos = rand()%dwellings.size();//take random dwelling
  632. ui32 creapos = rand()%dwellings[dwellpos]->creatures.size();//for multi-creature dwellings like Golem Factory
  633. ui32 creature = dwellings[dwellpos]->creatures[creapos].second[0];
  634. if (clear)
  635. ssi.creatures[CREATURES_PER_TOWN].first = std::max((ui32)1, (VLC->creh->creatures[creature]->growth)/2);
  636. else
  637. ssi.creatures[CREATURES_PER_TOWN].first = VLC->creh->creatures[creature]->growth;
  638. ssi.creatures[CREATURES_PER_TOWN].second.push_back(creature);
  639. sendAndApply(&ssi);
  640. }
  641. }
  642. void CGameHandler::newTurn()
  643. {
  644. tlog5 << "Turn " << gs->day+1 << std::endl;
  645. NewTurn n;
  646. n.creatureid = -1;
  647. n.day = gs->day + 1;
  648. n.resetBuilded = true;
  649. bool newmonth = false;
  650. std::map<ui8, si32> hadGold;//starting gold - for buildings like dwarven treasury
  651. srand(time(NULL));
  652. if (getDate(1) == 7 && getDate(0)>1) //new week (day numbers are confusing, as day was not yet switched)
  653. {
  654. int monsterid;
  655. int monthType = rand()%100;
  656. if(getDate(4) == 28) //new month
  657. {
  658. newmonth = true;
  659. if (monthType < 40) //double growth
  660. {
  661. n.specialWeek = NewTurn::DOUBLE_GROWTH;
  662. if (ALLCREATURESGETDOUBLEMONTHS)
  663. {
  664. std::pair<int,int> newMonster(54, VLC->creh->pickRandomMonster(boost::ref(rand)));
  665. n.creatureid = newMonster.second;
  666. }
  667. else
  668. {
  669. std::set<TCreature>::const_iterator it = VLC->creh->doubledCreatures.begin();
  670. std::advance (it, rand() % VLC->creh->doubledCreatures.size()); //picking random elelemnt of set is tiring
  671. n.creatureid = *it;
  672. }
  673. }
  674. else if (monthType < 90)
  675. n.specialWeek = NewTurn::NORMAL;
  676. else
  677. n.specialWeek = NewTurn::PLAGUE;
  678. }
  679. else //it's a week, but not full month
  680. {
  681. newmonth = false;
  682. if (monthType < 25)
  683. {
  684. n.specialWeek = NewTurn::BONUS_GROWTH; //+5
  685. std::pair<int,int> newMonster (54, VLC->creh->pickRandomMonster(boost::ref(rand)));
  686. monsterid = newMonster.second;
  687. }
  688. else
  689. n.specialWeek = NewTurn::NORMAL;
  690. }
  691. }
  692. else
  693. n.specialWeek = NewTurn::NO_ACTION; //don't remove bonuses
  694. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = gs->hpool.heroesPool;
  695. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  696. {
  697. if(i->first == 255)
  698. continue;
  699. else if(i->first >= PLAYER_LIMIT)
  700. assert(0); //illegal player number!
  701. std::pair<ui8,si32> playerGold(i->first,i->second.resources[6]);
  702. hadGold.insert(playerGold);
  703. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  704. {
  705. SetAvailableHeroes sah;
  706. sah.player = i->first;
  707. //pick heroes and their armies
  708. CHeroClass *banned = NULL;
  709. for (int j = 0; j < AVAILABLE_HEROES_PER_PLAYER; j++)
  710. {
  711. if(CGHeroInstance *h = gs->hpool.pickHeroFor(j == 0, i->first, getNativeTown(i->first), pool, banned)) //first hero - native if possible, second hero -> any other class
  712. {
  713. sah.hid[j] = h->subID;
  714. h->initArmy(sah.army[j] = new CCreatureSet());
  715. banned = h->type->heroClass;
  716. }
  717. else
  718. sah.hid[j] = -1;
  719. }
  720. sendAndApply(&sah);
  721. }
  722. n.res[i->first] = i->second.resources;
  723. // SetResources r;
  724. // r.player = i->first;
  725. // for(int j=0;j<RESOURCE_QUANTITY;j++)
  726. // r.res[j] = i->second.resources[j];
  727. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  728. {
  729. if(h->visitedTown)
  730. giveSpells(h->visitedTown, h);
  731. NewTurn::Hero hth;
  732. hth.id = h->id;
  733. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != TerrainTile::water);
  734. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  735. hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
  736. else
  737. hth.mana = std::max(si32(0), std::max(h->mana, std::min(h->mana + h->manaRegain(), h->manaLimit())) );
  738. n.heroes.insert(hth);
  739. if(gs->day) //not first day
  740. {
  741. n.res[i->first][6] += h->valOfBonuses(Selector::typeSybtype(Bonus::SECONDARY_SKILL, 13)); //estates
  742. for (int k = 0; k < RESOURCE_QUANTITY; k++)
  743. {
  744. n.res[i->first][k] += h->valOfBonuses(Bonus::GENERATE_RESOURCE, k);
  745. }
  746. }
  747. }
  748. //n.res.push_back(r);
  749. }
  750. // townID, creatureID, amount
  751. std::map<si32, std::map<si32, si32> > newCreas;//creatures that needs to be added by town events
  752. for(std::vector<ConstTransitivePtr<CGTownInstance> >::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  753. {
  754. ui8 player = (*j)->tempOwner;
  755. if(gs->getDate(1)==7) //first day of week
  756. {
  757. if ((*j)->subID == 5 && vstd::contains((*j)->builtBuildings, 22))
  758. setPortalDwelling(*j, true, (n.specialWeek == NewTurn::PLAGUE ? true : false)); //set creatures for Portal of Summoning
  759. if ((**j).subID == 1 && gs->getDate(0) && player < PLAYER_LIMIT && vstd::contains((**j).builtBuildings, 22))//dwarven treasury
  760. n.res[player][6] += hadGold[player]/10; //give 10% of starting gold
  761. }
  762. if(gs->day && player < PLAYER_LIMIT)//not the first day and town not neutral
  763. {
  764. ////SetResources r;
  765. //r.player = (**j).tempOwner;
  766. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  767. {
  768. if((**j).town->primaryRes == 127) //we'll give wood and ore
  769. {
  770. n.res[player][0] += 1;
  771. n.res[player][2] += 1;
  772. }
  773. else
  774. {
  775. n.res[player][(**j).town->primaryRes] += 1;
  776. }
  777. }
  778. n.res[player][6] += (**j).dailyIncome();
  779. }
  780. handleTownEvents(*j, n, newCreas);
  781. if (vstd::contains((**j).builtBuildings, 26))
  782. {
  783. switch ((**j).subID)
  784. {
  785. case 2: // Skyship, probably easier to handle same as Veil of darkness
  786. { //do it every new day after veils apply
  787. FoWChange fw;
  788. fw.mode = 1;
  789. fw.player = player;
  790. getAllTiles(fw.tiles, player, -1, 0);
  791. sendAndApply (&fw);
  792. }
  793. break;
  794. case 3: //Deity of Fire
  795. {
  796. if (getDate(0) > 1)
  797. {
  798. n.specialWeek = NewTurn::DEITYOFFIRE; //spawn familiars on new month
  799. n.creatureid = 42; //familiar
  800. }
  801. }
  802. break;
  803. }
  804. }
  805. if ((**j).hasBonusOfType (Bonus::DARKNESS))
  806. {
  807. (**j).hideTiles((**j).getOwner(), (**j).getBonus(Selector::type(Bonus::DARKNESS))->val);
  808. }
  809. //unhiding what shouldn't be hidden? //that's handled in netpacks client
  810. }
  811. if(getDate(2) == 1) //first week
  812. {
  813. SetAvailableArtifacts saa;
  814. saa.id = -1;
  815. pickAllowedArtsSet(saa.arts);
  816. sendAndApply(&saa);
  817. }
  818. sendAndApply(&n);
  819. if (gs->getDate(1)==1) //first day of week, day has already been changed
  820. {
  821. if (getDate(4) == 1 && (n.specialWeek == NewTurn::DOUBLE_GROWTH || n.specialWeek == NewTurn::DEITYOFFIRE))
  822. { //spawn wandering monsters
  823. std::vector<int3>::iterator tile;
  824. std::vector<int3> tiles;
  825. getFreeTiles(tiles);
  826. ui32 amount = (tiles.size()) >> 6;
  827. std::random_shuffle(tiles.begin(), tiles.end(), p_myrandom);
  828. for (int i = 0; i < amount; ++i)
  829. {
  830. tile = tiles.begin();
  831. NewObject no;
  832. no.ID = 54; //creature
  833. no.subID= n.creatureid;
  834. no.pos = *tile;
  835. sendAndApply(&no);
  836. tiles.erase(tile); //not use it again
  837. }
  838. }
  839. NewTurn n2; //just to handle creature growths after bonuses are applied
  840. n2.specialWeek = NewTurn::NO_ACTION;
  841. n2.day = gs->day;
  842. n2.resetBuilded = true;
  843. for(std::vector<ConstTransitivePtr<CGTownInstance> >::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  844. {
  845. SetAvailableCreatures sac;
  846. sac.tid = (**j).id;
  847. sac.creatures = (**j).creatures;
  848. for (int k=0; k < CREATURES_PER_TOWN; k++) //creature growths
  849. {
  850. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  851. {
  852. if (n.specialWeek == NewTurn::PLAGUE)
  853. sac.creatures[k].first = (**j).creatures[k].first / 2; //halve their number, no growth
  854. else
  855. {
  856. sac.creatures[k].first += (**j).creatureGrowth(k);
  857. if(gs->getDate(0) == 1) //first day of game: use only basic growths
  858. amin(sac.creatures[k].first, VLC->creh->creatures[(*j)->town->basicCreatures[k]]->growth);
  859. }
  860. }
  861. }
  862. //creatures from town events
  863. if (vstd::contains(newCreas, (**j).id))
  864. for(std::map<si32, si32>::iterator i=newCreas[(**j).id].begin() ; i!=newCreas[(**j).id].end(); i++)
  865. sac.creatures[i->first].first += i->second;
  866. n2.cres.push_back(sac);
  867. }
  868. if (gs->getDate(0) > 1)
  869. {
  870. InfoWindow iw; //new week info
  871. switch (n.specialWeek)
  872. {
  873. case NewTurn::DOUBLE_GROWTH:
  874. iw.text.addTxt(MetaString::ARRAY_TXT, 131);
  875. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  876. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  877. break;
  878. case NewTurn::PLAGUE:
  879. iw.text.addTxt(MetaString::ARRAY_TXT, 132);
  880. break;
  881. case NewTurn::BONUS_GROWTH:
  882. iw.text.addTxt(MetaString::ARRAY_TXT, 134);
  883. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  884. iw.text.addReplacement(MetaString::CRE_SING_NAMES, n.creatureid);
  885. break;
  886. case NewTurn::DEITYOFFIRE:
  887. iw.text.addTxt(MetaString::ARRAY_TXT, 135);
  888. iw.text.addReplacement(MetaString::CRE_SING_NAMES, 42); //%s imp
  889. iw.text.addReplacement(MetaString::CRE_SING_NAMES, 42); //%s imp
  890. iw.text.addReplacement2(15); //%+d 15
  891. iw.text.addReplacement(MetaString::CRE_SING_NAMES, 43); //%s familiar
  892. iw.text.addReplacement2(15); //%+d 15
  893. break;
  894. default:
  895. iw.text.addTxt(MetaString::ARRAY_TXT, (newmonth ? 130 : 133));
  896. iw.text.addReplacement(MetaString::ARRAY_TXT, 43 + rand()%15);
  897. }
  898. for (std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end(); i++)
  899. {
  900. iw.player = i->first;
  901. sendAndApply(&iw);
  902. }
  903. }
  904. sendAndApply(&n2);
  905. }
  906. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  907. handleTimeEvents();
  908. //call objects
  909. for(size_t i = 0; i<gs->map->objects.size(); i++)
  910. {
  911. if(gs->map->objects[i])
  912. gs->map->objects[i]->newTurn();
  913. }
  914. winLoseHandle(0xff);
  915. //warn players without town
  916. if(gs->day)
  917. {
  918. for (std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  919. {
  920. if(i->second.status || i->second.towns.size() || i->second.color >= PLAYER_LIMIT)
  921. continue;
  922. InfoWindow iw;
  923. iw.player = i->first;
  924. iw.components.push_back(Component(Component::FLAG,i->first,0,0));
  925. if(!i->second.daysWithoutCastle)
  926. {
  927. iw.text.addTxt(MetaString::GENERAL_TXT,6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  928. iw.text.addReplacement(MetaString::COLOR, i->first);
  929. }
  930. else if(i->second.daysWithoutCastle == 6)
  931. {
  932. iw.text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  933. iw.text.addReplacement(MetaString::COLOR, i->first);
  934. }
  935. else
  936. {
  937. iw.text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  938. iw.text.addReplacement(MetaString::COLOR, i->first);
  939. iw.text.addReplacement(7 - i->second.daysWithoutCastle);
  940. }
  941. sendAndApply(&iw);
  942. }
  943. }
  944. }
  945. void CGameHandler::run(bool resume)
  946. {
  947. using namespace boost::posix_time;
  948. BOOST_FOREACH(CConnection *cc, conns)
  949. {//init conn.
  950. ui32 quantity;
  951. ui8 pom;
  952. //ui32 seed;
  953. if(!resume)
  954. {
  955. ui32 sum = gs->map ? gs->map->checksum : 612;
  956. (*cc) << gs->initialOpts << sum << gs->seed; // gs->scenarioOps
  957. }
  958. (*cc) >> quantity; //how many players will be handled at that client
  959. tlog0 << "Connection " << cc->connectionID << " will handle " << quantity << " player: ";
  960. for(int i=0;i<quantity;i++)
  961. {
  962. (*cc) >> pom; //read player color
  963. tlog0 << (int)pom << " ";
  964. {
  965. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  966. connections[pom] = cc;
  967. }
  968. }
  969. tlog0 << std::endl;
  970. }
  971. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  972. {
  973. std::set<int> pom;
  974. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  975. if(j->second == *i)
  976. pom.insert(j->first);
  977. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  978. }
  979. if(gs->scenarioOps->mode == StartInfo::DUEL)
  980. {
  981. runBattle();
  982. return;
  983. }
  984. while (!end2)
  985. {
  986. if(!resume)
  987. newTurn();
  988. std::map<ui8,PlayerState>::iterator i;
  989. if(!resume)
  990. i = gs->players.begin();
  991. else
  992. i = gs->players.find(gs->currentPlayer);
  993. resume = false;
  994. for(; i != gs->players.end(); i++)
  995. {
  996. if(i->second.towns.size()==0 && i->second.heroes.size()==0
  997. || i->second.color<0
  998. || i->first>=PLAYER_LIMIT
  999. || i->second.status)
  1000. {
  1001. continue;
  1002. }
  1003. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1004. {
  1005. YourTurn yt;
  1006. yt.player = i->first;
  1007. sendAndApply(&yt);
  1008. }
  1009. //wait till turn is done
  1010. boost::unique_lock<boost::mutex> lock(states.mx);
  1011. while(states.players[i->first].makingTurn && !end2)
  1012. {
  1013. static time_duration p = milliseconds(200);
  1014. states.cv.timed_wait(lock,p);
  1015. }
  1016. }
  1017. }
  1018. while(conns.size() && (*conns.begin())->isOpen())
  1019. boost::this_thread::sleep(boost::posix_time::milliseconds(5)); //give time client to close socket
  1020. }
  1021. namespace CGH
  1022. {
  1023. using namespace std;
  1024. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  1025. {
  1026. for(int j=0; j<7; ++j)
  1027. {
  1028. std::vector<int> pom;
  1029. for(int g=0; g<j+1; ++g)
  1030. {
  1031. int hlp; input>>hlp;
  1032. pom.push_back(hlp);
  1033. }
  1034. dest.push_back(pom);
  1035. }
  1036. }
  1037. }
  1038. void CGameHandler::setupBattle( int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town )
  1039. {
  1040. battleResult.set(NULL);
  1041. //send info about battles
  1042. BattleStart bs;
  1043. bs.info = gs->setupBattle(tile, armies, heroes, creatureBank, town);
  1044. sendAndApply(&bs);
  1045. }
  1046. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1047. {
  1048. //checking winning condition
  1049. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1050. hasStack[0] = hasStack[1] = false;
  1051. for(int b = 0; b<stacks.size(); ++b)
  1052. {
  1053. if(stacks[b]->alive() && !stacks[b]->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1054. {
  1055. hasStack[1-stacks[b]->attackerOwned] = true;
  1056. }
  1057. }
  1058. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1059. {
  1060. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1061. br->result = 0;
  1062. br->winner = hasStack[1]; //fleeing side loses
  1063. gs->curB->calculateCasualties(br->casualties);
  1064. battleResult.set(br);
  1065. }
  1066. }
  1067. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1068. {
  1069. if(!vstd::contains(h->artifWorn,17))
  1070. return; //hero hasn't spellbok
  1071. ChangeSpells cs;
  1072. cs.hid = h->id;
  1073. cs.learn = true;
  1074. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(CGHeroInstance::WISDOM)+2);i++)
  1075. {
  1076. if (t->subID == 8 && vstd::contains(t->builtBuildings, 26)) //Aurora Borealis
  1077. {
  1078. std::vector<ui16> spells;
  1079. getAllowedSpells(spells, i);
  1080. for (int j = 0; j < spells.size(); ++j)
  1081. cs.spells.insert(spells[j]);
  1082. }
  1083. else
  1084. {
  1085. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1086. {
  1087. if(!vstd::contains(h->spells,t->spells[i][j]))
  1088. cs.spells.insert(t->spells[i][j]);
  1089. }
  1090. }
  1091. }
  1092. if(cs.spells.size())
  1093. sendAndApply(&cs);
  1094. }
  1095. void CGameHandler::setBlockVis(int objid, bool bv)
  1096. {
  1097. SetObjectProperty sop(objid,2,bv);
  1098. sendAndApply(&sop);
  1099. }
  1100. bool CGameHandler::removeObject( int objid )
  1101. {
  1102. if(!getObj(objid))
  1103. {
  1104. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1105. return false;
  1106. }
  1107. RemoveObject ro;
  1108. ro.id = objid;
  1109. sendAndApply(&ro);
  1110. winLoseHandle(255); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1111. return true;
  1112. }
  1113. void CGameHandler::setAmount(int objid, ui32 val)
  1114. {
  1115. SetObjectProperty sop(objid,3,val);
  1116. sendAndApply(&sop);
  1117. }
  1118. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1119. {
  1120. bool blockvis = false;
  1121. const CGHeroInstance *h = getHero(hid);
  1122. if(!h || asker != 255 && (instant || h->getOwner() != gs->currentPlayer) //not turn of that hero or player can't simply teleport hero (at least not with this function)
  1123. )
  1124. {
  1125. tlog1 << "Illegal call to move hero!\n";
  1126. return false;
  1127. }
  1128. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1129. int3 hmpos = dst + int3(-1,0,0);
  1130. if(!gs->map->isInTheMap(hmpos))
  1131. {
  1132. tlog1 << "Destination tile is outside the map!\n";
  1133. return false;
  1134. }
  1135. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1136. int cost = gs->getMovementCost(h, h->getPosition(false), CGHeroInstance::convertPosition(dst,false),h->movement);
  1137. int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1138. //result structure for start - movement failed, no move points used
  1139. TryMoveHero tmh;
  1140. tmh.id = hid;
  1141. tmh.start = h->pos;
  1142. tmh.end = dst;
  1143. tmh.result = TryMoveHero::FAILED;
  1144. tmh.movePoints = h->movement;
  1145. //check if destination tile is available
  1146. //it's a rock or blocked and not visitable tile
  1147. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1148. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable && !h->hasBonusOfType(Bonus::FLYING_MOVEMENT) ))
  1149. && complain("Cannot move hero, destination tile is blocked!")
  1150. || (!h->boat && !h->canWalkOnSea() && t.tertype == TerrainTile::water && (t.visitableObjects.size() != 1 || (t.visitableObjects.front()->ID != 8 && t.visitableObjects.front()->ID != HEROI_TYPE))) //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land)
  1151. && complain("Cannot move hero, destination tile is on water!")
  1152. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1153. && complain("Cannot disembark hero, tile is blocked!")
  1154. || (h->movement < cost && dst != h->pos && !instant)
  1155. && complain("Hero doesn't have any movement points left!")
  1156. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1157. && complain("Cannot move hero during the battle"))
  1158. {
  1159. //send info about movement failure
  1160. sendAndApply(&tmh);
  1161. return false;
  1162. }
  1163. //hero enters the boat
  1164. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1165. {
  1166. tmh.result = TryMoveHero::EMBARK;
  1167. tmh.movePoints = 0; //embarking takes all move points
  1168. //TODO: check for bonus that removes that penalty
  1169. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1170. sendAndApply(&tmh);
  1171. return true;
  1172. }
  1173. //hero leaves the boat
  1174. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1175. {
  1176. tmh.result = TryMoveHero::DISEMBARK;
  1177. tmh.movePoints = 0; //disembarking takes all move points
  1178. //TODO: check for bonus that removes that penalty
  1179. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1180. sendAndApply(&tmh);
  1181. tryAttackingGuard(guardPos, h);
  1182. return true;
  1183. }
  1184. //checks for standard movement
  1185. if(!instant)
  1186. {
  1187. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighboring!")
  1188. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1189. {
  1190. sendAndApply(&tmh);
  1191. return false;
  1192. }
  1193. //check if there is blocking visitable object
  1194. blockvis = false;
  1195. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1196. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1197. {
  1198. if(obj != h && obj->blockVisit && !(obj->getPassableness() & 1<<h->tempOwner))
  1199. {
  1200. blockvis = true;
  1201. break;
  1202. }
  1203. }
  1204. //we start moving
  1205. if(blockvis)//interaction with blocking object (like resources)
  1206. {
  1207. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1208. sendAndApply(&tmh);
  1209. //failed to move to that tile but we visit object
  1210. if(t.visitableObjects.size())
  1211. objectVisited(t.visitableObjects.back(), h);
  1212. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1213. // {
  1214. // if (obj->blockVisit)
  1215. // {
  1216. // objectVisited(obj, h);
  1217. // }
  1218. // }
  1219. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1220. return true;
  1221. }
  1222. else //normal move
  1223. {
  1224. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1225. {
  1226. obj->onHeroLeave(h);
  1227. }
  1228. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1229. tmh.result = TryMoveHero::SUCCESS;
  1230. tmh.attackedFrom = guardPos;
  1231. sendAndApply(&tmh);
  1232. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1233. // If a creature guards the tile, block visit.
  1234. const bool fightingGuard = tryAttackingGuard(guardPos, h);
  1235. if(!fightingGuard && t.visitableObjects.size()) //call objects if they are visited
  1236. {
  1237. visitObjectOnTile(t, h);
  1238. }
  1239. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1240. // {
  1241. // objectVisited(obj, h);
  1242. // }
  1243. tlog5 << "Movement end!\n";
  1244. return true;
  1245. }
  1246. }
  1247. else //instant move - teleportation
  1248. {
  1249. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1250. {
  1251. if(obj->ID==HEROI_TYPE)
  1252. {
  1253. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1254. if( gameState()->getPlayerRelations(dh->tempOwner, h->tempOwner))
  1255. {
  1256. heroExchange(h->id, dh->id);
  1257. return true;
  1258. }
  1259. startBattleI(h, dh);
  1260. return true;
  1261. }
  1262. }
  1263. tmh.result = TryMoveHero::TELEPORTATION;
  1264. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1265. sendAndApply(&tmh);
  1266. return true;
  1267. }
  1268. }
  1269. bool CGameHandler::teleportHero(si32 hid, si32 dstid, ui8 source, ui8 asker/* = 255*/)
  1270. {
  1271. const CGHeroInstance *h = getHero(hid);
  1272. const CGTownInstance *t = getTown(dstid);
  1273. if ( !h || !t || h->getOwner() != gs->currentPlayer )
  1274. tlog1<<"Invalid call to teleportHero!";
  1275. const CGTownInstance *from = h->visitedTown;
  1276. if((h->getOwner() != t->getOwner())
  1277. && complain("Cannot teleport hero to another player")
  1278. || (!from || from->subID!=3 || !vstd::contains(from->builtBuildings, 22))
  1279. && complain("Hero must be in town with Castle gate for teleporting")
  1280. || (t->subID!=3 || !vstd::contains(t->builtBuildings, 22))
  1281. && complain("Cannot teleport hero to town without Castle gate in it"))
  1282. return false;
  1283. int3 pos = t->visitablePos();
  1284. pos += h->getVisitableOffset();
  1285. stopHeroVisitCastle(from->id, hid);
  1286. moveHero(hid,pos,1);
  1287. heroVisitCastle(dstid, hid);
  1288. return true;
  1289. }
  1290. void CGameHandler::setOwner(int objid, ui8 owner)
  1291. {
  1292. ui8 oldOwner = getOwner(objid);
  1293. SetObjectProperty sop(objid,1,owner);
  1294. sendAndApply(&sop);
  1295. winLoseHandle(1<<owner | 1<<oldOwner);
  1296. if(owner < PLAYER_LIMIT && getTown(objid)) //town captured
  1297. {
  1298. const CGTownInstance * town = getTown(objid);
  1299. if (town->subID == 5 && vstd::contains(town->builtBuildings, 22))
  1300. setPortalDwelling(town, true, false);
  1301. if (!gs->getPlayer(owner)->towns.size())//player lost last town
  1302. {
  1303. InfoWindow iw;
  1304. iw.player = oldOwner;
  1305. iw.text.addTxt(MetaString::GENERAL_TXT, 6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1306. sendAndApply(&iw);
  1307. }
  1308. }
  1309. const CGObjectInstance * obj = getObj(objid);
  1310. const PlayerState * p = gs->getPlayer(owner);
  1311. if((obj->ID == 17 || obj->ID == 20 ) && p && p->dwellings.size()==1)//first dwelling captured
  1312. BOOST_FOREACH(const CGTownInstance *t, gs->getPlayer(owner)->towns)
  1313. if (t->subID == 5 && vstd::contains(t->builtBuildings, 22))
  1314. setPortalDwelling(t);//set initial creatures for all portals of summoning
  1315. }
  1316. void CGameHandler::setHoverName(int objid, MetaString* name)
  1317. {
  1318. SetHoverName shn(objid, *name);
  1319. sendAndApply(&shn);
  1320. }
  1321. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1322. {
  1323. sendToAllClients(iw);
  1324. }
  1325. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1326. {
  1327. ask(iw,iw->player,callback);
  1328. }
  1329. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1330. {
  1331. //TODO
  1332. //gsm.lock();
  1333. //int query = QID++;
  1334. //states.addQuery(player,query);
  1335. //sendToAllClients(iw);
  1336. //gsm.unlock();
  1337. //ui32 ret = getQueryResult(iw->player, query);
  1338. //gsm.lock();
  1339. //states.removeQuery(player, query);
  1340. //gsm.unlock();
  1341. return 0;
  1342. }
  1343. int CGameHandler::getCurrentPlayer()
  1344. {
  1345. return gs->currentPlayer;
  1346. }
  1347. void CGameHandler::giveResource(int player, int which, int val)
  1348. {
  1349. if(!val) return; //don't waste time on empty call
  1350. SetResource sr;
  1351. sr.player = player;
  1352. sr.resid = which;
  1353. sr.val = gs->players.find(player)->second.resources[which]+val;
  1354. sendAndApply(&sr);
  1355. }
  1356. void CGameHandler::giveCreatures(const CArmedInstance *obj, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove)
  1357. {
  1358. boost::function<void()> removeOrNot = 0;
  1359. if(remove)
  1360. removeOrNot = boost::bind(&CGameHandler::removeObject, this, obj->id);
  1361. COMPLAIN_RET_IF(!creatures.stacksCount(), "Strange, giveCreatures called without args!");
  1362. COMPLAIN_RET_IF(obj->stacksCount(), "Cannot give creatures from not-cleared object!");
  1363. COMPLAIN_RET_IF(creatures.stacksCount() > ARMY_SIZE, "Too many stacks to give!");
  1364. //first we move creatures to give to make them army of object-source
  1365. for(int i = 0; creatures.stacksCount(); i++)
  1366. {
  1367. TSlots::const_iterator stack = creatures.Slots().begin();
  1368. addToSlot(StackLocation(obj, i), stack->second->type, stack->second->count);
  1369. }
  1370. tryJoiningArmy(obj, h, remove, false);
  1371. }
  1372. void CGameHandler::takeCreatures(int objid, std::vector<CStackBasicDescriptor> creatures)
  1373. {
  1374. if (creatures.size() <= 0)
  1375. return;
  1376. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  1377. BOOST_FOREACH(CStackBasicDescriptor &sbd, creatures)
  1378. {
  1379. TQuantity collected = 0;
  1380. while(collected < sbd.count)
  1381. {
  1382. TSlots::const_iterator i = obj->Slots().begin();
  1383. for(; i != obj->Slots().end(); i++)
  1384. {
  1385. if(i->second->type == sbd.type)
  1386. {
  1387. TQuantity take = std::min(sbd.count - collected, i->second->count); //collect as much creatures as we can
  1388. changeStackCount(StackLocation(obj, i->first), take, false);
  1389. collected += take;
  1390. break;
  1391. }
  1392. }
  1393. if(i == obj->Slots().end()) //we went through the whole loop and haven't found appropriate creatures
  1394. {
  1395. complain("Unexpected failure during taking creatures!");
  1396. return;
  1397. }
  1398. }
  1399. }
  1400. }
  1401. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1402. {
  1403. sendToAllClients(comp);
  1404. }
  1405. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1406. {
  1407. HeroVisitCastle vc;
  1408. vc.hid = heroID;
  1409. vc.tid = obj;
  1410. vc.flags |= 1;
  1411. sendAndApply(&vc);
  1412. const CGHeroInstance *h = getHero(heroID);
  1413. vistiCastleObjects (getTown(obj), h);
  1414. giveSpells (getTown(obj), getHero(heroID));
  1415. if(gs->map->victoryCondition.condition == transportItem)
  1416. checkLossVictory(h->tempOwner); //transported artifact?
  1417. }
  1418. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1419. {
  1420. std::vector<CGTownBuilding*>::const_iterator i;
  1421. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1422. (*i)->onHeroVisit (h);
  1423. }
  1424. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1425. {
  1426. HeroVisitCastle vc;
  1427. vc.hid = heroID;
  1428. vc.tid = obj;
  1429. sendAndApply(&vc);
  1430. }
  1431. // bool CGameHandler::removeArtifact(const CArtifact* art, int hid)
  1432. // {
  1433. // const CGHeroInstance* h = getHero(hid);
  1434. //
  1435. // SetHeroArtifacts sha;
  1436. // sha.hid = hid;
  1437. // sha.artifacts = h->artifacts;
  1438. // sha.artifWorn = h->artifWorn;
  1439. //
  1440. // std::vector<const CArtifact*>::iterator it;
  1441. // if ((it = std::find(sha.artifacts.begin(), sha.artifacts.end(), art)) != sha.artifacts.end()) //it is in backpack
  1442. // sha.artifacts.erase(it);
  1443. // else //worn
  1444. // {
  1445. // std::map<ui16, const CArtifact*>::iterator itr;
  1446. // for (itr = sha.artifWorn.begin(); itr != sha.artifWorn.end(); ++itr)
  1447. // {
  1448. // if (itr->second == art)
  1449. // {
  1450. // VLC->arth->unequipArtifact(sha.artifWorn, itr->first);
  1451. // break;
  1452. // }
  1453. // }
  1454. //
  1455. // if(itr == sha.artifWorn.end())
  1456. // {
  1457. // tlog2 << "Cannot find artifact to remove!\n";
  1458. // return false;
  1459. // }
  1460. // }
  1461. // sendAndApply(&sha);
  1462. // return true;
  1463. // }
  1464. void CGameHandler::removeArtifact(const ArtifactLocation &al)
  1465. {
  1466. assert(al.getArt());
  1467. EraseArtifact ea;
  1468. ea.al = al;
  1469. sendAndApply(&ea);
  1470. }
  1471. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town) //use hero=NULL for no hero
  1472. {
  1473. engageIntoBattle(army1->tempOwner);
  1474. engageIntoBattle(army2->tempOwner);
  1475. //block engaged players
  1476. if(army2->tempOwner < PLAYER_LIMIT)
  1477. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1478. static const CArmedInstance *armies[2];
  1479. armies[0] = army1;
  1480. armies[1] = army2;
  1481. static const CGHeroInstance*heroes[2];
  1482. heroes[0] = hero1;
  1483. heroes[1] = hero2;
  1484. boost::thread(boost::bind(&CGameHandler::startBattle, this, armies, tile, heroes, creatureBank, cb, town));
  1485. }
  1486. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  1487. {
  1488. startBattleI(army1, army2, tile,
  1489. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  1490. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  1491. creatureBank, cb);
  1492. }
  1493. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  1494. {
  1495. startBattleI(army1, army2, army2->visitablePos(), cb, creatureBank);
  1496. }
  1497. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1498. //{
  1499. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1500. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  1501. // //battle(&h->army,army,tile,h,NULL);
  1502. //}
  1503. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1504. {
  1505. ChangeSpells cs;
  1506. cs.hid = hid;
  1507. cs.spells = spells;
  1508. cs.learn = give;
  1509. sendAndApply(&cs);
  1510. }
  1511. int CGameHandler::getSelectedHero()
  1512. {
  1513. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1514. }
  1515. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  1516. {
  1517. SetObjectProperty sob;
  1518. sob.id = objid;
  1519. sob.what = prop;
  1520. sob.val = val;
  1521. sendAndApply(&sob);
  1522. }
  1523. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1524. {
  1525. SystemMessage sm;
  1526. sm.text = message;
  1527. c << &sm;
  1528. }
  1529. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1530. {
  1531. sendAndApply(bonus);
  1532. }
  1533. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1534. {
  1535. sendAndApply(smp);
  1536. }
  1537. void CGameHandler::setManaPoints( int hid, int val )
  1538. {
  1539. SetMana sm;
  1540. sm.hid = hid;
  1541. sm.val = val;
  1542. sendAndApply(&sm);
  1543. }
  1544. void CGameHandler::giveHero( int id, int player )
  1545. {
  1546. GiveHero gh;
  1547. gh.id = id;
  1548. gh.player = player;
  1549. sendAndApply(&gh);
  1550. }
  1551. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1552. {
  1553. ChangeObjPos cop;
  1554. cop.objid = objid;
  1555. cop.nPos = newPos;
  1556. cop.flags = flags;
  1557. sendAndApply(&cop);
  1558. }
  1559. void CGameHandler::useScholarSkill(si32 fromHero, si32 toHero)
  1560. {
  1561. const CGHeroInstance * h1 = getHero(fromHero);
  1562. const CGHeroInstance * h2 = getHero(toHero);
  1563. if ( h1->getSecSkillLevel(CGHeroInstance::SCHOLAR) < h2->getSecSkillLevel(CGHeroInstance::SCHOLAR) )
  1564. {
  1565. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  1566. std::swap(fromHero, toHero);
  1567. }
  1568. int ScholarLevel = h1->getSecSkillLevel(CGHeroInstance::SCHOLAR);//heroes can trade up to this level
  1569. if (!ScholarLevel || !vstd::contains(h1->artifWorn,17) || !vstd::contains(h2->artifWorn,17) )
  1570. return;//no scholar skill or no spellbook
  1571. int h1Lvl = std::min(ScholarLevel+1, h1->getSecSkillLevel(CGHeroInstance::WISDOM)+2),
  1572. h2Lvl = std::min(ScholarLevel+1, h2->getSecSkillLevel(CGHeroInstance::WISDOM)+2);//heroes can receive this levels
  1573. ChangeSpells cs1;
  1574. cs1.learn = true;
  1575. cs1.hid = toHero;//giving spells to first hero
  1576. for(std::set<ui32>::const_iterator it=h1->spells.begin(); it!=h1->spells.end();it++)
  1577. if ( h2Lvl >= VLC->spellh->spells[*it]->level && !vstd::contains(h2->spells, *it))//hero can learn it and don't have it yet
  1578. cs1.spells.insert(*it);//spell to learn
  1579. ChangeSpells cs2;
  1580. cs2.learn = true;
  1581. cs2.hid = fromHero;
  1582. for(std::set<ui32>::const_iterator it=h2->spells.begin(); it!=h2->spells.end();it++)
  1583. if ( h1Lvl >= VLC->spellh->spells[*it]->level && !vstd::contains(h1->spells, *it))
  1584. cs2.spells.insert(*it);
  1585. if (cs1.spells.size() || cs2.spells.size())//create a message
  1586. {
  1587. InfoWindow iw;
  1588. iw.player = h1->tempOwner;
  1589. iw.components.push_back(Component(Component::SEC_SKILL, 18, ScholarLevel, 0));
  1590. iw.text.addTxt(MetaString::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  1591. iw.text.addReplacement(h1->name);
  1592. if (cs2.spells.size())//if found new spell - apply
  1593. {
  1594. iw.text.addTxt(MetaString::GENERAL_TXT, 140);//learns
  1595. int size = cs2.spells.size();
  1596. for(std::set<ui32>::const_iterator it=cs2.spells.begin(); it!=cs2.spells.end();it++)
  1597. {
  1598. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  1599. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  1600. switch (size--)
  1601. {
  1602. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  1603. case 1: break;
  1604. default: iw.text << ", ";
  1605. }
  1606. }
  1607. iw.text.addTxt(MetaString::GENERAL_TXT, 142);//from %s
  1608. iw.text.addReplacement(h2->name);
  1609. sendAndApply(&cs2);
  1610. }
  1611. if (cs1.spells.size() && cs2.spells.size() )
  1612. {
  1613. iw.text.addTxt(MetaString::GENERAL_TXT, 141);//and
  1614. }
  1615. if (cs1.spells.size())
  1616. {
  1617. iw.text.addTxt(MetaString::GENERAL_TXT, 147);//teaches
  1618. int size = cs1.spells.size();
  1619. for(std::set<ui32>::const_iterator it=cs1.spells.begin(); it!=cs1.spells.end();it++)
  1620. {
  1621. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  1622. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  1623. switch (size--)
  1624. {
  1625. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  1626. case 1: break;
  1627. default: iw.text << ", ";
  1628. } }
  1629. iw.text.addTxt(MetaString::GENERAL_TXT, 148);//from %s
  1630. iw.text.addReplacement(h2->name);
  1631. sendAndApply(&cs1);
  1632. }
  1633. sendAndApply(&iw);
  1634. }
  1635. }
  1636. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  1637. {
  1638. ui8 player1 = getHero(hero1)->tempOwner;
  1639. ui8 player2 = getHero(hero2)->tempOwner;
  1640. if( gameState()->getPlayerRelations( player1, player2))
  1641. {
  1642. OpenWindow hex;
  1643. hex.window = OpenWindow::EXCHANGE_WINDOW;
  1644. hex.id1 = hero1;
  1645. hex.id2 = hero2;
  1646. sendAndApply(&hex);
  1647. useScholarSkill(hero1,hero2);
  1648. }
  1649. }
  1650. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1651. {
  1652. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1653. sel->id = QID;
  1654. callbacks[QID] = callback;
  1655. states.addQuery(player,QID);
  1656. QID++;
  1657. sendAndApply(sel);
  1658. }
  1659. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1660. {
  1661. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1662. sel->id = QID;
  1663. callbacks[QID] = callback;
  1664. states.addQuery(player,QID);
  1665. sendToAllClients(sel);
  1666. QID++;
  1667. }
  1668. void CGameHandler::sendToAllClients( CPackForClient * info )
  1669. {
  1670. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1671. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1672. {
  1673. (*i)->wmx->lock();
  1674. **i << info;
  1675. (*i)->wmx->unlock();
  1676. }
  1677. }
  1678. void CGameHandler::sendAndApply( CPackForClient * info )
  1679. {
  1680. //TODO? mutex
  1681. sendToAllClients(info);
  1682. gs->apply(info);
  1683. }
  1684. void CGameHandler::sendAndApply(CGarrisonOperationPack * info)
  1685. {
  1686. sendAndApply((CPackForClient*)info);
  1687. if(gs->map->victoryCondition.condition == gatherTroop)
  1688. winLoseHandle();
  1689. }
  1690. // void CGameHandler::sendAndApply( SetGarrisons * info )
  1691. // {
  1692. // sendAndApply((CPackForClient*)info);
  1693. // if(gs->map->victoryCondition.condition == gatherTroop)
  1694. // for(std::map<ui32,CCreatureSet>::const_iterator i = info->garrs.begin(); i != info->garrs.end(); i++)
  1695. // checkLossVictory(getObj(i->first)->tempOwner);
  1696. // }
  1697. void CGameHandler::sendAndApply( SetResource * info )
  1698. {
  1699. sendAndApply((CPackForClient*)info);
  1700. if(gs->map->victoryCondition.condition == gatherResource)
  1701. checkLossVictory(info->player);
  1702. }
  1703. void CGameHandler::sendAndApply( SetResources * info )
  1704. {
  1705. sendAndApply((CPackForClient*)info);
  1706. if(gs->map->victoryCondition.condition == gatherResource)
  1707. checkLossVictory(info->player);
  1708. }
  1709. void CGameHandler::sendAndApply( NewStructures * info )
  1710. {
  1711. sendAndApply((CPackForClient*)info);
  1712. if(gs->map->victoryCondition.condition == buildCity)
  1713. checkLossVictory(getTown(info->tid)->tempOwner);
  1714. }
  1715. void CGameHandler::save( const std::string &fname )
  1716. {
  1717. {
  1718. tlog0 << "Ordering clients to serialize...\n";
  1719. SaveGame sg(fname);
  1720. sendToAllClients(&sg);
  1721. }
  1722. {
  1723. tlog0 << "Serializing game info...\n";
  1724. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vlgm1");
  1725. char hlp[8] = "VCMISVG";
  1726. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps << *VLC << gs;
  1727. }
  1728. {
  1729. tlog0 << "Serializing server info...\n";
  1730. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vsgm1");
  1731. save << *this;
  1732. }
  1733. tlog0 << "Game has been successfully saved!\n";
  1734. }
  1735. void CGameHandler::close()
  1736. {
  1737. tlog0 << "We have been requested to close.\n";
  1738. //BOOST_FOREACH(CConnection *cc, conns)
  1739. // if(cc && cc->socket && cc->socket->is_open())
  1740. // cc->socket->close();
  1741. //exit(0);
  1742. }
  1743. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val, ui8 player )
  1744. {
  1745. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1].get()),
  1746. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2].get());
  1747. CCreatureSet &S1 = *s1, &S2 = *s2;
  1748. StackLocation sl1(s1, p1), sl2(s2, p2);
  1749. if(!isAllowedExchange(id1,id2))
  1750. {
  1751. complain("Cannot exchange stacks between these two objects!\n");
  1752. return false;
  1753. }
  1754. if(what==1) //swap
  1755. {
  1756. if ( ((s1->tempOwner != player && s1->tempOwner != 254) && S1.slots[p1]->count) //why 254??
  1757. || ((s2->tempOwner != player && s2->tempOwner != 254) && S2.slots[p2]->count))
  1758. {
  1759. complain("Can't take troops from another player!");
  1760. return false;
  1761. }
  1762. swapStacks(sl1, sl2);
  1763. }
  1764. else if(what==2)//merge
  1765. {
  1766. if (( S1.slots[p1]->type != S2.slots[p2]->type && complain("Cannot merge different creatures stacks!"))
  1767. || ((s1->tempOwner != player && s1->tempOwner != 254) && S2.slots[p2]->count) && complain("Can't take troops from another player!"))
  1768. return false;
  1769. moveStack(sl1, sl2);
  1770. }
  1771. else if(what==3) //split
  1772. {
  1773. if ( (s1->tempOwner != player && S1.slots[p1]->count < s1->getArmy().getStackCount(p1) )
  1774. || (s2->tempOwner != player && S2.slots[p2]->count < s2->getArmy().getStackCount(p2) ) )
  1775. {
  1776. complain("Can't move troops of another player!");
  1777. return false;
  1778. }
  1779. //general conditions checking
  1780. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1781. || (val<1 && complain("no creatures to split")) )
  1782. {
  1783. return false;
  1784. }
  1785. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1786. {
  1787. int total = S1.slots[p1]->count + S2.slots[p2]->count;
  1788. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1789. || (S2.slots[p2]->type != S1.slots[p1]->type && complain("Cannot rebalance different creatures stacks!"))
  1790. )
  1791. {
  1792. return false;
  1793. }
  1794. moveStack(sl1, sl2, val - S2.slots[p2]->count);
  1795. //S2.slots[p2]->count = val;
  1796. //S1.slots[p1]->count = total - val;
  1797. }
  1798. else //split one stack to the two
  1799. {
  1800. if(S1.slots[p1]->count < val)//not enough creatures
  1801. {
  1802. complain("Cannot split that stack, not enough creatures!");
  1803. return false;
  1804. }
  1805. moveStack(sl1, sl2, val);
  1806. }
  1807. }
  1808. return true;
  1809. }
  1810. int CGameHandler::getPlayerAt( CConnection *c ) const
  1811. {
  1812. std::set<int> all;
  1813. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1814. if(i->second == c)
  1815. all.insert(i->first);
  1816. switch(all.size())
  1817. {
  1818. case 0:
  1819. return 255;
  1820. case 1:
  1821. return *all.begin();
  1822. default:
  1823. {
  1824. //if we have more than one player at this connection, try to pick active one
  1825. if(vstd::contains(all,int(gs->currentPlayer)))
  1826. return gs->currentPlayer;
  1827. else
  1828. return 253; //cannot say which player is it
  1829. }
  1830. }
  1831. }
  1832. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  1833. {
  1834. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id].get());
  1835. if(!vstd::contains(s1->slots,pos))
  1836. {
  1837. complain("Illegal call to disbandCreature - no such stack in army!");
  1838. return false;
  1839. }
  1840. eraseStack(StackLocation(s1, pos));
  1841. return true;
  1842. }
  1843. bool CGameHandler::buildStructure( si32 tid, si32 bid, bool force /*=false*/ )
  1844. {
  1845. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid].get());
  1846. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  1847. if( !force && gs->canBuildStructure(t,bid) != 7)
  1848. {
  1849. complain("Cannot build that building!");
  1850. return false;
  1851. }
  1852. if( !force && bid == 26) //grail
  1853. {
  1854. if(!t->visitingHero || !t->visitingHero->hasArt(2))
  1855. {
  1856. complain("Cannot build grail - hero doesn't have it");
  1857. return false;
  1858. }
  1859. //remove grail
  1860. removeArtifact(ArtifactLocation(t->visitingHero, t->visitingHero->getArtPos(2, false)));
  1861. }
  1862. NewStructures ns;
  1863. ns.tid = tid;
  1864. if ( (bid == 18) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[0]+37))) )
  1865. ns.bid.insert(19);//we have upgr. dwelling, upgr. horde will be builded as well
  1866. else if ( (bid == 24) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[1]+37))) )
  1867. ns.bid.insert(25);
  1868. else if(bid>36) //upg dwelling
  1869. {
  1870. if ( (bid-37 == t->town->hordeLvl[0]) && (vstd::contains(t->builtBuildings,18)) )
  1871. ns.bid.insert(19);//we have horde, will be upgraded as well as dwelling
  1872. if ( (bid-37 == t->town->hordeLvl[1]) && (vstd::contains(t->builtBuildings,24)) )
  1873. ns.bid.insert(25);
  1874. SetAvailableCreatures ssi;
  1875. ssi.tid = tid;
  1876. ssi.creatures = t->creatures;
  1877. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  1878. sendAndApply(&ssi);
  1879. }
  1880. else if(bid >= 30) //bas. dwelling
  1881. {
  1882. int crid = t->town->basicCreatures[bid-30];
  1883. SetAvailableCreatures ssi;
  1884. ssi.tid = tid;
  1885. ssi.creatures = t->creatures;
  1886. ssi.creatures[bid-30].first = VLC->creh->creatures[crid]->growth;
  1887. ssi.creatures[bid-30].second.push_back(crid);
  1888. sendAndApply(&ssi);
  1889. }
  1890. else if(bid == 11)
  1891. ns.bid.insert(27);
  1892. else if(bid == 12)
  1893. ns.bid.insert(28);
  1894. else if(bid == 13)
  1895. ns.bid.insert(29);
  1896. else if (t->subID == 4 && bid == 17) //veil of darkness
  1897. {
  1898. GiveBonus gb(GiveBonus::TOWN);
  1899. gb.bonus.type = Bonus::DARKNESS;
  1900. gb.bonus.val = 20;
  1901. gb.id = t->id;
  1902. gb.bonus.duration = Bonus::PERMANENT;
  1903. gb.bonus.source = Bonus::TOWN_STRUCTURE;
  1904. gb.bonus.id = 17;
  1905. sendAndApply(&gb);
  1906. }
  1907. else if ( t->subID == 5 && bid == 22 )
  1908. {
  1909. setPortalDwelling(t);
  1910. }
  1911. ns.bid.insert(bid);
  1912. ns.builded = force?t->builded:(t->builded+1);
  1913. sendAndApply(&ns);
  1914. //reveal ground for lookout tower
  1915. FoWChange fw;
  1916. fw.player = t->tempOwner;
  1917. fw.mode = 1;
  1918. getTilesInRange(fw.tiles,t->pos,t->getSightRadious(),t->tempOwner,1);
  1919. sendAndApply(&fw);
  1920. if (!force)
  1921. {
  1922. SetResources sr;
  1923. sr.player = t->tempOwner;
  1924. sr.res = gs->getPlayer(t->tempOwner)->resources;
  1925. for(int i=0;i<b->resources.size();i++)
  1926. sr.res[i]-=b->resources[i];
  1927. sendAndApply(&sr);
  1928. }
  1929. if(bid<5) //it's mage guild
  1930. {
  1931. if(t->visitingHero)
  1932. giveSpells(t,t->visitingHero);
  1933. if(t->garrisonHero)
  1934. giveSpells(t,t->garrisonHero);
  1935. }
  1936. if(t->visitingHero)
  1937. vistiCastleObjects (t, t->visitingHero);
  1938. if(t->garrisonHero)
  1939. vistiCastleObjects (t, t->garrisonHero);
  1940. checkLossVictory(t->tempOwner);
  1941. return true;
  1942. }
  1943. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  1944. {
  1945. ///incomplete, simply erases target building
  1946. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid].get());
  1947. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  1948. return false;
  1949. RazeStructures rs;
  1950. rs.tid = tid;
  1951. rs.bid.insert(bid);
  1952. rs.destroyed = t->destroyed + 1;
  1953. sendAndApply(&rs);
  1954. //TODO: Remove dwellers
  1955. if (t->subID == 4 && bid == 17) //Veil of Darkness
  1956. {
  1957. RemoveBonus rb(RemoveBonus::TOWN);
  1958. rb.whoID = t->id;
  1959. rb.source = Bonus::TOWN_STRUCTURE;
  1960. rb.id = 17;
  1961. sendAndApply(&rb);
  1962. }
  1963. return true;
  1964. }
  1965. void CGameHandler::sendMessageToAll( const std::string &message )
  1966. {
  1967. SystemMessage sm;
  1968. sm.text = message;
  1969. sendToAllClients(&sm);
  1970. }
  1971. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram, si32 fromLvl )
  1972. {
  1973. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid].get());
  1974. const CArmedInstance *dst = NULL;
  1975. const CCreature *c = VLC->creh->creatures[crid];
  1976. bool warMachine = c->hasBonusOfType(Bonus::SIEGE_WEAPON);
  1977. //TODO: test for owning
  1978. if(dw->ID == TOWNI_TYPE)
  1979. dst = dw;
  1980. else if(dw->ID == 17 || dw->ID == 20 || dw->ID == 78) //advmap dwelling
  1981. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  1982. else if(dw->ID == 106)
  1983. dst = dynamic_cast<const CGHeroInstance *>(getTile(dw->visitablePos())->visitableObjects.back());
  1984. assert(dw && dst);
  1985. //verify
  1986. bool found = false;
  1987. int level = 0;
  1988. typedef std::pair<const int,int> Parka;
  1989. for(; level < dw->creatures.size(); level++) //iterate through all levels
  1990. {
  1991. if ( (fromLvl != -1) && ( level !=fromLvl ) )
  1992. continue;
  1993. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  1994. int i = 0;
  1995. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  1996. if(cur.second[i] == crid)
  1997. break;
  1998. if(i < cur.second.size())
  1999. {
  2000. found = true;
  2001. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  2002. break;
  2003. }
  2004. }
  2005. int slot = dst->getSlotFor(crid);
  2006. if(!found && complain("Cannot recruit: no such creatures!")
  2007. || cram > VLC->creh->creatures[crid]->maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  2008. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  2009. || slot<0 && !warMachine && complain("Cannot recruit: no available slot!"))
  2010. {
  2011. return false;
  2012. }
  2013. //recruit
  2014. SetResources sr;
  2015. sr.player = dst->tempOwner;
  2016. for(int i=0;i<RESOURCE_QUANTITY;i++)
  2017. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (c->cost[i] * cram);
  2018. SetAvailableCreatures sac;
  2019. sac.tid = objid;
  2020. sac.creatures = dw->creatures;
  2021. sac.creatures[level].first -= cram;
  2022. sendAndApply(&sr);
  2023. sendAndApply(&sac);
  2024. if(warMachine)
  2025. {
  2026. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(dst);
  2027. if(!h)
  2028. COMPLAIN_RET("Only hero can buy war machines");
  2029. switch(crid)
  2030. {
  2031. case 146:
  2032. giveHeroNewArtifact(h, VLC->arth->artifacts[4], Arts::MACH1);
  2033. break;
  2034. case 147:
  2035. giveHeroNewArtifact(h, VLC->arth->artifacts[6], Arts::MACH3);
  2036. break;
  2037. case 148:
  2038. giveHeroNewArtifact(h, VLC->arth->artifacts[5], Arts::MACH2);
  2039. break;
  2040. default:
  2041. complain("This war machine cannot be recruited!");
  2042. return false;
  2043. }
  2044. }
  2045. else
  2046. {
  2047. addToSlot(StackLocation(dst, slot), c, cram);
  2048. }
  2049. return true;
  2050. }
  2051. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  2052. {
  2053. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid].get());
  2054. assert(obj->hasStackAtSlot(pos));
  2055. UpgradeInfo ui = gs->getUpgradeInfo(obj->getStack(pos));
  2056. int player = obj->tempOwner;
  2057. int crQuantity = obj->slots[pos]->count;
  2058. int newIDpos= vstd::findPos(ui.newID, upgID);//get position of new id in UpgradeInfo
  2059. //check if upgrade is possible
  2060. if( (ui.oldID<0 || newIDpos == -1 ) && complain("That upgrade is not possible!"))
  2061. {
  2062. return false;
  2063. }
  2064. //check if player has enough resources
  2065. for (std::set<std::pair<int,int> >::iterator j=ui.cost[newIDpos].begin(); j!=ui.cost[newIDpos].end(); j++)
  2066. {
  2067. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  2068. {
  2069. complain("Cannot upgrade, not enough resources!");
  2070. return false;
  2071. }
  2072. }
  2073. //take resources
  2074. for (std::set<std::pair<int,int> >::iterator j=ui.cost[newIDpos].begin(); j!=ui.cost[newIDpos].end(); j++)
  2075. {
  2076. SetResource sr;
  2077. sr.player = player;
  2078. sr.resid = j->first;
  2079. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  2080. sendAndApply(&sr);
  2081. }
  2082. //upgrade creature
  2083. changeStackType(StackLocation(obj, pos), VLC->creh->creatures[upgID]);
  2084. return true;
  2085. }
  2086. bool CGameHandler::changeStackType(const StackLocation &sl, CCreature *c)
  2087. {
  2088. if(!sl.army->hasStackAtSlot(sl.slot))
  2089. COMPLAIN_RET("Cannot find a stack to change type");
  2090. SetStackType sst;
  2091. sst.sl = sl;
  2092. sst.type = c;
  2093. sendAndApply(&sst);
  2094. return true;
  2095. }
  2096. void CGameHandler::moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging)
  2097. {
  2098. assert(src->canBeMergedWith(*dst, allowMerging));
  2099. while(!src->stacksCount())//while there are unmoved creatures
  2100. {
  2101. TSlots::const_iterator i = src->Slots().begin(); //iterator to stack to move
  2102. StackLocation sl(src, i->first); //location of stack to move
  2103. TSlot pos = dst->getSlotFor(i->second->type);
  2104. if(pos < 0)
  2105. {
  2106. //try to merge two other stacks to make place
  2107. std::pair<TSlot, TSlot> toMerge;
  2108. if(dst->mergableStacks(toMerge, i->first) && allowMerging)
  2109. {
  2110. moveStack(StackLocation(dst, toMerge.first), StackLocation(dst, toMerge.second)); //merge toMerge.first into toMerge.second
  2111. assert(!dst->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  2112. moveStack(sl, StackLocation(dst, toMerge.first)); //move stack to freed slot
  2113. }
  2114. else
  2115. {
  2116. complain("Unexpected failure during an attempt to move army from " + src->nodeName() + " to " + dst->nodeName() + "!");
  2117. return;
  2118. }
  2119. }
  2120. else
  2121. {
  2122. moveStack(sl, StackLocation(dst, pos));
  2123. }
  2124. }
  2125. }
  2126. bool CGameHandler::garrisonSwap( si32 tid )
  2127. {
  2128. CGTownInstance *town = gs->getTown(tid);
  2129. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2130. {
  2131. if(!town->visitingHero->canBeMergedWith(*town))
  2132. {
  2133. complain("Cannot make garrison swap, not enough free slots!");
  2134. return false;
  2135. }
  2136. moveArmy(town, town->visitingHero, true);
  2137. SetHeroesInTown intown;
  2138. intown.tid = tid;
  2139. intown.visiting = -1;
  2140. intown.garrison = town->visitingHero->id;
  2141. sendAndApply(&intown);
  2142. return true;
  2143. }
  2144. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2145. {
  2146. //check if moving hero out of town will break 8 wandering heroes limit
  2147. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2148. {
  2149. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2150. return false;
  2151. }
  2152. SetHeroesInTown intown;
  2153. intown.tid = tid;
  2154. intown.garrison = -1;
  2155. intown.visiting = town->garrisonHero->id;
  2156. sendAndApply(&intown);
  2157. return true;
  2158. }
  2159. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2160. {
  2161. SetHeroesInTown intown;
  2162. intown.tid = tid;
  2163. intown.garrison = town->visitingHero->id;
  2164. intown.visiting = town->garrisonHero->id;
  2165. sendAndApply(&intown);
  2166. return true;
  2167. }
  2168. else
  2169. {
  2170. complain("Cannot swap garrison hero!");
  2171. return false;
  2172. }
  2173. }
  2174. // With the amount of changes done to the function, it's more like transferArtifacts.
  2175. // Function moves artifact from src to dst. If dst is not a backpack and is already occupied, old dst art goes to backpack and is replaced.
  2176. bool CGameHandler::moveArtifact(si32 srcHeroID, si32 destHeroID, ui16 srcSlot, ui16 destSlot)
  2177. {
  2178. CGHeroInstance *srcHero = gs->getHero(srcHeroID);
  2179. CGHeroInstance *destHero = gs->getHero(destHeroID);
  2180. ArtifactLocation src(srcHero, srcSlot), dst(destHero, destSlot);
  2181. // Make sure exchange is even possible between the two heroes.
  2182. if(!isAllowedExchange(srcHeroID, destHeroID))
  2183. COMPLAIN_RET("That heroes cannot make any exchange!");
  2184. const CArtifactInstance *srcArtifact = src.getArt();
  2185. const CArtifactInstance *destArtifact = dst.getArt();
  2186. if (srcArtifact == NULL)
  2187. COMPLAIN_RET("No artifact to move!");
  2188. if (destArtifact && srcHero->tempOwner != destHero->tempOwner)
  2189. COMPLAIN_RET("Can't touch artifact on hero of another player!");
  2190. // // Combinational artifacts needs to be removed first so they don't get denied movement because of their own locks.
  2191. // if (srcHeroID == destHeroID && srcSlot < 19 && destSlot < 19)
  2192. // {
  2193. // sha.setArtAtPos(srcSlot, NULL);
  2194. // if (!vstd::contains(sha.artifWorn, destSlot))
  2195. // destArtifact = NULL;
  2196. // }
  2197. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2198. // Moving to the backpack is always allowed.
  2199. if ((!srcArtifact || destSlot < Arts::BACKPACK_START)
  2200. && srcArtifact && !srcArtifact->canBePutAt(dst))
  2201. COMPLAIN_RET("Cannot swap artifacts!");
  2202. if ((srcArtifact && srcArtifact->artType->id == Arts::LOCK_ID) || (destArtifact && destArtifact->artType->id == Arts::LOCK_ID))
  2203. COMPLAIN_RET("Cannot move artifact locks.");
  2204. if (destSlot >= Arts::BACKPACK_START && srcArtifact->artType->isBig())
  2205. COMPLAIN_RET("Cannot put big artifacts in backpack!");
  2206. if (srcSlot == Arts::MACH4 || destSlot == Arts::MACH4)
  2207. COMPLAIN_RET("Cannot move catapult!");
  2208. //moving art to backpack is always allowed (we've ruled out exceptions)
  2209. if(destSlot >= Arts::BACKPACK_START)
  2210. {
  2211. moveArtifact(src, dst);
  2212. }
  2213. else //moving art to another slot
  2214. {
  2215. if(destArtifact) //old artifact must be removed first
  2216. {
  2217. moveArtifact(dst, ArtifactLocation(destHero, destHero->artifactsInBackpack.size()-1));
  2218. }
  2219. moveArtifact(src, dst);
  2220. }
  2221. //
  2222. // // If dest does not fit in src, put it in dest's backpack instead.
  2223. // if (srcHeroID == destHeroID) // To avoid stumbling on own locks, remove artifact first.
  2224. // sha.setArtAtPos(destSlot, NULL);
  2225. // const bool destFits = !destArtifact || srcSlot >= 19 || destSlot >= 19 || destArtifact->fitsAt(sha.artifWorn, srcSlot);
  2226. // if (srcHeroID == destHeroID && destArtifact)
  2227. // sha.setArtAtPos(destSlot, destArtifact);
  2228. //
  2229. // sha.setArtAtPos(srcSlot, NULL);
  2230. // if (destSlot < 19 && (destArtifact || srcSlot < 19) && destFits)
  2231. // sha.setArtAtPos(srcSlot, destArtifact ? destArtifact : NULL);
  2232. //
  2233. // // Internal hero artifact arrangement.
  2234. // if(srcHero == destHero)
  2235. // {
  2236. // // Correction for destination from removing source artifact in backpack.
  2237. // if (srcSlot >= 19 && destSlot >= 19 && srcSlot < destSlot)
  2238. // destSlot--;
  2239. //
  2240. // sha.setArtAtPos(destSlot, srcHero->getArtAtPos(srcSlot));
  2241. // }
  2242. // if (srcHeroID != destHeroID)
  2243. // {
  2244. // // Exchange between two different heroes.
  2245. // SetHeroArtifacts sha2;
  2246. // sha2.hid = destHeroID;
  2247. // sha2.artifacts = destHero->artifacts;
  2248. // sha2.artifWorn = destHero->artifWorn;
  2249. // sha2.setArtAtPos(destSlot, srcArtifact ? srcArtifact : NULL);
  2250. // if (!destFits)
  2251. // sha2.setArtAtPos(sha2.artifacts.size() + 19, destHero->getArtAtPos(destSlot));
  2252. // sendAndApply(&sha2);
  2253. // }
  2254. // sendAndApply(&sha);
  2255. return true;
  2256. }
  2257. /**
  2258. * Assembles or disassembles a combination artifact.
  2259. * @param heroID ID of hero holding the artifact(s).
  2260. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2261. * @param assemble True for assembly operation, false for disassembly.
  2262. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2263. * artifact to assemble to. Otherwise it's not used.
  2264. */
  2265. bool CGameHandler::assembleArtifacts (si32 heroID, ui16 artifactSlot, bool assemble, ui32 assembleTo)
  2266. {
  2267. if (artifactSlot < 0 || artifactSlot > 18) {
  2268. complain("Illegal artifact slot.");
  2269. return false;
  2270. }
  2271. CGHeroInstance *hero = gs->getHero(heroID);
  2272. const CArtifactInstance *destArtifact = hero->getArt(artifactSlot);
  2273. /*
  2274. SetHeroArtifacts sha;
  2275. sha.hid = heroID;
  2276. sha.artifacts = hero->artifacts;
  2277. sha.artifWorn = hero->artifWorn;
  2278. if (assemble)
  2279. {
  2280. if (VLC->arth->artifacts.size() < assembleTo)
  2281. {
  2282. complain("Illegal artifact to assemble to.");
  2283. return false;
  2284. }
  2285. if (!destArtifact->canBeAssembledTo(hero->artifWorn, assembleTo))
  2286. {
  2287. complain("Artifact cannot be assembled.");
  2288. return false;
  2289. }
  2290. const CArtifact &artifact = *VLC->arth->artifacts[assembleTo];
  2291. if (artifact.constituents == NULL)
  2292. {
  2293. complain("Not a combinational artifact.");
  2294. return false;
  2295. }
  2296. // Perform assembly.
  2297. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2298. const bool destSpecific = vstd::contains(artifact.possibleSlots, artifactSlot); // Prefer the chosen slot as the location for the assembled artifact.
  2299. BOOST_FOREACH(ui32 constituentID, *artifact.constituents)
  2300. {
  2301. if (destSpecific && constituentID == destArtifact->id)
  2302. {
  2303. sha.artifWorn[artifactSlot] = VLC->arth->artifacts[assembleTo];
  2304. destConsumed = true;
  2305. continue;
  2306. }
  2307. bool found = false;
  2308. for (std::map<ui16, const CArtifact*>::iterator it = sha.artifWorn.begin(); it != sha.artifWorn.end(); ++it)
  2309. {
  2310. if (it->second->id == constituentID)
  2311. { // Found possible constituent to substitute.
  2312. if (destSpecific && !destConsumed && it->second->id == destArtifact->id)
  2313. {
  2314. // Find the specified destination for assembled artifact.
  2315. if (it->first == artifactSlot)
  2316. {
  2317. it->second = VLC->arth->artifacts[assembleTo];
  2318. destConsumed = true;
  2319. found = true;
  2320. break;
  2321. }
  2322. }
  2323. else
  2324. {
  2325. // Either put the assembled artifact in a fitting spot, or put a lock.
  2326. if (!destSpecific && !destConsumed && vstd::contains(artifact.possibleSlots, it->first))
  2327. {
  2328. it->second = VLC->arth->artifacts[assembleTo];
  2329. destConsumed = true;
  2330. }
  2331. else
  2332. {
  2333. it->second = VLC->arth->artifacts[145];
  2334. }
  2335. found = true;
  2336. break;
  2337. }
  2338. }
  2339. }
  2340. if (!found) {
  2341. complain("Constituent missing.");
  2342. return false;
  2343. }
  2344. }
  2345. }
  2346. else
  2347. {
  2348. // Perform disassembly.
  2349. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2350. BOOST_FOREACH(ui32 constituentID, *destArtifact->constituents)
  2351. {
  2352. const CArtifact &constituent = *VLC->arth->artifacts[constituentID];
  2353. if (!destConsumed && vstd::contains(constituent.possibleSlots, artifactSlot))
  2354. {
  2355. sha.artifWorn[artifactSlot] = VLC->arth->artifacts[constituentID];
  2356. destConsumed = true;
  2357. }
  2358. else
  2359. {
  2360. BOOST_REVERSE_FOREACH(ui16 slotID, constituent.possibleSlots)
  2361. {
  2362. if (vstd::contains(sha.artifWorn, slotID) && sha.artifWorn[slotID]->id == 145)
  2363. {
  2364. const_cast<CArtifact*>(sha.artifWorn[slotID])->id = constituentID;
  2365. break;
  2366. }
  2367. }
  2368. }
  2369. }
  2370. }
  2371. sendAndApply(&sha);
  2372. return true;*/
  2373. return false;
  2374. }
  2375. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2376. {
  2377. CGHeroInstance *hero = gs->getHero(hid);
  2378. CGTownInstance *town = const_cast<CGTownInstance*>(hero->visitedTown);
  2379. if(aid==0) //spellbook
  2380. {
  2381. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2382. || getResource(hero->getOwner(), Res::GOLD) < SPELLBOOK_GOLD_COST && complain("Cannot buy a spellbook, not enough gold!")
  2383. || hero->getArt(Arts::SPELLBOOK) && complain("Cannot buy a spellbook, hero already has a one!")
  2384. )
  2385. return false;
  2386. giveResource(hero->getOwner(),Res::GOLD,-SPELLBOOK_GOLD_COST);
  2387. giveHeroNewArtifact(hero, VLC->arth->artifacts[0], Arts::SPELLBOOK);
  2388. assert(hero->getArt(Arts::SPELLBOOK));
  2389. giveSpells(town,hero);
  2390. return true;
  2391. }
  2392. else if(aid < 7 && aid > 3) //war machine
  2393. {
  2394. int price = VLC->arth->artifacts[aid]->price;
  2395. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2396. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2397. || gs->getPlayer(hero->getOwner())->resources[Res::GOLD] < price && complain("Not enough gold!") //no gold
  2398. || (!(town->subID == 6 && vstd::contains(town->builtBuildings,si32(22) ) )
  2399. && town->town->warMachine!= aid ) && complain("This machine is unavailable here!") )
  2400. {
  2401. return false;
  2402. }
  2403. giveResource(hero->getOwner(),Res::GOLD,-price);
  2404. giveHeroNewArtifact(hero, VLC->arth->artifacts[aid], 9+aid);
  2405. return true;
  2406. }
  2407. return false;
  2408. }
  2409. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, int rid, int aid)
  2410. {
  2411. if(!vstd::contains(m->availableItemsIds(RESOURCE_ARTIFACT), aid))
  2412. COMPLAIN_RET("That artifact is unavailable!");
  2413. int b1, b2;
  2414. m->getOffer(rid, aid, b1, b2, RESOURCE_ARTIFACT);
  2415. if(getResource(h->tempOwner, rid) < b1)
  2416. COMPLAIN_RET("You can't afford to buy this artifact!");
  2417. SetResource sr;
  2418. sr.player = h->tempOwner;
  2419. sr.resid = rid;
  2420. sr.val = getResource(h->tempOwner, rid) - b1;
  2421. sendAndApply(&sr);
  2422. SetAvailableArtifacts saa;
  2423. if(m->o->ID == TOWNI_TYPE)
  2424. {
  2425. saa.id = -1;
  2426. saa.arts = CGTownInstance::merchantArtifacts;
  2427. }
  2428. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m->o)) //black market
  2429. {
  2430. saa.id = bm->id;
  2431. saa.arts = bm->artifacts;
  2432. }
  2433. else
  2434. COMPLAIN_RET("Wrong marktet...");
  2435. bool found = false;
  2436. BOOST_FOREACH(const CArtifact *&art, saa.arts)
  2437. {
  2438. if(art && art->id == aid)
  2439. {
  2440. art = NULL;
  2441. found = true;
  2442. break;
  2443. }
  2444. }
  2445. if(!found)
  2446. COMPLAIN_RET("Cannot find selected artifact on the list");
  2447. sendAndApply(&saa);
  2448. giveHeroNewArtifact(h, VLC->arth->artifacts[aid], -2);
  2449. return true;
  2450. }
  2451. bool CGameHandler::buySecSkill( const IMarket *m, const CGHeroInstance *h, int skill)
  2452. {
  2453. if (!h)
  2454. COMPLAIN_RET("You need hero to buy a skill!");
  2455. if (h->getSecSkillLevel(static_cast<CGHeroInstance::SecondarySkill>(skill)))
  2456. COMPLAIN_RET("Hero already know this skill");
  2457. if (h->secSkills.size() >= SKILL_PER_HERO)//can't learn more skills
  2458. COMPLAIN_RET("Hero can't learn any more skills");
  2459. if (h->type->heroClass->proSec[skill]==0)//can't learn this skill (like necromancy for most of non-necros)
  2460. COMPLAIN_RET("The hero can't learn this skill!");
  2461. if(!vstd::contains(m->availableItemsIds(RESOURCE_SKILL), skill))
  2462. COMPLAIN_RET("That skill is unavailable!");
  2463. if(getResource(h->tempOwner, 6) < 2000)//TODO: remove hardcoded resource\summ?
  2464. COMPLAIN_RET("You can't afford to buy this skill");
  2465. SetResource sr;
  2466. sr.player = h->tempOwner;
  2467. sr.resid = 6;
  2468. sr.val = getResource(h->tempOwner, 6) - 2000;
  2469. sendAndApply(&sr);
  2470. changeSecSkill(h->id, skill, 1, true);
  2471. return true;
  2472. }
  2473. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, ui8 player, ui32 id1, ui32 id2)
  2474. {
  2475. int r1 = gs->getPlayer(player)->resources[id1],
  2476. r2 = gs->getPlayer(player)->resources[id2];
  2477. amin(val, r1); //can't trade more resources than have
  2478. int b1, b2; //base quantities for trade
  2479. market->getOffer(id1, id2, b1, b2, RESOURCE_RESOURCE);
  2480. int units = val / b1; //how many base quantities we trade
  2481. if(val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2482. {
  2483. //TODO: complain?
  2484. assert(0);
  2485. }
  2486. SetResource sr;
  2487. sr.player = player;
  2488. sr.resid = id1;
  2489. sr.val = r1 - b1 * units;
  2490. sendAndApply(&sr);
  2491. sr.resid = id2;
  2492. sr.val = r2 + b2 * units;
  2493. sendAndApply(&sr);
  2494. return true;
  2495. }
  2496. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, ui32 slot, ui32 resourceID)
  2497. {
  2498. if(!vstd::contains(hero->Slots(), slot))
  2499. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  2500. const CStackInstance &s = hero->getStack(slot);
  2501. if(s.count < count //can't sell more creatures than have
  2502. || hero->Slots().size() == 1 && hero->needsLastStack() && s.count == count) //can't sell last stack
  2503. {
  2504. COMPLAIN_RET("Not enough creatures in army!");
  2505. }
  2506. int b1, b2; //base quantities for trade
  2507. market->getOffer(s.type->idNumber, resourceID, b1, b2, CREATURE_RESOURCE);
  2508. int units = count / b1; //how many base quantities we trade
  2509. if(count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2510. {
  2511. //TODO: complain?
  2512. assert(0);
  2513. }
  2514. changeStackCount(StackLocation(hero, slot), -count);
  2515. SetResource sr;
  2516. sr.player = hero->tempOwner;
  2517. sr.resid = resourceID;
  2518. sr.val = getResource(hero->tempOwner, resourceID) + b2 * units;
  2519. sendAndApply(&sr);
  2520. return true;
  2521. }
  2522. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, ui32 slot)
  2523. {
  2524. const CArmedInstance *army = NULL;
  2525. if (hero)
  2526. army = hero;
  2527. else
  2528. army = dynamic_cast<const CGTownInstance *>(market->o);
  2529. if (!army)
  2530. COMPLAIN_RET("Incorrect call to transform in undead!");
  2531. if(!army->hasStackAtSlot(slot))
  2532. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  2533. const CStackInstance &s = army->getStack(slot);
  2534. int resCreature;//resulting creature - bone dragons or skeletons
  2535. if (s.hasBonusOfType(Bonus::DRAGON_NATURE))
  2536. resCreature = 68;
  2537. else
  2538. resCreature = 56;
  2539. changeStackType(StackLocation(army, slot), VLC->creh->creatures[resCreature]);
  2540. return true;
  2541. }
  2542. bool CGameHandler::sendResources(ui32 val, ui8 player, ui32 r1, ui32 r2)
  2543. {
  2544. const PlayerState *p2 = gs->getPlayer(r2, false);
  2545. if(!p2 || p2->status != PlayerState::INGAME)
  2546. {
  2547. complain("Dest player must be in game!");
  2548. return false;
  2549. }
  2550. si32 curRes1 = gs->getPlayer(player)->resources[r1], curRes2 = gs->getPlayer(r2)->resources[r1];
  2551. val = std::min(si32(val),curRes1);
  2552. SetResource sr;
  2553. sr.player = player;
  2554. sr.resid = r1;
  2555. sr.val = curRes1 - val;
  2556. sendAndApply(&sr);
  2557. sr.player = r2;
  2558. sr.val = curRes2 + val;
  2559. sendAndApply(&sr);
  2560. return true;
  2561. }
  2562. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  2563. {
  2564. gs->getHero(hid)-> formation = formation;
  2565. return true;
  2566. }
  2567. bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, ui8 player)
  2568. {
  2569. const PlayerState *p = gs->getPlayer(player);
  2570. const CGTownInstance *t = gs->getTown(obj->id);
  2571. //common prconditions
  2572. if( p->resources[6]<2500 && complain("Not enough gold for buying hero!")
  2573. || getHeroCount(player, false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!"))
  2574. return false;
  2575. if(t) //tavern in town
  2576. {
  2577. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  2578. || t->visitingHero && complain("There is visiting hero - no place!"))
  2579. return false;
  2580. }
  2581. else if(obj->ID == 95) //Tavern on adv map
  2582. {
  2583. if(getTile(obj->visitablePos())->visitableObjects.back() != obj && complain("Tavern entry must be unoccupied!"))
  2584. return false;
  2585. }
  2586. const CGHeroInstance *nh = p->availableHeroes[hid];
  2587. assert(nh);
  2588. HeroRecruited hr;
  2589. hr.tid = obj->id;
  2590. hr.hid = nh->subID;
  2591. hr.player = player;
  2592. hr.tile = obj->visitablePos() + nh->getVisitableOffset();
  2593. sendAndApply(&hr);
  2594. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = gs->unusedHeroesFromPool();
  2595. const CGHeroInstance *theOtherHero = p->availableHeroes[!hid];
  2596. const CGHeroInstance *newHero = gs->hpool.pickHeroFor(false, player, getNativeTown(player), pool, theOtherHero->type->heroClass);
  2597. SetAvailableHeroes sah;
  2598. sah.player = player;
  2599. if(newHero)
  2600. {
  2601. sah.hid[hid] = newHero->subID;
  2602. sah.army[hid] = new CCreatureSet();
  2603. sah.army[hid]->addToSlot(0, VLC->creh->nameToID[newHero->type->refTypeStack[0]],1);
  2604. }
  2605. else
  2606. sah.hid[hid] = -1;
  2607. sah.hid[!hid] = theOtherHero ? theOtherHero->subID : -1;
  2608. sendAndApply(&sah);
  2609. SetResource sr;
  2610. sr.player = player;
  2611. sr.resid = 6;
  2612. sr.val = p->resources[6] - 2500;
  2613. sendAndApply(&sr);
  2614. if(t)
  2615. {
  2616. vistiCastleObjects (t, nh);
  2617. giveSpells (t,nh);
  2618. }
  2619. return true;
  2620. }
  2621. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  2622. {
  2623. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2624. if(vstd::contains(callbacks,qid))
  2625. {
  2626. CFunctionList<void(ui32)> callb = callbacks[qid];
  2627. callbacks.erase(qid);
  2628. if(callb)
  2629. callb(answer);
  2630. }
  2631. else if(vstd::contains(garrisonCallbacks,qid))
  2632. {
  2633. if(garrisonCallbacks[qid])
  2634. garrisonCallbacks[qid]();
  2635. garrisonCallbacks.erase(qid);
  2636. allowedExchanges.erase(qid);
  2637. }
  2638. else
  2639. {
  2640. tlog1 << "Unknown query reply...\n";
  2641. return false;
  2642. }
  2643. return true;
  2644. }
  2645. bool CGameHandler::makeBattleAction( BattleAction &ba )
  2646. {
  2647. tlog1 << "\tMaking action of type " << ba.actionType << std::endl;
  2648. bool ok = true;
  2649. switch(ba.actionType)
  2650. {
  2651. case 2: //walk
  2652. {
  2653. sendAndApply(&StartAction(ba)); //start movement
  2654. moveStack(ba.stackNumber,ba.destinationTile); //move
  2655. sendAndApply(&EndAction());
  2656. break;
  2657. }
  2658. case 3: //defend
  2659. case 8: //wait
  2660. {
  2661. sendAndApply(&StartAction(ba));
  2662. sendAndApply(&EndAction());
  2663. break;
  2664. }
  2665. case 4: //retreat/flee
  2666. {
  2667. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  2668. break;
  2669. //TODO: remove retreating hero from map and place it in recruitment list
  2670. BattleResult *br = new BattleResult;
  2671. br->result = 1;
  2672. br->winner = !ba.side; //fleeing side loses
  2673. gs->curB->calculateCasualties(br->casualties);
  2674. giveExp(*br);
  2675. battleResult.set(br);
  2676. break;
  2677. }
  2678. case 6: //walk or attack
  2679. {
  2680. sendAndApply(&StartAction(ba)); //start movement and attack
  2681. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  2682. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  2683. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2684. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  2685. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  2686. && !(curStack->doubleWide()
  2687. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  2688. ) //nor occupy specified hex
  2689. )
  2690. {
  2691. std::string problem = "We cannot move this stack to its destination " + curStack->getCreature()->namePl;
  2692. tlog3 << problem << std::endl;
  2693. complain(problem);
  2694. ok = false;
  2695. sendAndApply(&EndAction());
  2696. break;
  2697. }
  2698. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  2699. {
  2700. stackAtEnd = NULL;
  2701. }
  2702. if(!stackAtEnd)
  2703. {
  2704. std::ostringstream problem;
  2705. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  2706. std::string probl = problem.str();
  2707. tlog3 << probl << std::endl;
  2708. complain(probl);
  2709. ok = false;
  2710. sendAndApply(&EndAction());
  2711. break;
  2712. }
  2713. ui16 curpos = curStack->position,
  2714. enemypos = stackAtEnd->position;
  2715. if( !(
  2716. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  2717. || (curStack->doubleWide() //back <=> front
  2718. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  2719. || (stackAtEnd->doubleWide() //front <=> back
  2720. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2721. || (stackAtEnd->doubleWide() && curStack->doubleWide()//back <=> back
  2722. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2723. )
  2724. )
  2725. {
  2726. tlog3 << "Attack cannot be performed!";
  2727. sendAndApply(&EndAction());
  2728. ok = false;
  2729. }
  2730. //attack
  2731. BattleAttack bat;
  2732. prepareAttack(bat, curStack, stackAtEnd, distance);
  2733. sendAndApply(&bat);
  2734. handleAfterAttackCasting(bat);
  2735. //counterattack
  2736. if(!curStack->hasBonusOfType(Bonus::BLOCKS_RETALIATION)
  2737. && stackAtEnd->alive()
  2738. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS) )
  2739. && !stackAtEnd->hasBonusOfType(Bonus::SIEGE_WEAPON)
  2740. && !stackAtEnd->hasBonusOfType(Bonus::HYPNOTIZED))
  2741. {
  2742. prepareAttack(bat, stackAtEnd, curStack, 0);
  2743. bat.flags |= 2;
  2744. sendAndApply(&bat);
  2745. handleAfterAttackCasting(bat);
  2746. }
  2747. //second attack
  2748. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0
  2749. && !curStack->hasBonusOfType(Bonus::SHOOTER)
  2750. && curStack->alive()
  2751. && stackAtEnd->alive() )
  2752. {
  2753. bat.flags = 0;
  2754. prepareAttack(bat, curStack, stackAtEnd, 0);
  2755. sendAndApply(&bat);
  2756. handleAfterAttackCasting(bat);
  2757. }
  2758. //return
  2759. if(curStack->hasBonusOfType(Bonus::RETURN_AFTER_STRIKE) && startingPos != curStack->position && curStack->alive())
  2760. {
  2761. moveStack(ba.stackNumber, startingPos);
  2762. //NOTE: curStack->ID == ba.stackNumber (rev 1431)
  2763. }
  2764. sendAndApply(&EndAction());
  2765. break;
  2766. }
  2767. case 7: //shoot
  2768. {
  2769. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2770. *destStack= gs->curB->getStackT(ba.destinationTile);
  2771. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  2772. break;
  2773. sendAndApply(&StartAction(ba)); //start shooting
  2774. BattleAttack bat;
  2775. bat.flags |= 1;
  2776. prepareAttack(bat, curStack, destStack, 0);
  2777. sendAndApply(&bat);
  2778. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  2779. && curStack->alive()
  2780. && destStack->alive()
  2781. && curStack->shots
  2782. )
  2783. {
  2784. prepareAttack(bat, curStack, destStack, 0);
  2785. sendAndApply(&bat);
  2786. handleAfterAttackCasting(bat);
  2787. }
  2788. sendAndApply(&EndAction());
  2789. break;
  2790. }
  2791. case 9: //catapult
  2792. {
  2793. sendAndApply(&StartAction(ba));
  2794. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  2795. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(CGHeroInstance::BALLISTICS)];
  2796. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  2797. if(attackedPart == -1)
  2798. {
  2799. complain("catapult tried to attack non-catapultable hex!");
  2800. break;
  2801. }
  2802. int wallInitHP = gs->curB->si.wallState[attackedPart];
  2803. int dmgAlreadyDealt = 0; //in successive iterations damage is dealt but not yet substracted from wall's HPs
  2804. for(int g=0; g<sbi.shots; ++g)
  2805. {
  2806. if(wallInitHP + dmgAlreadyDealt == 3) //it's not destroyed
  2807. continue;
  2808. CatapultAttack ca; //package for clients
  2809. std::pair< std::pair< ui8, si16 >, ui8> attack; //<< attackedPart , destination tile >, damageDealt >
  2810. attack.first.first = attackedPart;
  2811. attack.first.second = ba.destinationTile;
  2812. attack.second = 0;
  2813. int chanceForHit = 0;
  2814. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  2815. switch(attackedPart)
  2816. {
  2817. case 0: //keep
  2818. chanceForHit = sbi.keep;
  2819. break;
  2820. case 1: //bottom tower
  2821. case 6: //upper tower
  2822. chanceForHit = sbi.tower;
  2823. break;
  2824. case 2: //bottom wall
  2825. case 3: //below gate
  2826. case 4: //over gate
  2827. case 5: //upper wall
  2828. chanceForHit = sbi.wall;
  2829. break;
  2830. case 7: //gate
  2831. chanceForHit = sbi.gate;
  2832. break;
  2833. }
  2834. if(rand()%100 <= chanceForHit) //hit is successful
  2835. {
  2836. int dmgRand = rand()%100;
  2837. //accumulating dmgChance
  2838. dmgChance[1] += dmgChance[0];
  2839. dmgChance[2] += dmgChance[1];
  2840. //calculating dealt damage
  2841. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  2842. {
  2843. if(dmgRand <= dmgChance[v])
  2844. {
  2845. attack.second = std::min(3 - dmgAlreadyDealt - wallInitHP, v);
  2846. dmgAlreadyDealt += attack.second;
  2847. break;
  2848. }
  2849. }
  2850. //removing creatures in turrets / keep if one is destroyed
  2851. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  2852. {
  2853. int posRemove = -1;
  2854. switch(attackedPart)
  2855. {
  2856. case 0: //keep
  2857. posRemove = -2;
  2858. break;
  2859. case 1: //bottom tower
  2860. posRemove = -3;
  2861. break;
  2862. case 6: //upper tower
  2863. posRemove = -4;
  2864. break;
  2865. }
  2866. BattleStacksRemoved bsr;
  2867. for(int g=0; g<gs->curB->stacks.size(); ++g)
  2868. {
  2869. if(gs->curB->stacks[g]->position == posRemove)
  2870. {
  2871. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  2872. break;
  2873. }
  2874. }
  2875. sendAndApply(&bsr);
  2876. }
  2877. }
  2878. ca.attacker = ba.stackNumber;
  2879. ca.attackedParts.insert(attack);
  2880. sendAndApply(&ca);
  2881. }
  2882. sendAndApply(&EndAction());
  2883. break;
  2884. }
  2885. case 12: //healing
  2886. {
  2887. sendAndApply(&StartAction(ba));
  2888. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  2889. CStack *healer = gs->curB->getStack(ba.stackNumber),
  2890. *destStack = gs->curB->getStackT(ba.destinationTile);
  2891. if(healer == NULL || destStack == NULL || !healer->hasBonusOfType(Bonus::HEALER))
  2892. {
  2893. complain("There is either no healer, no destination, or healer cannot heal :P");
  2894. }
  2895. int maxHealable = destStack->MaxHealth() - destStack->firstHPleft;
  2896. int maxiumHeal = std::max(10, attackingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 27));
  2897. int healed = std::min(maxHealable, maxiumHeal);
  2898. if(healed == 0)
  2899. {
  2900. //nothing to heal.. should we complain?
  2901. }
  2902. else
  2903. {
  2904. StacksHealedOrResurrected shr;
  2905. shr.lifeDrain = false;
  2906. StacksHealedOrResurrected::HealInfo hi;
  2907. hi.healedHP = healed;
  2908. hi.lowLevelResurrection = 0;
  2909. hi.stackID = destStack->ID;
  2910. shr.healedStacks.push_back(hi);
  2911. sendAndApply(&shr);
  2912. }
  2913. sendAndApply(&EndAction());
  2914. break;
  2915. }
  2916. }
  2917. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  2918. battleMadeAction.setn(true);
  2919. return ok;
  2920. }
  2921. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  2922. {
  2923. bool cheated=true;
  2924. sendAndApply(&PlayerMessage(player,message));
  2925. if(message == "vcmiistari") //give all spells and 999 mana
  2926. {
  2927. SetMana sm;
  2928. ChangeSpells cs;
  2929. SetHeroArtifacts sha;
  2930. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  2931. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  2932. sm.hid = cs.hid = h->id;
  2933. //give all spells
  2934. cs.learn = 1;
  2935. for(int i=0;i<VLC->spellh->spells.size();i++)
  2936. {
  2937. if(!VLC->spellh->spells[i]->creatureAbility)
  2938. cs.spells.insert(i);
  2939. }
  2940. //give mana
  2941. sm.val = 999;
  2942. if(!h->getArt(17)) //hero doesn't have spellbook
  2943. {
  2944. //give spellbook
  2945. sha.hid = h->id;
  2946. sha.artifacts = h->artifacts;
  2947. sha.artifWorn = h->artifWorn;
  2948. VLC->arth->equipArtifact(sha.artifWorn, 17, 0);
  2949. sendAndApply(&sha);
  2950. }
  2951. sendAndApply(&cs);
  2952. sendAndApply(&sm);
  2953. }
  2954. else if(message == "vcmiainur") //gives 5 archangels into each slot
  2955. {
  2956. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2957. const CCreature *archangel = VLC->creh->creatures[13];
  2958. if(!hero) return;
  2959. for(int i = 0; i < ARMY_SIZE; i++)
  2960. if(!hero->hasStackAtSlot(i))
  2961. insertNewStack(StackLocation(hero, i), archangel, 10);
  2962. }
  2963. else if(message == "vcmiangband") //gives 10 black knight into each slot
  2964. {
  2965. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2966. const CCreature *blackKnight = VLC->creh->creatures[66];
  2967. if(!hero) return;
  2968. for(int i = 0; i < ARMY_SIZE; i++)
  2969. if(!hero->hasStackAtSlot(i))
  2970. insertNewStack(StackLocation(hero, i), blackKnight, 10);
  2971. }
  2972. else if(message == "vcminoldor") //all war machines
  2973. {
  2974. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2975. if(!hero) return;
  2976. SetHeroArtifacts sha;
  2977. sha.hid = hero->id;
  2978. sha.artifacts = hero->artifacts;
  2979. sha.artifWorn = hero->artifWorn;
  2980. VLC->arth->equipArtifact(sha.artifWorn, 13, VLC->arth->artifacts[4]);
  2981. VLC->arth->equipArtifact(sha.artifWorn, 14, VLC->arth->artifacts[5]);
  2982. VLC->arth->equipArtifact(sha.artifWorn, 15, VLC->arth->artifacts[6]);
  2983. sendAndApply(&sha);
  2984. }
  2985. else if(message == "vcminahar") //1000000 movement points
  2986. {
  2987. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2988. if(!hero) return;
  2989. SetMovePoints smp;
  2990. smp.hid = hero->id;
  2991. smp.val = 1000000;
  2992. sendAndApply(&smp);
  2993. }
  2994. else if(message == "vcmiformenos") //give resources
  2995. {
  2996. SetResources sr;
  2997. sr.player = player;
  2998. sr.res = gs->getPlayer(player)->resources;
  2999. for(int i=0;i<7;i++)
  3000. sr.res[i] += 100;
  3001. sr.res[6] += 19900;
  3002. sendAndApply(&sr);
  3003. }
  3004. else if(message == "vcmieagles") //reveal FoW
  3005. {
  3006. FoWChange fc;
  3007. fc.mode = 1;
  3008. fc.player = player;
  3009. for(int i=0;i<gs->map->width;i++)
  3010. for(int j=0;j<gs->map->height;j++)
  3011. for(int k=0;k<gs->map->twoLevel+1;k++)
  3012. if(!gs->getPlayerTeam(fc.player)->fogOfWarMap[i][j][k])
  3013. fc.tiles.insert(int3(i,j,k));
  3014. sendAndApply(&fc);
  3015. }
  3016. else if(message == "vcmiglorfindel") //selected hero gains a new level
  3017. {
  3018. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3019. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  3020. }
  3021. else if(message == "vcmisilmaril") //player wins
  3022. {
  3023. gs->getPlayer(player)->enteredWinningCheatCode = 1;
  3024. checkLossVictory(player);
  3025. }
  3026. else if(message == "vcmimelkor") //player looses
  3027. {
  3028. gs->getPlayer(player)->enteredLosingCheatCode = 1;
  3029. checkLossVictory(player);
  3030. }
  3031. else if (message == "vcmiforgeofnoldorking") //hero gets all artifacts except war machines, spell scrolls and spell book
  3032. {
  3033. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3034. if(!hero) return;
  3035. SetHeroArtifacts sha;
  3036. sha.hid = hero->id;
  3037. sha.artifacts = hero->artifacts;
  3038. sha.artifWorn = hero->artifWorn;
  3039. sha.artifacts.push_back(VLC->arth->artifacts[2]); //grail
  3040. for (int g=7; g<=140; ++g)
  3041. {
  3042. sha.artifacts.push_back(VLC->arth->artifacts[g]);
  3043. }
  3044. sendAndApply(&sha);
  3045. }
  3046. else
  3047. cheated = false;
  3048. if(cheated)
  3049. {
  3050. sendAndApply(&SystemMessage(VLC->generaltexth->allTexts[260]));
  3051. }
  3052. }
  3053. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  3054. {
  3055. std::vector<ui32> ret;
  3056. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3057. {
  3058. if (NBonus::hasOfType(caster, Bonus::NEGATE_ALL_NATURAL_IMMUNITIES) ||
  3059. NBonus::hasOfType(hero2, Bonus::NEGATE_ALL_NATURAL_IMMUNITIES))
  3060. {
  3061. //don't use natural immunities when one of heroes has this bonus
  3062. BonusList bl = (*it)->getBonuses(Selector::type(Bonus::SPELL_IMMUNITY)),
  3063. b2 = (*it)->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  3064. bl.insert(bl.end(), b2.begin(), b2.end());
  3065. BOOST_FOREACH(Bonus *bb, bl)
  3066. {
  3067. if( (bb->type == Bonus::SPELL_IMMUNITY && bb->subtype == sp->id || //100% sure spell immunity
  3068. bb->type == Bonus::LEVEL_SPELL_IMMUNITY && bb->val >= sp->level) //some creature abilities have level 0
  3069. && bb->source != Bonus::CREATURE_ABILITY)
  3070. {
  3071. ret.push_back((*it)->ID);
  3072. continue;
  3073. }
  3074. }
  3075. }
  3076. else
  3077. {
  3078. if ((*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3079. || ( (*it)->hasBonusOfType(Bonus::LEVEL_SPELL_IMMUNITY) &&
  3080. (*it)->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY) >= sp->level) ) //some creature abilities have level 0
  3081. {
  3082. ret.push_back((*it)->ID);
  3083. continue;
  3084. }
  3085. }
  3086. //non-negative spells on friendly stacks should always succeed, unless immune
  3087. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  3088. continue;
  3089. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  3090. if(caster && (*it)->owner == caster->tempOwner)
  3091. bonusHero = caster;
  3092. else
  3093. bonusHero = hero2;
  3094. int prob = (*it)->valOfBonuses(Bonus::MAGIC_RESISTANCE); //probability of resistance in %
  3095. if(bonusHero)
  3096. {
  3097. //bonusHero's resistance support (secondary skils and artifacts)
  3098. prob += bonusHero->valOfBonuses(Bonus::MAGIC_RESISTANCE);
  3099. //resistance skill
  3100. prob += bonusHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 26) / 100.0f;
  3101. }
  3102. if(prob > 100) prob = 100;
  3103. if(rand()%100 < prob) //immunity from resistance
  3104. ret.push_back((*it)->ID);
  3105. }
  3106. if(sp->id == 60) //hypnotize
  3107. {
  3108. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3109. {
  3110. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3111. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  3112. >
  3113. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  3114. )
  3115. {
  3116. ret.push_back((*it)->ID);
  3117. }
  3118. }
  3119. }
  3120. return ret;
  3121. }
  3122. void CGameHandler::handleSpellCasting( int spellID, int spellLvl, int destination, ui8 casterSide, ui8 casterColor,
  3123. const CGHeroInstance * caster, const CGHeroInstance * secHero, int usedSpellPower )
  3124. {
  3125. const CSpell *spell = VLC->spellh->spells[spellID];
  3126. BattleSpellCast sc;
  3127. sc.side = casterSide;
  3128. sc.id = spellID;
  3129. sc.skill = spellLvl;
  3130. sc.tile = destination;
  3131. sc.dmgToDisplay = 0;
  3132. sc.castedByHero = (bool)caster;
  3133. //calculating affected creatures for all spells
  3134. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(spell, spellLvl, casterColor, destination);
  3135. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3136. {
  3137. sc.affectedCres.insert((*it)->ID);
  3138. }
  3139. //checking if creatures resist
  3140. sc.resisted = calculateResistedStacks(spell, caster, secHero, attackedCres);
  3141. //calculating dmg to display
  3142. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3143. {
  3144. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3145. continue;
  3146. sc.dmgToDisplay += gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3147. }
  3148. sendAndApply(&sc);
  3149. //applying effects
  3150. switch(spellID)
  3151. {
  3152. case 15: //magic arrow
  3153. case 16: //ice bolt
  3154. case 17: //lightning bolt
  3155. case 18: //implosion
  3156. case 20: //frost ring
  3157. case 21: //fireball
  3158. case 22: //inferno
  3159. case 23: //meteor shower
  3160. case 24: //death ripple
  3161. case 25: //destroy undead
  3162. case 26: //armageddon
  3163. case 77: //Thunderbolt (thunderbirds)
  3164. {
  3165. StacksInjured si;
  3166. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3167. {
  3168. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3169. continue;
  3170. BattleStackAttacked bsa;
  3171. bsa.flags |= 2;
  3172. bsa.effect = spell->mainEffectAnim;
  3173. bsa.damageAmount = gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3174. bsa.stackAttacked = (*it)->ID;
  3175. bsa.attackerID = -1;
  3176. prepareAttacked(bsa,*it);
  3177. si.stacks.push_back(bsa);
  3178. }
  3179. if(!si.stacks.empty())
  3180. sendAndApply(&si);
  3181. break;
  3182. }
  3183. case 27: //shield
  3184. case 28: //air shield
  3185. case 29: //fire shield
  3186. case 30: //protection from air
  3187. case 31: //protection from fire
  3188. case 32: //protection from water
  3189. case 33: //protection from earth
  3190. case 34: //anti-magic
  3191. case 41: //bless
  3192. case 42: //curse
  3193. case 43: //bloodlust
  3194. case 44: //precision
  3195. case 45: //weakness
  3196. case 46: //stone skin
  3197. case 47: //disrupting ray
  3198. case 48: //prayer
  3199. case 49: //mirth
  3200. case 50: //sorrow
  3201. case 51: //fortune
  3202. case 52: //misfortune
  3203. case 53: //haste
  3204. case 54: //slow
  3205. case 55: //slayer
  3206. case 56: //frenzy
  3207. case 58: //counterstrike
  3208. case 59: //berserk
  3209. case 60: //hypnotize
  3210. case 61: //forgetfulness
  3211. case 62: //blind
  3212. {
  3213. SetStackEffect sse;
  3214. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3215. {
  3216. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3217. continue;
  3218. sse.stacks.push_back((*it)->ID);
  3219. }
  3220. sse.effect.id = spellID;
  3221. sse.effect.val = spellLvl;
  3222. sse.effect.turnsRemain = gs->curB->calculateSpellDuration(spell, caster, usedSpellPower);
  3223. if(!sse.stacks.empty())
  3224. sendAndApply(&sse);
  3225. break;
  3226. }
  3227. case 63: //teleport
  3228. {
  3229. BattleStackMoved bsm;
  3230. bsm.distance = -1;
  3231. bsm.stack = gs->curB->activeStack;
  3232. bsm.ending = true;
  3233. bsm.tile = destination;
  3234. bsm.teleporting = true;
  3235. sendAndApply(&bsm);
  3236. break;
  3237. }
  3238. case 37: //cure
  3239. case 38: //resurrection
  3240. case 39: //animate dead
  3241. {
  3242. StacksHealedOrResurrected shr;
  3243. shr.lifeDrain = false;
  3244. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3245. {
  3246. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  3247. || (spellID == 39 && !(*it)->hasBonusOfType(Bonus::UNDEAD)) //we try to cast animate dead on living stack
  3248. )
  3249. continue;
  3250. StacksHealedOrResurrected::HealInfo hi;
  3251. hi.stackID = (*it)->ID;
  3252. hi.healedHP = gs->curB->calculateHealedHP(caster, spell, *it);
  3253. hi.lowLevelResurrection = spellLvl <= 1;
  3254. shr.healedStacks.push_back(hi);
  3255. }
  3256. if(!shr.healedStacks.empty())
  3257. sendAndApply(&shr);
  3258. break;
  3259. }
  3260. case 64: //remove obstacle
  3261. {
  3262. ObstaclesRemoved obr;
  3263. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  3264. {
  3265. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  3266. if(vstd::contains(blockedHexes, destination)) //this obstacle covers given hex
  3267. {
  3268. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  3269. }
  3270. }
  3271. if(!obr.obstacles.empty())
  3272. sendAndApply(&obr);
  3273. break;
  3274. }
  3275. }
  3276. }
  3277. bool CGameHandler::makeCustomAction( BattleAction &ba )
  3278. {
  3279. switch(ba.actionType)
  3280. {
  3281. case 1: //hero casts spell
  3282. {
  3283. const CGHeroInstance *h = gs->curB->heroes[ba.side];
  3284. const CGHeroInstance *secondHero = gs->curB->heroes[!ba.side];
  3285. if(!h)
  3286. {
  3287. tlog2 << "Wrong caster!\n";
  3288. return false;
  3289. }
  3290. if(ba.additionalInfo >= VLC->spellh->spells.size())
  3291. {
  3292. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  3293. return false;
  3294. }
  3295. const CSpell *s = VLC->spellh->spells[ba.additionalInfo];
  3296. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  3297. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  3298. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  3299. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  3300. || (gs->curB->castSpells[ba.side]) //spell has been cast
  3301. || (NBonus::hasOfType(secondHero, Bonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  3302. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  3303. )
  3304. {
  3305. tlog2 << "Spell cannot be cast!\n";
  3306. return false;
  3307. }
  3308. sendAndApply(&StartAction(ba)); //start spell casting
  3309. handleSpellCasting (ba.additionalInfo, skill, ba.destinationTile, ba.side, h->tempOwner, h, secondHero, h->getPrimSkillLevel(2));
  3310. sendAndApply(&EndAction());
  3311. if( !gs->curB->getStack(gs->curB->activeStack, false)->alive() )
  3312. {
  3313. battleMadeAction.setn(true);
  3314. }
  3315. checkForBattleEnd(gs->curB->stacks);
  3316. if(battleResult.get())
  3317. {
  3318. battleMadeAction.setn(true);
  3319. //battle will be ended by startBattle function
  3320. //endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  3321. }
  3322. return true;
  3323. }
  3324. }
  3325. return false;
  3326. }
  3327. void CGameHandler::handleTimeEvents()
  3328. {
  3329. gs->map->events.sort(evntCmp);
  3330. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  3331. {
  3332. CMapEvent *ev = gs->map->events.front();
  3333. for(int player = 0; player < PLAYER_LIMIT; player++)
  3334. {
  3335. PlayerState *pinfo = gs->getPlayer(player);
  3336. if( pinfo //player exists
  3337. && (ev->players & 1<<player) //event is enabled to this player
  3338. && ((ev->computerAffected && !pinfo->human)
  3339. || (ev->humanAffected && pinfo->human)
  3340. )
  3341. )
  3342. {
  3343. //give resources
  3344. SetResources sr;
  3345. sr.player = player;
  3346. sr.res = pinfo->resources;
  3347. //prepare dialog
  3348. InfoWindow iw;
  3349. iw.player = player;
  3350. iw.text << ev->message;
  3351. for (int i=0; i<ev->resources.size(); i++)
  3352. {
  3353. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  3354. {
  3355. // If removing too much resources, adjust the
  3356. // amount so the total doesn't become negative.
  3357. if (sr.res[i] + ev->resources[i] < 0)
  3358. ev->resources[i] = -sr.res[i];
  3359. if(ev->resources[i]) //if non-zero res change
  3360. {
  3361. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  3362. sr.res[i] += ev->resources[i];
  3363. }
  3364. }
  3365. }
  3366. if (iw.components.size())
  3367. {
  3368. sendAndApply(&sr); //update player resources if changed
  3369. }
  3370. sendAndApply(&iw); //show dialog
  3371. }
  3372. } //PLAYERS LOOP
  3373. if(ev->nextOccurence)
  3374. {
  3375. ev->firstOccurence += ev->nextOccurence;
  3376. gs->map->events.sort(evntCmp);
  3377. }
  3378. else
  3379. {
  3380. delete ev;
  3381. gs->map->events.pop_front();
  3382. }
  3383. }
  3384. }
  3385. void CGameHandler::handleTownEvents(CGTownInstance * town, NewTurn &n, std::map<si32, std::map<si32, si32> > &newCreas)
  3386. {
  3387. town->events.sort(evntCmp);
  3388. while(town->events.size() && town->events.front()->firstOccurence == gs->day)
  3389. {
  3390. ui8 player = town->tempOwner;
  3391. CCastleEvent *ev = town->events.front();
  3392. PlayerState *pinfo = gs->getPlayer(player);
  3393. if( pinfo //player exists
  3394. && (ev->players & 1<<player) //event is enabled to this player
  3395. && ((ev->computerAffected && !pinfo->human)
  3396. || (ev->humanAffected && pinfo->human) ) )
  3397. {
  3398. // dialog
  3399. InfoWindow iw;
  3400. iw.player = player;
  3401. iw.text << ev->message;
  3402. for (int i=0; i<ev->resources.size(); i++)
  3403. if(ev->resources[i]) //if resource had changed, we add it to the dialog
  3404. {
  3405. int was = n.res[player][i];
  3406. n.res[player][i] += ev->resources[i];
  3407. n.res[player][i] = std::max<si32>(n.res[player][i], 0);
  3408. if(pinfo->resources[i] != n.res[player][i]) //if non-zero res change
  3409. iw.components.push_back(Component(Component::RESOURCE,i,n.res[player][i]-was,0));
  3410. }
  3411. for(std::set<si32>::iterator i = ev->buildings.begin(); i!=ev->buildings.end();i++)
  3412. if ( !vstd::contains(town->builtBuildings, *i))
  3413. {
  3414. buildStructure(town->id, *i, true);
  3415. iw.components.push_back(Component(Component::BUILDING, town->subID, *i, 0));
  3416. }
  3417. for(si32 i=0;i<ev->creatures.size();i++) //creature growths
  3418. {
  3419. if(town->creatureDwelling(i) && ev->creatures[i])//there is dwelling
  3420. {
  3421. newCreas[town->id][i] += ev->creatures[i];
  3422. iw.components.push_back(Component(Component::CREATURE,
  3423. town->creatures[i].second.back(), ev->creatures[i], 0));
  3424. }
  3425. }
  3426. sendAndApply(&iw); //show dialog
  3427. }
  3428. if(ev->nextOccurence)
  3429. {
  3430. ev->firstOccurence += ev->nextOccurence;
  3431. town->events.sort(evntCmp);
  3432. }
  3433. else
  3434. {
  3435. delete ev;
  3436. town->events.pop_front();
  3437. }
  3438. }
  3439. }
  3440. bool CGameHandler::complain( const std::string &problem )
  3441. {
  3442. sendMessageToAll("Server encountered a problem: " + problem);
  3443. tlog1 << problem << std::endl;
  3444. return true;
  3445. }
  3446. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  3447. {
  3448. //TODO: write
  3449. return 0;
  3450. }
  3451. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  3452. {
  3453. ui8 player = getOwner(hid);
  3454. GarrisonDialog gd;
  3455. gd.hid = hid;
  3456. gd.objid = upobj;
  3457. {
  3458. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3459. gd.id = QID;
  3460. garrisonCallbacks[QID] = cb;
  3461. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  3462. states.addQuery(player,QID);
  3463. QID++;
  3464. gd.removableUnits = removableUnits;
  3465. sendAndApply(&gd);
  3466. }
  3467. }
  3468. void CGameHandler::showThievesGuildWindow(int requestingObjId)
  3469. {
  3470. OpenWindow ow;
  3471. ow.window = OpenWindow::THIEVES_GUILD;
  3472. ow.id1 = requestingObjId;
  3473. sendAndApply(&ow);
  3474. }
  3475. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  3476. {
  3477. if(id1 == id2)
  3478. return true;
  3479. {
  3480. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3481. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  3482. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  3483. return true;
  3484. }
  3485. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  3486. if(o1->ID == TOWNI_TYPE)
  3487. {
  3488. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  3489. if(t->visitingHero == o2 || t->garrisonHero == o2)
  3490. return true;
  3491. }
  3492. if(o2->ID == TOWNI_TYPE)
  3493. {
  3494. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  3495. if(t->visitingHero == o1 || t->garrisonHero == o1)
  3496. return true;
  3497. }
  3498. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  3499. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  3500. {
  3501. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  3502. //(to block moving stacks for free [without visiting] beteen heroes)
  3503. return true;
  3504. }
  3505. return false;
  3506. }
  3507. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  3508. {
  3509. obj->onHeroVisit(h);
  3510. }
  3511. bool CGameHandler::buildBoat( ui32 objid )
  3512. {
  3513. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  3514. if(obj->state())
  3515. {
  3516. complain("Cannot build boat in this shipyard!");
  3517. return false;
  3518. }
  3519. else if(obj->o->ID == TOWNI_TYPE
  3520. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  3521. {
  3522. complain("Cannot build boat in the town - no shipyard!");
  3523. return false;
  3524. }
  3525. //TODO use "real" cost via obj->getBoatCost
  3526. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  3527. {
  3528. complain("Not enough resources to build a boat!");
  3529. return false;
  3530. }
  3531. int3 tile = obj->bestLocation();
  3532. if(!gs->map->isInTheMap(tile))
  3533. {
  3534. complain("Cannot find appropriate tile for a boat!");
  3535. return false;
  3536. }
  3537. //take boat cost
  3538. SetResources sr;
  3539. sr.player = obj->o->tempOwner;
  3540. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  3541. sr.res[0] -= 10;
  3542. sr.res[6] -= 1000;
  3543. sendAndApply(&sr);
  3544. //create boat
  3545. NewObject no;
  3546. no.ID = 8;
  3547. no.subID = obj->getBoatType();
  3548. no.pos = tile + int3(1,0,0);
  3549. sendAndApply(&no);
  3550. return true;
  3551. }
  3552. void CGameHandler::engageIntoBattle( ui8 player )
  3553. {
  3554. if(vstd::contains(states.players, player))
  3555. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  3556. //notify interfaces
  3557. PlayerBlocked pb;
  3558. pb.player = player;
  3559. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  3560. sendAndApply(&pb);
  3561. }
  3562. void CGameHandler::winLoseHandle(ui8 players )
  3563. {
  3564. for(size_t i = 0; i < PLAYER_LIMIT; i++)
  3565. {
  3566. if(players & 1<<i && gs->getPlayer(i))
  3567. {
  3568. checkLossVictory(i);
  3569. }
  3570. }
  3571. }
  3572. void CGameHandler::checkLossVictory( ui8 player )
  3573. {
  3574. const PlayerState *p = gs->getPlayer(player);
  3575. if(p->status) //player already won / lost
  3576. return;
  3577. int loss = gs->lossCheck(player);
  3578. int vic = gs->victoryCheck(player);
  3579. if(!loss && !vic)
  3580. return;
  3581. InfoWindow iw;
  3582. getLossVicMessage(player, vic ? vic : loss , vic, iw);
  3583. sendAndApply(&iw);
  3584. PlayerEndsGame peg;
  3585. peg.player = player;
  3586. peg.victory = vic;
  3587. sendAndApply(&peg);
  3588. if(vic > 0) //one player won -> all enemies lost
  3589. {
  3590. iw.text.localStrings.front().second++; //message about losing because enemy won first is just after victory message
  3591. for (bmap<ui8,PlayerState>::const_iterator i = gs->players.begin(); i!=gs->players.end(); i++)
  3592. {
  3593. if(i->first < PLAYER_LIMIT && i->first != player)//FIXME: skip already eliminated players?
  3594. {
  3595. iw.player = i->first;
  3596. sendAndApply(&iw);
  3597. peg.player = i->first;
  3598. peg.victory = gameState()->getPlayerRelations(player, i->first) == 1; // ally of winner
  3599. sendAndApply(&peg);
  3600. }
  3601. }
  3602. }
  3603. else //player lost -> all his objects become unflagged (neutral)
  3604. {
  3605. std::vector<ConstTransitivePtr<CGHeroInstance> > hlp = p->heroes;
  3606. for (std::vector<ConstTransitivePtr<CGHeroInstance> >::const_iterator i = hlp.begin(); i != hlp.end(); i++) //eliminate heroes
  3607. removeObject((*i)->id);
  3608. for (std::vector<ConstTransitivePtr<CGObjectInstance> >::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  3609. {
  3610. if(*i && (*i)->tempOwner == player)
  3611. setOwner((**i).id,NEUTRAL_PLAYER);
  3612. }
  3613. //eliminating one player may cause victory of another:
  3614. winLoseHandle(ALL_PLAYERS & ~(1<<player));
  3615. }
  3616. if(vic)
  3617. {
  3618. end2 = true;
  3619. if(gs->campaign)
  3620. {
  3621. std::vector<CGHeroInstance *> hes;
  3622. BOOST_FOREACH(CGHeroInstance * ghi, gs->map->heroes)
  3623. {
  3624. if (ghi->tempOwner == 0 /*TODO: insert human player's color*/)
  3625. {
  3626. hes.push_back(ghi);
  3627. }
  3628. }
  3629. gs->campaign->mapConquered(hes);
  3630. UpdateCampaignState ucs;
  3631. ucs.camp = gs->campaign;
  3632. sendAndApply(&ucs);
  3633. }
  3634. }
  3635. }
  3636. void CGameHandler::getLossVicMessage( ui8 player, ui8 standard, bool victory, InfoWindow &out ) const
  3637. {
  3638. // const PlayerState *p = gs->getPlayer(player);
  3639. // if(!p->human)
  3640. // return; //AI doesn't need text info of loss
  3641. out.player = player;
  3642. if(victory)
  3643. {
  3644. if(standard < 0) //not std loss
  3645. {
  3646. switch(gs->map->victoryCondition.condition)
  3647. {
  3648. case artifact:
  3649. out.text.addTxt(MetaString::GENERAL_TXT, 280); //Congratulations! You have found the %s, and can claim victory!
  3650. out.text.addReplacement(MetaString::ART_NAMES,gs->map->victoryCondition.ID); //artifact name
  3651. break;
  3652. case gatherTroop:
  3653. out.text.addTxt(MetaString::GENERAL_TXT, 276); //Congratulations! You have over %d %s in your armies. Your enemies have no choice but to bow down before your power!
  3654. out.text.addReplacement(gs->map->victoryCondition.count);
  3655. out.text.addReplacement(MetaString::CRE_PL_NAMES, gs->map->victoryCondition.ID);
  3656. break;
  3657. case gatherResource:
  3658. out.text.addTxt(MetaString::GENERAL_TXT, 278); //Congratulations! You have collected over %d %s in your treasury. Victory is yours!
  3659. out.text.addReplacement(gs->map->victoryCondition.count);
  3660. out.text.addReplacement(MetaString::RES_NAMES, gs->map->victoryCondition.ID);
  3661. break;
  3662. case buildCity:
  3663. out.text.addTxt(MetaString::GENERAL_TXT, 282); //Congratulations! You have successfully upgraded your town, and can claim victory!
  3664. break;
  3665. case buildGrail:
  3666. out.text.addTxt(MetaString::GENERAL_TXT, 284); //Congratulations! You have constructed a permanent home for the Grail, and can claim victory!
  3667. break;
  3668. case beatHero:
  3669. {
  3670. out.text.addTxt(MetaString::GENERAL_TXT, 252); //Congratulations! You have completed your quest to defeat the enemy hero %s. Victory is yours!
  3671. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->victoryCondition.obj);
  3672. assert(h);
  3673. out.text.addReplacement(h->name);
  3674. }
  3675. break;
  3676. case captureCity:
  3677. {
  3678. out.text.addTxt(MetaString::GENERAL_TXT, 249); //Congratulations! You captured %s, and are victorious!
  3679. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->victoryCondition.obj);
  3680. assert(t);
  3681. out.text.addReplacement(t->name);
  3682. }
  3683. break;
  3684. case beatMonster:
  3685. out.text.addTxt(MetaString::GENERAL_TXT, 286); //Congratulations! You have completed your quest to kill the fearsome beast, and can claim victory!
  3686. break;
  3687. case takeDwellings:
  3688. out.text.addTxt(MetaString::GENERAL_TXT, 288); //Congratulations! Your flag flies on the dwelling of every creature. Victory is yours!
  3689. break;
  3690. case takeMines:
  3691. out.text.addTxt(MetaString::GENERAL_TXT, 290); //Congratulations! Your flag flies on every mine. Victory is yours!
  3692. break;
  3693. case transportItem:
  3694. out.text.addTxt(MetaString::GENERAL_TXT, 292); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  3695. break;
  3696. }
  3697. }
  3698. else
  3699. {
  3700. out.text.addTxt(MetaString::GENERAL_TXT, 659); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  3701. }
  3702. }
  3703. else
  3704. {
  3705. if(standard < 0) //not std loss
  3706. {
  3707. switch(gs->map->lossCondition.typeOfLossCon)
  3708. {
  3709. case lossCastle:
  3710. {
  3711. out.text.addTxt(MetaString::GENERAL_TXT, 251); //The town of %s has fallen - all is lost!
  3712. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->lossCondition.obj);
  3713. assert(t);
  3714. out.text.addReplacement(t->name);
  3715. }
  3716. break;
  3717. case lossHero:
  3718. {
  3719. out.text.addTxt(MetaString::GENERAL_TXT, 253); //The hero, %s, has suffered defeat - your quest is over!
  3720. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->lossCondition.obj);
  3721. assert(h);
  3722. out.text.addReplacement(h->name);
  3723. }
  3724. break;
  3725. case timeExpires:
  3726. out.text.addTxt(MetaString::GENERAL_TXT, 254); //Alas, time has run out on your quest. All is lost.
  3727. break;
  3728. }
  3729. }
  3730. else if(standard == 2)
  3731. {
  3732. out.text.addTxt(MetaString::GENERAL_TXT, 7);//%s, your heroes abandon you, and you are banished from this land.
  3733. out.text.addReplacement(MetaString::COLOR, player);
  3734. out.components.push_back(Component(Component::FLAG,player,0,0));
  3735. }
  3736. else //lost all towns and heroes
  3737. {
  3738. out.text.addTxt(MetaString::GENERAL_TXT, 660); //All your forces have been defeated, and you are banished from this land!
  3739. }
  3740. }
  3741. }
  3742. bool CGameHandler::dig( const CGHeroInstance *h )
  3743. {
  3744. for (std::vector<ConstTransitivePtr<CGObjectInstance> >::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  3745. {
  3746. if(*i && (*i)->ID == 124 && (*i)->pos == h->getPosition())
  3747. {
  3748. complain("Cannot dig - there is already a hole under the hero!");
  3749. return false;
  3750. }
  3751. }
  3752. NewObject no;
  3753. no.ID = 124;
  3754. no.pos = h->getPosition();
  3755. no.subID = getTile(no.pos)->tertype;
  3756. if(no.subID >= 8) //no digging on water / rock
  3757. {
  3758. complain("Cannot dig - wrong terrain type!");
  3759. return false;
  3760. }
  3761. sendAndApply(&no);
  3762. SetMovePoints smp;
  3763. smp.hid = h->id;
  3764. smp.val = 0;
  3765. sendAndApply(&smp);
  3766. InfoWindow iw;
  3767. iw.player = h->tempOwner;
  3768. if(gs->map->grailPos == h->getPosition())
  3769. {
  3770. iw.text.addTxt(MetaString::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  3771. iw.text.addTxt(MetaString::ART_NAMES, 2);
  3772. iw.soundID = soundBase::ULTIMATEARTIFACT;
  3773. giveHeroNewArtifact(h, VLC->arth->artifacts[2], -1); //give grail
  3774. sendAndApply(&iw);
  3775. iw.text.clear();
  3776. iw.text.addTxt(MetaString::ART_DESCR, 2);
  3777. sendAndApply(&iw);
  3778. }
  3779. else
  3780. {
  3781. iw.text.addTxt(MetaString::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  3782. iw.soundID = soundBase::Dig;
  3783. sendAndApply(&iw);
  3784. }
  3785. return true;
  3786. }
  3787. void CGameHandler::handleAfterAttackCasting( const BattleAttack & bat )
  3788. {
  3789. const CStack * attacker = gs->curB->getStack(bat.stackAttacking);
  3790. if( attacker->hasBonusOfType(Bonus::SPELL_AFTER_ATTACK) )
  3791. {
  3792. BOOST_FOREACH(const Bonus *sf, attacker->getBonuses(Selector::type(Bonus::SPELL_AFTER_ATTACK)))
  3793. {
  3794. if (sf->type == Bonus::SPELL_AFTER_ATTACK)
  3795. {
  3796. const CStack * oneOfAttacked = NULL;
  3797. for(int g=0; g<bat.bsa.size(); ++g)
  3798. {
  3799. if (bat.bsa[g].newAmount > 0)
  3800. {
  3801. oneOfAttacked = gs->curB->getStack(bat.bsa[g].stackAttacked);
  3802. break;
  3803. }
  3804. }
  3805. if(oneOfAttacked == NULL) //all attacked creatures have been killed
  3806. return;
  3807. int spellID = sf->subtype;
  3808. int spellLevel = sf->val;
  3809. int chance = sf->additionalInfo % 1000;
  3810. //int meleeRanged = sf->additionalInfo / 1000;
  3811. int destination = oneOfAttacked->position;
  3812. //check if spell should be casted (probability handling)
  3813. if( rand()%100 >= chance )
  3814. continue;
  3815. //casting
  3816. handleSpellCasting(spellID, spellLevel, destination, !attacker->attackerOwned, attacker->owner, NULL, NULL, attacker->count);
  3817. }
  3818. }
  3819. }
  3820. }
  3821. bool CGameHandler::castSpell(const CGHeroInstance *h, int spellID, const int3 &pos)
  3822. {
  3823. const CSpell *s = VLC->spellh->spells[spellID];
  3824. int cost = h->getSpellCost(s);
  3825. int schoolLevel = h->getSpellSchoolLevel(s);
  3826. if(!h->canCastThisSpell(s))
  3827. COMPLAIN_RET("Hero cannot cast this spell!");
  3828. if(h->mana < cost)
  3829. COMPLAIN_RET("Hero doesn't have enough spell points to cast this spell!");
  3830. if(s->combatSpell)
  3831. COMPLAIN_RET("This function can be used only for adventure map spells!");
  3832. AdvmapSpellCast asc;
  3833. asc.caster = h;
  3834. asc.spellID = spellID;
  3835. sendAndApply(&asc);
  3836. using namespace Spells;
  3837. switch(spellID)
  3838. {
  3839. case SUMMON_BOAT: //Summon Boat
  3840. {
  3841. //check if spell works at all
  3842. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  3843. {
  3844. InfoWindow iw;
  3845. iw.player = h->tempOwner;
  3846. iw.text.addTxt(MetaString::GENERAL_TXT, 336); //%s tried to summon a boat, but failed.
  3847. iw.text.addReplacement(h->name);
  3848. sendAndApply(&iw);
  3849. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  3850. }
  3851. //try to find unoccupied boat to summon
  3852. const CGBoat *nearest = NULL;
  3853. double dist = 0;
  3854. int3 summonPos = h->bestLocation();
  3855. if(summonPos.x < 0)
  3856. COMPLAIN_RET("There is no water tile available!");
  3857. BOOST_FOREACH(const CGObjectInstance *obj, gs->map->objects)
  3858. {
  3859. if(obj && obj->ID == 8)
  3860. {
  3861. const CGBoat *b = static_cast<const CGBoat*>(obj);
  3862. if(b->hero) continue; //we're looking for unoccupied boat
  3863. double nDist = distance(b->pos, h->getPosition());
  3864. if(!nearest || nDist < dist) //it's first boat or closer than previous
  3865. {
  3866. nearest = b;
  3867. dist = nDist;
  3868. }
  3869. }
  3870. }
  3871. if(nearest) //we found boat to summon
  3872. {
  3873. ChangeObjPos cop;
  3874. cop.objid = nearest->id;
  3875. cop.nPos = summonPos + int3(1,0,0);;
  3876. cop.flags = 1;
  3877. sendAndApply(&cop);
  3878. }
  3879. else if(schoolLevel < 2) //none or basic level -> cannot create boat :(
  3880. {
  3881. InfoWindow iw;
  3882. iw.player = h->tempOwner;
  3883. iw.text.addTxt(MetaString::GENERAL_TXT, 335); //There are no boats to summon.
  3884. sendAndApply(&iw);
  3885. }
  3886. else //create boat
  3887. {
  3888. NewObject no;
  3889. no.ID = 8;
  3890. no.subID = h->getBoatType();
  3891. no.pos = summonPos + int3(1,0,0);;
  3892. sendAndApply(&no);
  3893. }
  3894. break;
  3895. }
  3896. case SCUTTLE_BOAT: //Scuttle Boat
  3897. {
  3898. //check if spell works at all
  3899. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  3900. {
  3901. InfoWindow iw;
  3902. iw.player = h->tempOwner;
  3903. iw.text.addTxt(MetaString::GENERAL_TXT, 337); //%s tried to scuttle the boat, but failed
  3904. iw.text.addReplacement(h->name);
  3905. sendAndApply(&iw);
  3906. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  3907. }
  3908. if(!gs->map->isInTheMap(pos))
  3909. COMPLAIN_RET("Invalid dst tile for scuttle!");
  3910. //TODO: test range, visibility
  3911. const TerrainTile *t = &gs->map->getTile(pos);
  3912. if(!t->visitableObjects.size() || t->visitableObjects.back()->ID != 8)
  3913. COMPLAIN_RET("There is no boat to scuttle!");
  3914. RemoveObject ro;
  3915. ro.id = t->visitableObjects.back()->id;
  3916. sendAndApply(&ro);
  3917. break;
  3918. }
  3919. case DIMENSION_DOOR: //Dimension Door
  3920. {
  3921. const TerrainTile *dest = getTile(pos);
  3922. const TerrainTile *curr = getTile(h->getSightCenter());
  3923. if(!dest)
  3924. COMPLAIN_RET("Destination tile doesn't exist!");
  3925. if(!h->movement)
  3926. COMPLAIN_RET("Hero needs movement points to cast Dimension Door!");
  3927. if(h->getBonusesCount(Bonus::CASTED_SPELL, Spells::DIMENSION_DOOR) >= s->powers[schoolLevel]) //limit casts per turn
  3928. {
  3929. InfoWindow iw;
  3930. iw.player = h->tempOwner;
  3931. iw.text.addTxt(MetaString::GENERAL_TXT, 338); //%s is not skilled enough to cast this spell again today.
  3932. iw.text.addReplacement(h->name);
  3933. sendAndApply(&iw);
  3934. break;
  3935. }
  3936. GiveBonus gb;
  3937. gb.id = h->id;
  3938. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::NONE, Bonus::CASTED_SPELL, 0, Spells::DIMENSION_DOOR);
  3939. sendAndApply(&gb);
  3940. if(!dest->isClear(curr)) //wrong dest tile
  3941. {
  3942. InfoWindow iw;
  3943. iw.player = h->tempOwner;
  3944. iw.text.addTxt(MetaString::GENERAL_TXT, 70); //Dimension Door failed!
  3945. sendAndApply(&iw);
  3946. break;
  3947. }
  3948. //we need obtain guard pos before moving hero, otherwise we get nothing, because tile will be "unguarded" by hero
  3949. int3 guardPos = gs->guardingCreaturePosition(pos);
  3950. TryMoveHero tmh;
  3951. tmh.id = h->id;
  3952. tmh.movePoints = std::max<int>(0, h->movement - 300);
  3953. tmh.result = TryMoveHero::TELEPORTATION;
  3954. tmh.start = h->pos;
  3955. tmh.end = pos + h->getVisitableOffset();
  3956. getTilesInRange(tmh.fowRevealed, pos, h->getSightRadious(), h->tempOwner,1);
  3957. sendAndApply(&tmh);
  3958. tryAttackingGuard(guardPos, h);
  3959. }
  3960. break;
  3961. case FLY: //Fly
  3962. {
  3963. int subtype = schoolLevel >= 2 ? 1 : 2; //adv or expert
  3964. GiveBonus gb;
  3965. gb.id = h->id;
  3966. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::FLYING_MOVEMENT, Bonus::CASTED_SPELL, 0, Spells::FLY, subtype);
  3967. sendAndApply(&gb);
  3968. }
  3969. break;
  3970. case WATER_WALK: //Water Walk
  3971. {
  3972. int subtype = schoolLevel >= 2 ? 1 : 2; //adv or expert
  3973. GiveBonus gb;
  3974. gb.id = h->id;
  3975. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::WATER_WALKING, Bonus::CASTED_SPELL, 0, Spells::FLY, subtype);
  3976. sendAndApply(&gb);
  3977. }
  3978. break;
  3979. case TOWN_PORTAL: //Town Portal
  3980. {
  3981. //TODO: check if given position is valid
  3982. moveHero(h->id,pos,1);
  3983. }
  3984. break;
  3985. case VISIONS: //Visions
  3986. case VIEW_EARTH: //View Earth
  3987. case DISGUISE: //Disguise
  3988. case VIEW_AIR: //View Air
  3989. default:
  3990. COMPLAIN_RET("This spell is not implemented yet!");
  3991. break;
  3992. }
  3993. SetMana sm;
  3994. sm.hid = h->id;
  3995. sm.val = h->mana - cost;
  3996. sendAndApply(&sm);
  3997. return true;
  3998. }
  3999. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  4000. {
  4001. //to prevent self-visiting heroes on space press
  4002. if(t.visitableObjects.back() != h)
  4003. objectVisited(t.visitableObjects.back(), h);
  4004. else if(t.visitableObjects.size() > 1)
  4005. objectVisited(*(t.visitableObjects.end()-2),h);
  4006. }
  4007. bool CGameHandler::tryAttackingGuard(const int3 &guardPos, const CGHeroInstance * h)
  4008. {
  4009. if(!gs->map->isInTheMap(guardPos))
  4010. return false;
  4011. const TerrainTile &guardTile = gs->map->terrain[guardPos.x][guardPos.y][guardPos.z];
  4012. objectVisited(guardTile.visitableObjects.back(), h);
  4013. visitObjectAfterVictory = true;
  4014. return true;
  4015. }
  4016. bool CGameHandler::sacrificeCreatures(const IMarket *market, const CGHeroInstance *hero, TSlot slot, ui32 count)
  4017. {
  4018. int oldCount = hero->getStackCount(slot);
  4019. if(oldCount < count)
  4020. COMPLAIN_RET("Not enough creatures to sacrifice!")
  4021. else if(oldCount == count && hero->Slots().size() == 1 && hero->needsLastStack())
  4022. COMPLAIN_RET("Cannot sacrifice last creature!");
  4023. int crid = hero->getStack(slot).type->idNumber;
  4024. changeStackCount(StackLocation(hero, slot), -count);
  4025. int dump, exp;
  4026. market->getOffer(crid, 0, dump, exp, CREATURE_EXP);
  4027. exp *= count;
  4028. changePrimSkill(hero->id, 4, exp*(100+hero->getSecSkillLevel(CGHeroInstance::LEARNING)*5)/100.0f);
  4029. return true;
  4030. }
  4031. bool CGameHandler::sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, int slot)
  4032. {
  4033. ArtifactLocation al(hero, slot);
  4034. const CArtifactInstance *a = al.getArt();
  4035. if(!a)
  4036. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  4037. int dmp, expToGive;
  4038. m->getOffer(hero->getArtTypeId(slot), 0, dmp, expToGive, ARTIFACT_EXP);
  4039. removeArtifact(al);
  4040. changePrimSkill(hero->id, 4, expToGive);
  4041. return true;
  4042. }
  4043. void CGameHandler::makeStackDoNothing(const CStack * next)
  4044. {
  4045. BattleAction doNothing;
  4046. doNothing.actionType = 0;
  4047. doNothing.additionalInfo = 0;
  4048. doNothing.destinationTile = -1;
  4049. doNothing.side = !next->attackerOwned;
  4050. doNothing.stackNumber = next->ID;
  4051. sendAndApply(&StartAction(doNothing));
  4052. sendAndApply(&EndAction());
  4053. }
  4054. bool CGameHandler::insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count)
  4055. {
  4056. if(sl.army->hasStackAtSlot(sl.slot))
  4057. COMPLAIN_RET("Slot is already taken!");
  4058. InsertNewStack ins;
  4059. ins.sl = sl;
  4060. ins.stack = CStackBasicDescriptor(c, count);
  4061. sendAndApply(&ins);
  4062. return true;
  4063. }
  4064. bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval/* = false*/)
  4065. {
  4066. if(!sl.army->hasStackAtSlot(sl.slot))
  4067. COMPLAIN_RET("Cannot find a stack to erase");
  4068. if(sl.army->Slots().size() == 1 //from the last stack
  4069. && sl.army->needsLastStack() //that must be left
  4070. && !forceRemoval) //ignore above conditions if we are forcing removal
  4071. {
  4072. COMPLAIN_RET("Cannot erase the last stack!");
  4073. }
  4074. EraseStack es;
  4075. es.sl = sl;
  4076. sendAndApply(&es);
  4077. return true;
  4078. }
  4079. bool CGameHandler::changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue /*= false*/)
  4080. {
  4081. TQuantity currentCount = sl.army->getStackCount(sl.slot);
  4082. if(absoluteValue && count < 0
  4083. || !absoluteValue && -count > currentCount)
  4084. {
  4085. COMPLAIN_RET("Cannot take more stacks than present!");
  4086. }
  4087. if(currentCount == -count && !absoluteValue
  4088. || !count && absoluteValue)
  4089. {
  4090. eraseStack(sl);
  4091. }
  4092. else
  4093. {
  4094. ChangeStackCount csc;
  4095. csc.sl = sl;
  4096. csc.count = count;
  4097. csc.absoluteValue = absoluteValue;
  4098. sendAndApply(&csc);
  4099. }
  4100. return true;
  4101. }
  4102. bool CGameHandler::addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count)
  4103. {
  4104. const CCreature *slotC = sl.army->getCreature(sl.slot);
  4105. if(!slotC) //slot is empty
  4106. insertNewStack(sl, c, count);
  4107. else if(c == slotC)
  4108. changeStackCount(sl, count);
  4109. else
  4110. {
  4111. COMPLAIN_RET("Cannot add " + c->namePl + " to slot " + boost::lexical_cast<std::string>(sl.slot) + "!");
  4112. }
  4113. return true;
  4114. }
  4115. void CGameHandler::tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging)
  4116. {
  4117. if(!dst->canBeMergedWith(*src, allowMerging))
  4118. {
  4119. boost::function<void()> removeOrNot = 0;
  4120. if(removeObjWhenFinished)
  4121. removeOrNot = boost::bind(&IGameCallback::removeObject,this,src->id);
  4122. showGarrisonDialog(src->id, dst->id, true, removeOrNot); //show garrison window and optionally remove ourselves from map when player ends
  4123. }
  4124. else //merge
  4125. {
  4126. moveArmy(src, dst, allowMerging);
  4127. if(removeObjWhenFinished)
  4128. removeObject(src->id);
  4129. }
  4130. }
  4131. bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count)
  4132. {
  4133. if(!src.army->hasStackAtSlot(src.slot))
  4134. COMPLAIN_RET("No stack to move!");
  4135. if(dst.army->hasStackAtSlot(dst.slot) && dst.army->getCreature(dst.slot) != src.army->getCreature(src.slot))
  4136. COMPLAIN_RET("Cannot move: stack of different type at destination pos!");
  4137. if(count == -1)
  4138. {
  4139. count = src.army->getStackCount(src.slot);
  4140. }
  4141. if(src.army != dst.army //moving away
  4142. && count == src.army->getStackCount(src.slot) //all creatures
  4143. && src.army->Slots().size() == 1 //from the last stack
  4144. && src.army->needsLastStack()) //that must be left
  4145. {
  4146. COMPLAIN_RET("Cannot move away the alst creature!");
  4147. }
  4148. RebalanceStacks rs;
  4149. rs.src = src;
  4150. rs.dst = dst;
  4151. rs.count = count;
  4152. sendAndApply(&rs);
  4153. return true;
  4154. }
  4155. bool CGameHandler::swapStacks(const StackLocation &sl1, const StackLocation &sl2)
  4156. {
  4157. if(!sl1.army->hasStackAtSlot(sl1.slot))
  4158. return moveStack(sl2, sl1);
  4159. else if(!sl2.army->hasStackAtSlot(sl2.slot))
  4160. return moveStack(sl1, sl2);
  4161. else
  4162. {
  4163. SwapStacks ss;
  4164. ss.sl1 = sl1;
  4165. ss.sl2 = sl2;
  4166. sendAndApply(&ss);
  4167. return true;
  4168. }
  4169. }
  4170. void CGameHandler::runBattle()
  4171. {
  4172. assert(gs->curB);
  4173. //TODO: pre-tactic stuff, call scripts etc.
  4174. //tactic round
  4175. {
  4176. if( (gs->curB->heroes[0] && gs->curB->heroes[0]->getSecSkillLevel(CGHeroInstance::TACTICS)>0) ||
  4177. ( gs->curB->heroes[1] && gs->curB->heroes[1]->getSecSkillLevel(CGHeroInstance::TACTICS)>0) )//someone has tactics
  4178. {
  4179. //TODO: tactic round (round -1)
  4180. NEW_ROUND;
  4181. }
  4182. }
  4183. //spells opening battle
  4184. if (gs->curB->heroes[0] && gs->curB->heroes[0]->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL))
  4185. {
  4186. BonusList bl;
  4187. gs->curB->heroes[0]->getBonuses(bl, Selector::type(Bonus::OPENING_BATTLE_SPELL));
  4188. BOOST_FOREACH (Bonus *b, bl)
  4189. {
  4190. handleSpellCasting(b->subtype, 3, -1, 0, gs->curB->heroes[0]->tempOwner, NULL, gs->curB->heroes[1], b->val);
  4191. }
  4192. }
  4193. if (gs->curB->heroes[1] && gs->curB->heroes[1]->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL))
  4194. {
  4195. BonusList bl;
  4196. gs->curB->heroes[1]->getBonuses(bl, Selector::type(Bonus::OPENING_BATTLE_SPELL));
  4197. BOOST_FOREACH (Bonus *b, bl)
  4198. {
  4199. handleSpellCasting(b->subtype, 3, -1, 1, gs->curB->heroes[1]->tempOwner, NULL, gs->curB->heroes[0], b->val);
  4200. }
  4201. }
  4202. //main loop
  4203. while(!battleResult.get()) //till the end of the battle ;]
  4204. {
  4205. NEW_ROUND;
  4206. std::vector<CStack*> & stacks = (gs->curB->stacks);
  4207. const BattleInfo & curB = *gs->curB;
  4208. //stack loop
  4209. const CStack *next;
  4210. while(!battleResult.get() && (next = curB.getNextStack()) && next->willMove())
  4211. {
  4212. //check for bad morale => freeze
  4213. int nextStackMorale = next->MoraleVal();
  4214. if( nextStackMorale < 0 &&
  4215. !(NBonus::hasOfType(gs->curB->heroes[0], Bonus::BLOCK_MORALE) || NBonus::hasOfType(gs->curB->heroes[1], Bonus::BLOCK_MORALE)) //checking if gs->curB->heroes have (or don't have) morale blocking bonuses)
  4216. )
  4217. {
  4218. if( rand()%24 < -2 * nextStackMorale)
  4219. {
  4220. //unit loses its turn - empty freeze action
  4221. BattleAction ba;
  4222. ba.actionType = BattleAction::BAD_MORALE;
  4223. ba.additionalInfo = 1;
  4224. ba.side = !next->attackerOwned;
  4225. ba.stackNumber = next->ID;
  4226. sendAndApply(&StartAction(ba));
  4227. sendAndApply(&EndAction());
  4228. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  4229. continue;
  4230. }
  4231. }
  4232. if(next->hasBonusOfType(Bonus::ATTACKS_NEAREST_CREATURE)) //while in berserk
  4233. {
  4234. std::pair<const CStack *, int> attackInfo = curB.getNearestStack(next, boost::logic::indeterminate);
  4235. if(attackInfo.first != NULL)
  4236. {
  4237. BattleAction attack;
  4238. attack.actionType = BattleAction::WALK_AND_ATTACK;
  4239. attack.side = !next->attackerOwned;
  4240. attack.stackNumber = next->ID;
  4241. attack.additionalInfo = attackInfo.first->position;
  4242. attack.destinationTile = attackInfo.second;
  4243. makeBattleAction(attack);
  4244. checkForBattleEnd(stacks);
  4245. }
  4246. else
  4247. {
  4248. makeStackDoNothing(next);
  4249. }
  4250. continue;
  4251. }
  4252. const CGHeroInstance * curOwner = gs->battleGetOwner(next->ID);
  4253. if( (next->position < 0 && (!curOwner || curOwner->getSecSkillLevel(CGHeroInstance::BALLISTICS) == 0)) //arrow turret, hero has no ballistics
  4254. || (next->getCreature()->idNumber == 146 && (!curOwner || curOwner->getSecSkillLevel(CGHeroInstance::ARTILLERY) == 0))) //ballista, hero has no artillery
  4255. {
  4256. BattleAction attack;
  4257. attack.actionType = BattleAction::SHOOT;
  4258. attack.side = !next->attackerOwned;
  4259. attack.stackNumber = next->ID;
  4260. for(int g=0; g<gs->curB->stacks.size(); ++g)
  4261. {
  4262. if(gs->curB->stacks[g]->owner != next->owner && gs->curB->stacks[g]->alive())
  4263. {
  4264. attack.destinationTile = gs->curB->stacks[g]->position;
  4265. break;
  4266. }
  4267. }
  4268. makeBattleAction(attack);
  4269. checkForBattleEnd(stacks);
  4270. continue;
  4271. }
  4272. if(next->getCreature()->idNumber == 145 && (!curOwner || curOwner->getSecSkillLevel(CGHeroInstance::BALLISTICS) == 0)) //catapult, hero has no ballistics
  4273. {
  4274. BattleAction attack;
  4275. static const int wallHexes[] = {50, 183, 182, 130, 62, 29, 12, 95};
  4276. attack.destinationTile = wallHexes[ rand()%ARRAY_COUNT(wallHexes) ];
  4277. attack.actionType = BattleAction::CATAPULT;
  4278. attack.additionalInfo = 0;
  4279. attack.side = !next->attackerOwned;
  4280. attack.stackNumber = next->ID;
  4281. makeBattleAction(attack);
  4282. continue;
  4283. }
  4284. if(next->getCreature()->idNumber == 147 && (!curOwner || curOwner->getSecSkillLevel(CGHeroInstance::FIRST_AID) == 0)) //first aid tent, hero has no first aid
  4285. {
  4286. BattleAction heal;
  4287. std::vector< const CStack * > possibleStacks;
  4288. for (int v=0; v<gs->curB->stacks.size(); ++v)
  4289. {
  4290. const CStack * cstack = gs->curB->stacks[v];
  4291. if (cstack->owner == next->owner && cstack->firstHPleft < cstack->MaxHealth() && cstack->alive()) //it's friendly and not fully healthy
  4292. {
  4293. possibleStacks.push_back(cstack);
  4294. }
  4295. }
  4296. if(possibleStacks.size() == 0)
  4297. {
  4298. //nothing to heal
  4299. makeStackDoNothing(next);
  4300. continue;
  4301. }
  4302. else
  4303. {
  4304. //heal random creature
  4305. const CStack * toBeHealed = possibleStacks[ rand()%possibleStacks.size() ];
  4306. heal.actionType = BattleAction::STACK_HEAL;
  4307. heal.additionalInfo = 0;
  4308. heal.destinationTile = toBeHealed->position;
  4309. heal.side = !next->attackerOwned;
  4310. heal.stackNumber = next->ID;
  4311. makeBattleAction(heal);
  4312. }
  4313. continue;
  4314. }
  4315. int numberOfAsks = 1;
  4316. bool breakOuter = false;
  4317. do
  4318. {//ask interface and wait for answer
  4319. if(!battleResult.get())
  4320. {
  4321. BattleSetActiveStack sas;
  4322. sas.stack = next->ID;
  4323. sendAndApply(&sas);
  4324. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  4325. while(next->alive() && (!battleMadeAction.data && !battleResult.get())) //active stack hasn't made its action and battle is still going
  4326. battleMadeAction.cond.wait(lock);
  4327. battleMadeAction.data = false;
  4328. }
  4329. if(battleResult.get()) //don't touch it, battle could be finished while waiting got action
  4330. {
  4331. breakOuter = true;
  4332. break;
  4333. }
  4334. //we're after action, all results applied
  4335. checkForBattleEnd(stacks); //check if this action ended the battle
  4336. //check for good morale
  4337. nextStackMorale = next->MoraleVal();
  4338. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  4339. && !vstd::contains(next->state,DEFENDING)
  4340. && !vstd::contains(next->state,WAITING)
  4341. && next->alive()
  4342. && nextStackMorale > 0
  4343. && !(NBonus::hasOfType(gs->curB->heroes[0], Bonus::BLOCK_MORALE) || NBonus::hasOfType(gs->curB->heroes[1], Bonus::BLOCK_MORALE)) //checking if gs->curB->heroes have (or don't have) morale blocking bonuses
  4344. )
  4345. {
  4346. if(rand()%24 < nextStackMorale) //this stack hasn't got morale this turn
  4347. ++numberOfAsks; //move this stack once more
  4348. }
  4349. --numberOfAsks;
  4350. } while (numberOfAsks > 0);
  4351. if (breakOuter)
  4352. {
  4353. break;
  4354. }
  4355. }
  4356. }
  4357. endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  4358. }
  4359. void CGameHandler::giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, int pos)
  4360. {
  4361. assert(a->artType);
  4362. ArtifactLocation al;
  4363. al.hero = h;
  4364. int slot = -1;
  4365. if(pos < 0)
  4366. {
  4367. if(pos == -2)
  4368. slot = a->firstAvailableSlot(h);
  4369. else
  4370. slot = a->firstBackpackSlot(h);
  4371. }
  4372. else
  4373. {
  4374. slot = pos;
  4375. }
  4376. al.slot = slot;
  4377. if(slot < 0 || !a->canBePutAt(al))
  4378. {
  4379. complain("Cannot put artifact in that slot!");
  4380. return;
  4381. }
  4382. putArtifact(al, a);
  4383. }
  4384. void CGameHandler::putArtifact(const ArtifactLocation &al, const CArtifactInstance *a)
  4385. {
  4386. PutArtifact pa;
  4387. pa.art = a;
  4388. pa.al = al;
  4389. sendAndApply(&pa);
  4390. }
  4391. void CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2)
  4392. {
  4393. MoveArtifact ma;
  4394. ma.src = al1;
  4395. ma.dst = al2;
  4396. sendAndApply(&ma);
  4397. }
  4398. void CGameHandler::giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, int pos)
  4399. {
  4400. CArtifactInstance *a = NULL;
  4401. a->artType = artType; //NOT via settype -> all bonus-related stuff must be done by NewArtifact apply
  4402. NewArtifact na;
  4403. na.art = a;
  4404. sendAndApply(&na); // -> updates a!!!
  4405. giveHeroArtifact(h, a, pos);
  4406. }
  4407. CasualtiesAfterBattle::CasualtiesAfterBattle(const CArmedInstance *army, BattleInfo *bat)
  4408. {
  4409. int color = army->tempOwner;
  4410. if(color == 254)
  4411. color = NEUTRAL_PLAYER;
  4412. BOOST_FOREACH(CStack *st, bat->stacks)
  4413. {
  4414. if(vstd::contains(st->state, SUMMONED)) //don't take into account summoned stacks
  4415. continue;
  4416. if(st->owner==color && !army->slotEmpty(st->slot) && st->count < army->getStackCount(st->slot))
  4417. {
  4418. StackLocation sl(army, st->slot);
  4419. if(st->alive())
  4420. newStackCounts.push_back(std::pair<StackLocation, int>(sl, st->count));
  4421. else
  4422. newStackCounts.push_back(std::pair<StackLocation, int>(sl, 0));
  4423. }
  4424. }
  4425. }
  4426. void CasualtiesAfterBattle::takeFromArmy(CGameHandler *gh)
  4427. {
  4428. BOOST_FOREACH(TStackAndItsNewCount &ncount, newStackCounts)
  4429. {
  4430. if(ncount.second > 0)
  4431. gh->changeStackCount(ncount.first, ncount.second, true);
  4432. else
  4433. gh->eraseStack(ncount.first, true);
  4434. }
  4435. }