CGameHandler.cpp 157 KB

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