CGameHandler.cpp 152 KB

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