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