CGameHandler.cpp 156 KB

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