CGameHandler.cpp 156 KB

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