CGameHandler.cpp 157 KB

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