CGameHandler.cpp 149 KB

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