CGameHandler.cpp 175 KB

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