CGameHandler.cpp 155 KB

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