CGameHandler.cpp 156 KB

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