2
0

CGameHandler.cpp 185 KB

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