CGameHandler.cpp 152 KB

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