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