CGameHandler.cpp 208 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939
  1. /*
  2. * CGameHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CGameHandler.h"
  12. #include "HeroPoolProcessor.h"
  13. #include "ServerNetPackVisitors.h"
  14. #include "ServerSpellCastEnvironment.h"
  15. #include "CVCMIServer.h"
  16. #include "PlayerMessageProcessor.h"
  17. #include "../lib/filesystem/Filesystem.h"
  18. #include "../lib/filesystem/FileInfo.h"
  19. #include "../lib/int3.h"
  20. #include "../lib/ArtifactUtils.h"
  21. #include "../lib/StartInfo.h"
  22. #include "../lib/CArtHandler.h"
  23. #include "../lib/CBuildingHandler.h"
  24. #include "../lib/CHeroHandler.h"
  25. #include "../lib/pathfinder/CPathfinder.h"
  26. #include "../lib/pathfinder/PathfinderOptions.h"
  27. #include "../lib/pathfinder/TurnInfo.h"
  28. #include "../lib/spells/AbilityCaster.h"
  29. #include "../lib/spells/BonusCaster.h"
  30. #include "../lib/spells/CSpellHandler.h"
  31. #include "../lib/spells/ISpellMechanics.h"
  32. #include "../lib/spells/ObstacleCasterProxy.h"
  33. #include "../lib/spells/Problem.h"
  34. #include "../lib/CGeneralTextHandler.h"
  35. #include "../lib/CTownHandler.h"
  36. #include "../lib/CCreatureHandler.h"
  37. #include "../lib/gameState/CGameState.h"
  38. #include "../lib/CStack.h"
  39. #include "../lib/UnlockGuard.h"
  40. #include "../lib/GameSettings.h"
  41. #include "../lib/battle/BattleInfo.h"
  42. #include "../lib/CondSh.h"
  43. #include "../lib/VCMI_Lib.h"
  44. #include "../lib/mapping/CMap.h"
  45. #include "../lib/mapping/CMapService.h"
  46. #include "../lib/modding/ModIncompatibility.h"
  47. #include "../lib/rmg/CMapGenOptions.h"
  48. #include "../lib/VCMIDirs.h"
  49. #include "../lib/ScopeGuard.h"
  50. #include "../lib/CSoundBase.h"
  51. #include "../lib/TerrainHandler.h"
  52. #include "../lib/CCreatureSet.h"
  53. #include "../lib/CThreadHelper.h"
  54. #include "../lib/GameConstants.h"
  55. #include "../lib/registerTypes/RegisterTypes.h"
  56. #include "../lib/serializer/CTypeList.h"
  57. #include "../lib/serializer/Connection.h"
  58. #include "../lib/serializer/Cast.h"
  59. #include "../lib/serializer/JsonSerializer.h"
  60. #include "../lib/ScriptHandler.h"
  61. #include "vstd/CLoggerBase.h"
  62. #include <memory>
  63. #include <vcmi/events/EventBus.h>
  64. #include <vcmi/events/GenericEvents.h>
  65. #include <vcmi/events/AdventureEvents.h>
  66. #ifndef _MSC_VER
  67. #include <boost/thread/xtime.hpp>
  68. #endif
  69. #define COMPLAIN_RET_IF(cond, txt) do {if (cond){complain(txt); return;}} while(0)
  70. #define COMPLAIN_RET_FALSE_IF(cond, txt) do {if (cond){complain(txt); return false;}} while(0)
  71. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  72. #define COMPLAIN_RETF(txt, FORMAT) {complain(boost::str(boost::format(txt) % FORMAT)); return false;}
  73. CondSh<bool> battleMadeAction(false);
  74. boost::recursive_mutex battleActionMutex;
  75. CondSh<BattleResult *> battleResult(nullptr);
  76. template <typename T> class CApplyOnGH;
  77. class CBaseForGHApply
  78. {
  79. public:
  80. virtual bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const =0;
  81. virtual ~CBaseForGHApply(){}
  82. template<typename U> static CBaseForGHApply *getApplier(const U * t=nullptr)
  83. {
  84. return new CApplyOnGH<U>();
  85. }
  86. };
  87. template <typename T> class CApplyOnGH : public CBaseForGHApply
  88. {
  89. public:
  90. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  91. {
  92. T *ptr = static_cast<T*>(pack);
  93. try
  94. {
  95. ApplyGhNetPackVisitor applier(*gh, *gs);
  96. ptr->visit(applier);
  97. return applier.getResult();
  98. }
  99. catch(ExceptionNotAllowedAction & e)
  100. {
  101. (void)e;
  102. return false;
  103. }
  104. }
  105. };
  106. template <>
  107. class CApplyOnGH<CPack> : public CBaseForGHApply
  108. {
  109. public:
  110. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  111. {
  112. logGlobal->error("Cannot apply on GH plain CPack!");
  113. assert(0);
  114. return false;
  115. }
  116. };
  117. static inline double distance(int3 a, int3 b)
  118. {
  119. return std::sqrt((double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
  120. }
  121. static void giveExp(BattleResult &r)
  122. {
  123. if (r.winner > 1)
  124. {
  125. // draw
  126. return;
  127. }
  128. r.exp[0] = 0;
  129. r.exp[1] = 0;
  130. for (auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  131. {
  132. r.exp[r.winner] += VLC->creh->objects.at(i->first)->valOfBonuses(BonusType::STACK_HEALTH) * i->second;
  133. }
  134. }
  135. static void summonGuardiansHelper(std::vector<BattleHex> & output, const BattleHex & targetPosition, ui8 side, bool targetIsTwoHex) //return hexes for summoning two hex monsters in output, target = unit to guard
  136. {
  137. int x = targetPosition.getX();
  138. int y = targetPosition.getY();
  139. const bool targetIsAttacker = side == BattleSide::ATTACKER;
  140. if (targetIsAttacker) //handle front guardians, TODO: should we handle situation when units start battle near opposite side of the battlefield? Cannot happen in normal H3...
  141. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  142. else
  143. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  144. //guardian spawn locations for four default position cases for attacker and defender, non-default starting location for att and def is handled in first two if's
  145. if (targetIsAttacker && ((y % 2 == 0) || (x > 1)))
  146. {
  147. if (targetIsTwoHex && (y % 2 == 1) && (x == 2)) //handle exceptional case
  148. {
  149. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  150. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  151. }
  152. else
  153. { //add back-side guardians for two-hex target, side guardians for one-hex
  154. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_LEFT : BattleHex::EDir::TOP_RIGHT, false), output);
  155. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_LEFT : BattleHex::EDir::BOTTOM_RIGHT, false), output);
  156. if (!targetIsTwoHex && x > 2) //back guard for one-hex
  157. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false), output);
  158. else if (targetIsTwoHex)//front-side guardians for two-hex target
  159. {
  160. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  161. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  162. if (x > 3) //back guard for two-hex
  163. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  164. }
  165. }
  166. }
  167. else if (!targetIsAttacker && ((y % 2 == 1) || (x < GameConstants::BFIELD_WIDTH - 2)))
  168. {
  169. if (targetIsTwoHex && (y % 2 == 0) && (x == GameConstants::BFIELD_WIDTH - 3)) //handle exceptional case... equivalent for above for defender side
  170. {
  171. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  172. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  173. }
  174. else
  175. {
  176. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_RIGHT : BattleHex::EDir::TOP_LEFT, false), output);
  177. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_RIGHT : BattleHex::EDir::BOTTOM_LEFT, false), output);
  178. if (!targetIsTwoHex && x < GameConstants::BFIELD_WIDTH - 3)
  179. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  180. else if (targetIsTwoHex)
  181. {
  182. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  183. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  184. if (x < GameConstants::BFIELD_WIDTH - 4)
  185. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  186. }
  187. }
  188. }
  189. else if (!targetIsAttacker && y % 2 == 0)
  190. {
  191. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  192. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  193. }
  194. else if (targetIsAttacker && y % 2 == 1)
  195. {
  196. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  197. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  198. }
  199. }
  200. PlayerStatus PlayerStatuses::operator[](PlayerColor player)
  201. {
  202. boost::unique_lock<boost::mutex> l(mx);
  203. if (players.find(player) != players.end())
  204. {
  205. return players.at(player);
  206. }
  207. else
  208. {
  209. throw std::runtime_error("No such player!");
  210. }
  211. }
  212. void PlayerStatuses::addPlayer(PlayerColor player)
  213. {
  214. boost::unique_lock<boost::mutex> l(mx);
  215. players[player];
  216. }
  217. bool PlayerStatuses::checkFlag(PlayerColor player, bool PlayerStatus::*flag)
  218. {
  219. boost::unique_lock<boost::mutex> l(mx);
  220. if (players.find(player) != players.end())
  221. {
  222. return players[player].*flag;
  223. }
  224. else
  225. {
  226. throw std::runtime_error("No such player!");
  227. }
  228. }
  229. void PlayerStatuses::setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val)
  230. {
  231. boost::unique_lock<boost::mutex> l(mx);
  232. if (players.find(player) != players.end())
  233. {
  234. players[player].*flag = val;
  235. }
  236. else
  237. {
  238. throw std::runtime_error("No such player!");
  239. }
  240. cv.notify_all();
  241. }
  242. template <typename T>
  243. void callWith(std::vector<T> args, std::function<void(T)> fun, ui32 which)
  244. {
  245. fun(args[which]);
  246. }
  247. const Services * CGameHandler::services() const
  248. {
  249. return VLC;
  250. }
  251. const CGameHandler::BattleCb * CGameHandler::battle() const
  252. {
  253. return this;
  254. }
  255. const CGameHandler::GameCb * CGameHandler::game() const
  256. {
  257. return this;
  258. }
  259. vstd::CLoggerBase * CGameHandler::logger() const
  260. {
  261. return logGlobal;
  262. }
  263. events::EventBus * CGameHandler::eventBus() const
  264. {
  265. return serverEventBus.get();
  266. }
  267. CVCMIServer * CGameHandler::gameLobby() const
  268. {
  269. return lobby;
  270. }
  271. void CGameHandler::levelUpHero(const CGHeroInstance * hero, SecondarySkill skill)
  272. {
  273. changeSecSkill(hero, skill, 1, 0);
  274. expGiven(hero);
  275. }
  276. void CGameHandler::levelUpHero(const CGHeroInstance * hero)
  277. {
  278. // required exp for at least 1 lvl-up hasn't been reached
  279. if (!hero->gainsLevel())
  280. {
  281. return;
  282. }
  283. // give primary skill
  284. logGlobal->trace("%s got level %d", hero->getNameTranslated(), hero->level);
  285. auto primarySkill = hero->nextPrimarySkill(getRandomGenerator());
  286. SetPrimSkill sps;
  287. sps.id = hero->id;
  288. sps.which = primarySkill;
  289. sps.abs = false;
  290. sps.val = 1;
  291. sendAndApply(&sps);
  292. PrepareHeroLevelUp pre;
  293. pre.heroId = hero->id;
  294. sendAndApply(&pre);
  295. HeroLevelUp hlu;
  296. hlu.player = hero->tempOwner;
  297. hlu.heroId = hero->id;
  298. hlu.primskill = primarySkill;
  299. hlu.skills = pre.skills;
  300. if (hlu.skills.size() == 0)
  301. {
  302. sendAndApply(&hlu);
  303. levelUpHero(hero);
  304. }
  305. else if (hlu.skills.size() == 1)
  306. {
  307. sendAndApply(&hlu);
  308. levelUpHero(hero, pre.skills.front());
  309. }
  310. else if (hlu.skills.size() > 1)
  311. {
  312. auto levelUpQuery = std::make_shared<CHeroLevelUpDialogQuery>(this, hlu, hero);
  313. hlu.queryID = levelUpQuery->queryID;
  314. queries.addQuery(levelUpQuery);
  315. sendAndApply(&hlu);
  316. //level up will be called on query reply
  317. }
  318. }
  319. void CGameHandler::levelUpCommander (const CCommanderInstance * c, int skill)
  320. {
  321. SetCommanderProperty scp;
  322. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  323. if (hero)
  324. scp.heroid = hero->id;
  325. else
  326. {
  327. complain ("Commander is not led by hero!");
  328. return;
  329. }
  330. scp.accumulatedBonus.subtype = 0;
  331. scp.accumulatedBonus.additionalInfo = 0;
  332. scp.accumulatedBonus.duration = BonusDuration::PERMANENT;
  333. scp.accumulatedBonus.turnsRemain = 0;
  334. scp.accumulatedBonus.source = BonusSource::COMMANDER;
  335. scp.accumulatedBonus.valType = BonusValueType::BASE_NUMBER;
  336. if (skill <= ECommander::SPELL_POWER)
  337. {
  338. scp.which = SetCommanderProperty::BONUS;
  339. auto difference = [](std::vector< std::vector <ui8> > skillLevels, std::vector <ui8> secondarySkills, int skill)->int
  340. {
  341. int s = std::min (skill, (int)ECommander::SPELL_POWER); //spell power level controls also casts and resistance
  342. return skillLevels.at(skill).at(secondarySkills.at(s)) - (secondarySkills.at(s) ? skillLevels.at(skill).at(secondarySkills.at(s)-1) : 0);
  343. };
  344. switch (skill)
  345. {
  346. case ECommander::ATTACK:
  347. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  348. scp.accumulatedBonus.subtype = PrimarySkill::ATTACK;
  349. break;
  350. case ECommander::DEFENSE:
  351. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  352. scp.accumulatedBonus.subtype = PrimarySkill::DEFENSE;
  353. break;
  354. case ECommander::HEALTH:
  355. scp.accumulatedBonus.type = BonusType::STACK_HEALTH;
  356. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  357. break;
  358. case ECommander::DAMAGE:
  359. scp.accumulatedBonus.type = BonusType::CREATURE_DAMAGE;
  360. scp.accumulatedBonus.subtype = 0;
  361. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  362. break;
  363. case ECommander::SPEED:
  364. scp.accumulatedBonus.type = BonusType::STACKS_SPEED;
  365. break;
  366. case ECommander::SPELL_POWER:
  367. scp.accumulatedBonus.type = BonusType::MAGIC_RESISTANCE;
  368. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::RESISTANCE);
  369. sendAndApply (&scp); //additional pack
  370. scp.accumulatedBonus.type = BonusType::CREATURE_SPELL_POWER;
  371. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::SPELL_POWER) * 100; //like hero with spellpower = ability level
  372. sendAndApply (&scp); //additional pack
  373. scp.accumulatedBonus.type = BonusType::CASTS;
  374. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::CASTS);
  375. sendAndApply (&scp); //additional pack
  376. scp.accumulatedBonus.type = BonusType::CREATURE_ENCHANT_POWER; //send normally
  377. break;
  378. }
  379. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, skill);
  380. sendAndApply (&scp);
  381. scp.which = SetCommanderProperty::SECONDARY_SKILL;
  382. scp.additionalInfo = skill;
  383. scp.amount = c->secondarySkills.at(skill) + 1;
  384. sendAndApply (&scp);
  385. }
  386. else if (skill >= 100)
  387. {
  388. scp.which = SetCommanderProperty::SPECIAL_SKILL;
  389. scp.accumulatedBonus = *VLC->creh->skillRequirements.at(skill-100).first;
  390. scp.additionalInfo = skill; //unnormalized
  391. sendAndApply (&scp);
  392. }
  393. expGiven(hero);
  394. }
  395. void CGameHandler::levelUpCommander(const CCommanderInstance * c)
  396. {
  397. if (!c->gainsLevel())
  398. {
  399. return;
  400. }
  401. CommanderLevelUp clu;
  402. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  403. if(hero)
  404. {
  405. clu.heroId = hero->id;
  406. clu.player = hero->tempOwner;
  407. }
  408. else
  409. {
  410. complain ("Commander is not led by hero!");
  411. return;
  412. }
  413. //picking sec. skills for choice
  414. for (int i = 0; i <= ECommander::SPELL_POWER; ++i)
  415. {
  416. if (c->secondarySkills.at(i) < ECommander::MAX_SKILL_LEVEL)
  417. clu.skills.push_back(i);
  418. }
  419. int i = 100;
  420. for (auto specialSkill : VLC->creh->skillRequirements)
  421. {
  422. if (c->secondarySkills.at(specialSkill.second.first) == ECommander::MAX_SKILL_LEVEL
  423. && c->secondarySkills.at(specialSkill.second.second) == ECommander::MAX_SKILL_LEVEL
  424. && !vstd::contains (c->specialSKills, i))
  425. clu.skills.push_back (i);
  426. ++i;
  427. }
  428. int skillAmount = static_cast<int>(clu.skills.size());
  429. if (!skillAmount)
  430. {
  431. sendAndApply(&clu);
  432. levelUpCommander(c);
  433. }
  434. else if (skillAmount == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  435. {
  436. sendAndApply(&clu);
  437. levelUpCommander(c, *RandomGeneratorUtil::nextItem(clu.skills, getRandomGenerator()));
  438. }
  439. else if (skillAmount > 1) //apply and ask for secondary skill
  440. {
  441. auto commanderLevelUp = std::make_shared<CCommanderLevelUpDialogQuery>(this, clu, hero);
  442. clu.queryID = commanderLevelUp->queryID;
  443. queries.addQuery(commanderLevelUp);
  444. sendAndApply(&clu);
  445. }
  446. }
  447. void CGameHandler::expGiven(const CGHeroInstance *hero)
  448. {
  449. if (hero->gainsLevel())
  450. levelUpHero(hero);
  451. else if (hero->commander && hero->commander->gainsLevel())
  452. levelUpCommander(hero->commander);
  453. //if (hero->commander && hero->level > hero->commander->level && hero->commander->gainsLevel())
  454. // levelUpCommander(hero->commander);
  455. // else
  456. // levelUpHero(hero);
  457. }
  458. void CGameHandler::changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs)
  459. {
  460. if (which == PrimarySkill::EXPERIENCE) // Check if scenario limit reached
  461. {
  462. if (gs->map->levelLimit != 0)
  463. {
  464. TExpType expLimit = VLC->heroh->reqExp(gs->map->levelLimit);
  465. TExpType resultingExp = abs ? val : hero->exp + val;
  466. if (resultingExp > expLimit)
  467. {
  468. // set given experience to max possible, but don't decrease if hero already over top
  469. abs = true;
  470. val = std::max(expLimit, hero->exp);
  471. InfoWindow iw;
  472. iw.player = hero->tempOwner;
  473. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 1); //can gain no more XP
  474. iw.text.replaceRawString(hero->getNameTranslated());
  475. sendAndApply(&iw);
  476. }
  477. }
  478. }
  479. SetPrimSkill sps;
  480. sps.id = hero->id;
  481. sps.which = which;
  482. sps.abs = abs;
  483. sps.val = val;
  484. sendAndApply(&sps);
  485. //only for exp - hero may level up
  486. if (which == PrimarySkill::EXPERIENCE)
  487. {
  488. if (hero->commander && hero->commander->alive)
  489. {
  490. //FIXME: trim experience according to map limit?
  491. SetCommanderProperty scp;
  492. scp.heroid = hero->id;
  493. scp.which = SetCommanderProperty::EXPERIENCE;
  494. scp.amount = val;
  495. sendAndApply (&scp);
  496. CBonusSystemNode::treeHasChanged();
  497. }
  498. expGiven(hero);
  499. }
  500. }
  501. void CGameHandler::changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs)
  502. {
  503. if(!hero)
  504. {
  505. logGlobal->error("changeSecSkill provided no hero");
  506. return;
  507. }
  508. SetSecSkill sss;
  509. sss.id = hero->id;
  510. sss.which = which;
  511. sss.val = val;
  512. sss.abs = abs;
  513. sendAndApply(&sss);
  514. if (hero->visitedTown)
  515. giveSpells(hero->visitedTown, hero);
  516. }
  517. void CGameHandler::endBattle(int3 tile, const CGHeroInstance * heroAttacker, const CGHeroInstance * heroDefender)
  518. {
  519. LOG_TRACE(logGlobal);
  520. //Fill BattleResult structure with exp info
  521. giveExp(*battleResult.data);
  522. if (battleResult.get()->result == BattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  523. {
  524. if(heroAttacker)
  525. battleResult.data->exp[1] += 500;
  526. if(heroDefender)
  527. battleResult.data->exp[0] += 500;
  528. }
  529. if(heroAttacker)
  530. battleResult.data->exp[0] = heroAttacker->calculateXp(battleResult.data->exp[0]);//scholar skill
  531. if(heroDefender)
  532. battleResult.data->exp[1] = heroDefender->calculateXp(battleResult.data->exp[1]);
  533. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(gs->curB->sides[0].color));
  534. if (!battleQuery)
  535. {
  536. logGlobal->error("Cannot find battle query!");
  537. complain("Player " + boost::lexical_cast<std::string>(gs->curB->sides[0].color) + " has no battle query at the top!");
  538. return;
  539. }
  540. battleQuery->result = std::make_optional(*battleResult.data);
  541. //Check how many battle queries were created (number of players blocked by battle)
  542. const int queriedPlayers = battleQuery ? (int)boost::count(queries.allQueries(), battleQuery) : 0;
  543. finishingBattle = std::make_unique<FinishingBattleHelper>(battleQuery, queriedPlayers);
  544. // in battles against neutrals, 1st player can ask to replay battle manually
  545. if (!gs->curB->sides[1].color.isValidPlayer())
  546. {
  547. auto battleDialogQuery = std::make_shared<CBattleDialogQuery>(this, gs->curB);
  548. battleResult.data->queryID = battleDialogQuery->queryID;
  549. queries.addQuery(battleDialogQuery);
  550. }
  551. else
  552. battleResult.data->queryID = -1;
  553. //set same battle result for all queries
  554. for(auto q : queries.allQueries())
  555. {
  556. auto otherBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(q);
  557. if(otherBattleQuery)
  558. otherBattleQuery->result = battleQuery->result;
  559. }
  560. sendAndApply(battleResult.data); //after this point casualties objects are destroyed
  561. if (battleResult.data->queryID == -1)
  562. endBattleConfirm(gs->curB);
  563. }
  564. void CGameHandler::endBattleConfirm(const BattleInfo * battleInfo)
  565. {
  566. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(battleInfo->sides.at(0).color));
  567. if(!battleQuery)
  568. {
  569. logGlobal->trace("No battle query, battle end was confirmed by another player");
  570. return;
  571. }
  572. const BattleResult::EResult result = battleResult.get()->result;
  573. CasualtiesAfterBattle cab1(battleInfo->sides.at(0), battleInfo), cab2(battleInfo->sides.at(1), battleInfo); //calculate casualties before deleting battle
  574. ChangeSpells cs; //for Eagle Eye
  575. if(!finishingBattle->isDraw() && finishingBattle->winnerHero)
  576. {
  577. if (int eagleEyeLevel = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT, -1))
  578. {
  579. double eagleEyeChance = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE, 0);
  580. for(auto & spellId : battleInfo->sides.at(!battleResult.data->winner).usedSpellsHistory)
  581. {
  582. auto spell = spellId.toSpell(VLC->spells());
  583. if(spell && spell->getLevel() <= eagleEyeLevel && !finishingBattle->winnerHero->spellbookContainsSpell(spell->getId()) && getRandomGenerator().nextInt(99) < eagleEyeChance)
  584. cs.spells.insert(spell->getId());
  585. }
  586. }
  587. }
  588. std::vector<const CArtifactInstance *> arts; //display them in window
  589. if(result == BattleResult::NORMAL && !finishingBattle->isDraw() && finishingBattle->winnerHero)
  590. {
  591. auto sendMoveArtifact = [&](const CArtifactInstance *art, MoveArtifact *ma)
  592. {
  593. const auto slot = ArtifactUtils::getArtAnyPosition(finishingBattle->winnerHero, art->getTypeId());
  594. if(slot != ArtifactPosition::PRE_FIRST)
  595. {
  596. arts.push_back(art);
  597. ma->dst = ArtifactLocation(finishingBattle->winnerHero, slot);
  598. if(ArtifactUtils::isSlotBackpack(slot))
  599. ma->askAssemble = false;
  600. sendAndApply(ma);
  601. }
  602. };
  603. if (finishingBattle->loserHero)
  604. {
  605. //TODO: wrap it into a function, somehow (std::variant -_-)
  606. auto artifactsWorn = finishingBattle->loserHero->artifactsWorn;
  607. for (auto artSlot : artifactsWorn)
  608. {
  609. MoveArtifact ma;
  610. ma.src = ArtifactLocation(finishingBattle->loserHero, artSlot.first);
  611. const CArtifactInstance * art = ma.src.getArt();
  612. if (art && !art->artType->isBig() &&
  613. art->artType->getId() != ArtifactID::SPELLBOOK)
  614. // don't move war machines or locked arts (spellbook)
  615. {
  616. sendMoveArtifact(art, &ma);
  617. }
  618. }
  619. for(int slotNumber = finishingBattle->loserHero->artifactsInBackpack.size() - 1; slotNumber >= 0; slotNumber--)
  620. {
  621. //we assume that no big artifacts can be found
  622. MoveArtifact ma;
  623. ma.src = ArtifactLocation(finishingBattle->loserHero,
  624. ArtifactPosition(GameConstants::BACKPACK_START + slotNumber)); //backpack automatically shifts arts to beginning
  625. const CArtifactInstance * art = ma.src.getArt();
  626. if (art->artType->getId() != ArtifactID::GRAIL) //grail may not be won
  627. {
  628. sendMoveArtifact(art, &ma);
  629. }
  630. }
  631. if (finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero?
  632. {
  633. artifactsWorn = finishingBattle->loserHero->commander->artifactsWorn;
  634. for (auto artSlot : artifactsWorn)
  635. {
  636. MoveArtifact ma;
  637. ma.src = ArtifactLocation(finishingBattle->loserHero->commander.get(), artSlot.first);
  638. const CArtifactInstance * art = ma.src.getArt();
  639. if (art && !art->artType->isBig())
  640. {
  641. sendMoveArtifact(art, &ma);
  642. }
  643. }
  644. }
  645. }
  646. for (auto armySlot : battleInfo->sides.at(!battleResult.data->winner).armyObject->stacks)
  647. {
  648. auto artifactsWorn = armySlot.second->artifactsWorn;
  649. for (auto artSlot : artifactsWorn)
  650. {
  651. MoveArtifact ma;
  652. ma.src = ArtifactLocation(armySlot.second, artSlot.first);
  653. const CArtifactInstance * art = ma.src.getArt();
  654. if (art && !art->artType->isBig())
  655. {
  656. sendMoveArtifact(art, &ma);
  657. }
  658. }
  659. }
  660. }
  661. if (arts.size()) //display loot
  662. {
  663. InfoWindow iw;
  664. iw.player = finishingBattle->winnerHero->tempOwner;
  665. iw.text.appendLocalString (EMetaText::GENERAL_TXT, 30); //You have captured enemy artifact
  666. for (auto art : arts) //TODO; separate function to display loot for various ojects?
  667. {
  668. iw.components.emplace_back(
  669. Component::EComponentType::ARTIFACT, art->artType->getId(),
  670. art->artType->getId() == ArtifactID::SPELL_SCROLL? art->getScrollSpellID() : 0, 0);
  671. if (iw.components.size() >= 14)
  672. {
  673. sendAndApply(&iw);
  674. iw.components.clear();
  675. }
  676. }
  677. if (iw.components.size())
  678. {
  679. sendAndApply(&iw);
  680. }
  681. }
  682. //Eagle Eye secondary skill handling
  683. if (!cs.spells.empty())
  684. {
  685. cs.learn = 1;
  686. cs.hid = finishingBattle->winnerHero->id;
  687. InfoWindow iw;
  688. iw.player = finishingBattle->winnerHero->tempOwner;
  689. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
  690. iw.text.replaceRawString(finishingBattle->winnerHero->getNameTranslated());
  691. std::ostringstream names;
  692. for (int i = 0; i < cs.spells.size(); i++)
  693. {
  694. names << "%s";
  695. if (i < cs.spells.size() - 2)
  696. names << ", ";
  697. else if (i < cs.spells.size() - 1)
  698. names << "%s";
  699. }
  700. names << ".";
  701. iw.text.replaceRawString(names.str());
  702. auto it = cs.spells.begin();
  703. for (int i = 0; i < cs.spells.size(); i++, it++)
  704. {
  705. iw.text.replaceLocalString(EMetaText::SPELL_NAME, it->toEnum());
  706. if (i == cs.spells.size() - 2) //we just added pre-last name
  707. iw.text.replaceLocalString(EMetaText::GENERAL_TXT, 141); // " and "
  708. iw.components.emplace_back(Component::EComponentType::SPELL, *it, 0, 0);
  709. }
  710. sendAndApply(&iw);
  711. sendAndApply(&cs);
  712. }
  713. cab1.updateArmy(this);
  714. cab2.updateArmy(this); //take casualties after battle is deleted
  715. if(finishingBattle->loserHero) //remove beaten hero
  716. {
  717. RemoveObject ro(finishingBattle->loserHero->id);
  718. sendAndApply(&ro);
  719. }
  720. if(finishingBattle->isDraw() && finishingBattle->winnerHero) //for draw case both heroes should be removed
  721. {
  722. RemoveObject ro(finishingBattle->winnerHero->id);
  723. sendAndApply(&ro);
  724. }
  725. if(battleResult.data->winner == BattleSide::DEFENDER
  726. && finishingBattle->winnerHero
  727. && finishingBattle->winnerHero->visitedTown
  728. && !finishingBattle->winnerHero->inTownGarrison
  729. && finishingBattle->winnerHero->visitedTown->garrisonHero == finishingBattle->winnerHero)
  730. {
  731. swapGarrisonOnSiege(finishingBattle->winnerHero->visitedTown->id); //return defending visitor from garrison to its rightful place
  732. }
  733. //give exp
  734. if(!finishingBattle->isDraw() && battleResult.data->exp[finishingBattle->winnerSide] && finishingBattle->winnerHero)
  735. changePrimSkill(finishingBattle->winnerHero, PrimarySkill::EXPERIENCE, battleResult.data->exp[finishingBattle->winnerSide]);
  736. BattleResultAccepted raccepted;
  737. raccepted.heroResult[0].army = const_cast<CArmedInstance*>(battleInfo->sides.at(0).armyObject);
  738. raccepted.heroResult[1].army = const_cast<CArmedInstance*>(battleInfo->sides.at(1).armyObject);
  739. raccepted.heroResult[0].hero = const_cast<CGHeroInstance*>(battleInfo->sides.at(0).hero);
  740. raccepted.heroResult[1].hero = const_cast<CGHeroInstance*>(battleInfo->sides.at(1).hero);
  741. raccepted.heroResult[0].exp = battleResult.data->exp[0];
  742. raccepted.heroResult[1].exp = battleResult.data->exp[1];
  743. raccepted.winnerSide = finishingBattle->winnerSide;
  744. sendAndApply(&raccepted);
  745. queries.popIfTop(battleQuery);
  746. //--> continuation (battleAfterLevelUp) occurs after level-up queries are handled or on removing query
  747. }
  748. void CGameHandler::battleAfterLevelUp(const BattleResult &result)
  749. {
  750. LOG_TRACE(logGlobal);
  751. if(!finishingBattle)
  752. return;
  753. finishingBattle->remainingBattleQueriesCount--;
  754. logGlobal->trace("Decremented queries count to %d", finishingBattle->remainingBattleQueriesCount);
  755. if (finishingBattle->remainingBattleQueriesCount > 0)
  756. //Battle results will be handled when all battle queries are closed
  757. return;
  758. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  759. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  760. // Still, it looks like a hole.
  761. // Necromancy if applicable.
  762. const CStackBasicDescriptor raisedStack = finishingBattle->winnerHero ? finishingBattle->winnerHero->calculateNecromancy(*battleResult.data) : CStackBasicDescriptor();
  763. // Give raised units to winner and show dialog, if any were raised,
  764. // units will be given after casualties are taken
  765. const SlotID necroSlot = raisedStack.type ? finishingBattle->winnerHero->getSlotFor(raisedStack.type) : SlotID();
  766. if (necroSlot != SlotID())
  767. {
  768. finishingBattle->winnerHero->showNecromancyDialog(raisedStack, getRandomGenerator());
  769. addToSlot(StackLocation(finishingBattle->winnerHero, necroSlot), raisedStack.type, raisedStack.count);
  770. }
  771. BattleResultsApplied resultsApplied;
  772. resultsApplied.player1 = finishingBattle->victor;
  773. resultsApplied.player2 = finishingBattle->loser;
  774. sendAndApply(&resultsApplied);
  775. setBattle(nullptr);
  776. if (visitObjectAfterVictory && result.winner==0 && !finishingBattle->winnerHero->stacks.empty())
  777. {
  778. logGlobal->trace("post-victory visit");
  779. visitObjectOnTile(*getTile(finishingBattle->winnerHero->visitablePos()), finishingBattle->winnerHero);
  780. }
  781. visitObjectAfterVictory = false;
  782. //handle victory/loss of engaged players
  783. std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
  784. checkVictoryLossConditions(playerColors);
  785. if (result.result == BattleResult::SURRENDER)
  786. heroPool->onHeroSurrendered(finishingBattle->loser, finishingBattle->loserHero);
  787. if (result.result == BattleResult::ESCAPE)
  788. heroPool->onHeroEscaped(finishingBattle->loser, finishingBattle->loserHero);
  789. if (result.winner != 2 && finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()
  790. && (!finishingBattle->winnerHero->commander || !finishingBattle->winnerHero->commander->alive))
  791. {
  792. RemoveObject ro(finishingBattle->winnerHero->id);
  793. sendAndApply(&ro);
  794. if (VLC->settings()->getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  795. heroPool->onHeroEscaped(finishingBattle->victor, finishingBattle->winnerHero);
  796. }
  797. finishingBattle.reset();
  798. }
  799. void CGameHandler::makeAttack(const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter)
  800. {
  801. if(first && !counter)
  802. handleAttackBeforeCasting(ranged, attacker, defender);
  803. FireShieldInfo fireShield;
  804. BattleAttack bat;
  805. BattleLogMessage blm;
  806. bat.stackAttacking = attacker->unitId();
  807. bat.tile = targetHex;
  808. std::shared_ptr<battle::CUnitState> attackerState = attacker->acquireState();
  809. if(ranged)
  810. bat.flags |= BattleAttack::SHOT;
  811. if(counter)
  812. bat.flags |= BattleAttack::COUNTER;
  813. const int attackerLuck = attacker->luckVal();
  814. if(attackerLuck > 0)
  815. {
  816. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_LUCK_DICE);
  817. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, attackerLuck);
  818. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  819. bat.flags |= BattleAttack::LUCKY;
  820. }
  821. if(attackerLuck < 0)
  822. {
  823. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_LUCK_DICE);
  824. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, -attackerLuck);
  825. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  826. bat.flags |= BattleAttack::UNLUCKY;
  827. }
  828. if (getRandomGenerator().nextInt(99) < attacker->valOfBonuses(BonusType::DOUBLE_DAMAGE_CHANCE))
  829. {
  830. bat.flags |= BattleAttack::DEATH_BLOW;
  831. }
  832. const auto * owner = gs->curB->getHero(attacker->unitOwner());
  833. if(owner)
  834. {
  835. int chance = owner->valOfBonuses(BonusType::BONUS_DAMAGE_CHANCE, attacker->creatureIndex());
  836. if (chance > getRandomGenerator().nextInt(99))
  837. bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
  838. }
  839. int64_t drainedLife = 0;
  840. // only primary target
  841. if(defender->alive())
  842. drainedLife += applyBattleEffects(bat, attackerState, fireShield, defender, distance, false);
  843. //multiple-hex normal attack
  844. std::set<const CStack*> attackedCreatures = gs->curB->getAttackedCreatures(attacker, targetHex, bat.shot()); //creatures other than primary target
  845. for(const CStack * stack : attackedCreatures)
  846. {
  847. if(stack != defender && stack->alive()) //do not hit same stack twice
  848. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  849. }
  850. std::shared_ptr<const Bonus> bonus = attacker->getBonusLocalFirst(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  851. if(bonus && ranged) //TODO: make it work in melee?
  852. {
  853. //this is need for displaying hit animation
  854. bat.flags |= BattleAttack::SPELL_LIKE;
  855. bat.spellID = SpellID(bonus->subtype);
  856. //TODO: should spell override creature`s projectile?
  857. auto spell = bat.spellID.toSpell();
  858. battle::Target target;
  859. target.emplace_back(defender, targetHex);
  860. spells::BattleCast event(gs->curB, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  861. event.setSpellLevel(bonus->val);
  862. auto attackedCreatures = spell->battleMechanics(&event)->getAffectedStacks(target);
  863. //TODO: get exact attacked hex for defender
  864. for(const CStack * stack : attackedCreatures)
  865. {
  866. if(stack != defender && stack->alive()) //do not hit same stack twice
  867. {
  868. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  869. }
  870. }
  871. //now add effect info for all attacked stacks
  872. for (BattleStackAttacked & bsa : bat.bsa)
  873. {
  874. if (bsa.attackerID == attacker->unitId()) //this is our attack and not f.e. fire shield
  875. {
  876. //this is need for displaying affect animation
  877. bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
  878. bsa.spellID = SpellID(bonus->subtype);
  879. }
  880. }
  881. }
  882. attackerState->afterAttack(ranged, counter);
  883. {
  884. UnitChanges info(attackerState->unitId(), UnitChanges::EOperation::RESET_STATE);
  885. attackerState->save(info.data);
  886. bat.attackerChanges.changedStacks.push_back(info);
  887. }
  888. if (drainedLife > 0)
  889. bat.flags |= BattleAttack::LIFE_DRAIN;
  890. sendAndApply(&bat);
  891. {
  892. const bool multipleTargets = bat.bsa.size() > 1;
  893. int64_t totalDamage = 0;
  894. int32_t totalKills = 0;
  895. for(const BattleStackAttacked & bsa : bat.bsa)
  896. {
  897. totalDamage += bsa.damageAmount;
  898. totalKills += bsa.killedAmount;
  899. }
  900. {
  901. MetaString text;
  902. attacker->addText(text, EMetaText::GENERAL_TXT, 376);
  903. attacker->addNameReplacement(text);
  904. text.replaceNumber(totalDamage);
  905. blm.lines.push_back(text);
  906. }
  907. addGenericKilledLog(blm, defender, totalKills, multipleTargets);
  908. }
  909. // drain life effect (as well as log entry) must be applied after the attack
  910. if(drainedLife > 0)
  911. {
  912. MetaString text;
  913. attackerState->addText(text, EMetaText::GENERAL_TXT, 361);
  914. attackerState->addNameReplacement(text, false);
  915. text.replaceNumber(drainedLife);
  916. defender->addNameReplacement(text, true);
  917. blm.lines.push_back(std::move(text));
  918. }
  919. if(!fireShield.empty())
  920. {
  921. //todo: this should be "virtual" spell instead, we only need fire spell school bonus here
  922. const CSpell * fireShieldSpell = SpellID(SpellID::FIRE_SHIELD).toSpell();
  923. int64_t totalDamage = 0;
  924. for(const auto & item : fireShield)
  925. {
  926. const CStack * actor = item.first;
  927. int64_t rawDamage = item.second;
  928. const CGHeroInstance * actorOwner = gs->curB->getHero(actor->unitOwner());
  929. if(actorOwner)
  930. {
  931. rawDamage = fireShieldSpell->adjustRawDamage(actorOwner, attacker, rawDamage);
  932. }
  933. else
  934. {
  935. rawDamage = fireShieldSpell->adjustRawDamage(actor, attacker, rawDamage);
  936. }
  937. totalDamage+=rawDamage;
  938. //FIXME: add custom effect on actor
  939. }
  940. if (totalDamage > 0)
  941. {
  942. BattleStackAttacked bsa;
  943. bsa.flags |= BattleStackAttacked::FIRE_SHIELD;
  944. bsa.stackAttacked = attacker->unitId(); //invert
  945. bsa.attackerID = defender->unitId();
  946. bsa.damageAmount = totalDamage;
  947. attacker->prepareAttacked(bsa, getRandomGenerator());
  948. StacksInjured pack;
  949. pack.stacks.push_back(bsa);
  950. sendAndApply(&pack);
  951. // TODO: this is already implemented in Damage::describeEffect()
  952. {
  953. MetaString text;
  954. text.appendLocalString(EMetaText::GENERAL_TXT, 376);
  955. text.replaceLocalString(EMetaText::SPELL_NAME, SpellID::FIRE_SHIELD);
  956. text.replaceNumber(totalDamage);
  957. blm.lines.push_back(std::move(text));
  958. }
  959. addGenericKilledLog(blm, attacker, bsa.killedAmount, false);
  960. }
  961. }
  962. sendAndApply(&blm);
  963. handleAfterAttackCasting(ranged, attacker, defender);
  964. }
  965. int64_t CGameHandler::applyBattleEffects(BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, int distance, bool secondary)
  966. {
  967. BattleStackAttacked bsa;
  968. if(secondary)
  969. bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
  970. bsa.attackerID = attackerState->unitId();
  971. bsa.stackAttacked = def->unitId();
  972. {
  973. BattleAttackInfo bai(attackerState.get(), def, distance, bat.shot());
  974. bai.deathBlow = bat.deathBlow();
  975. bai.doubleDamage = bat.ballistaDoubleDmg();
  976. bai.luckyStrike = bat.lucky();
  977. bai.unluckyStrike = bat.unlucky();
  978. auto range = gs->curB->calculateDmgRange(bai);
  979. bsa.damageAmount = gs->curB->getActualDamage(range.damage, attackerState->getCount(), getRandomGenerator());
  980. CStack::prepareAttacked(bsa, getRandomGenerator(), bai.defender->acquireState()); //calculate casualties
  981. }
  982. int64_t drainedLife = 0;
  983. //life drain handling
  984. if(attackerState->hasBonusOfType(BonusType::LIFE_DRAIN) && def->isLiving())
  985. {
  986. int64_t toHeal = bsa.damageAmount * attackerState->valOfBonuses(BonusType::LIFE_DRAIN) / 100;
  987. attackerState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  988. drainedLife += toHeal;
  989. }
  990. //soul steal handling
  991. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL) && def->isLiving())
  992. {
  993. //we can have two bonuses - one with subtype 0 and another with subtype 1
  994. //try to use permanent first, use only one of two
  995. for(si32 subtype = 1; subtype >= 0; subtype--)
  996. {
  997. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL, subtype))
  998. {
  999. int64_t toHeal = bsa.killedAmount * attackerState->valOfBonuses(BonusType::SOUL_STEAL, subtype) * attackerState->getMaxHealth();
  1000. attackerState->heal(toHeal, EHealLevel::OVERHEAL, ((subtype == 0) ? EHealPower::ONE_BATTLE : EHealPower::PERMANENT));
  1001. drainedLife += toHeal;
  1002. break;
  1003. }
  1004. }
  1005. }
  1006. bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
  1007. //fire shield handling
  1008. if(!bat.shot() &&
  1009. !def->isClone() &&
  1010. def->hasBonusOfType(BonusType::FIRE_SHIELD) &&
  1011. !attackerState->hasBonusOfType(BonusType::FIRE_IMMUNITY) &&
  1012. CStack::isMeleeAttackPossible(attackerState.get(), def) // attacked needs to be adjacent to defender for fire shield to trigger (e.g. Dragon Breath attack)
  1013. )
  1014. {
  1015. //TODO: use damage with bonus but without penalties
  1016. auto fireShieldDamage = (std::min<int64_t>(def->getAvailableHealth(), bsa.damageAmount) * def->valOfBonuses(BonusType::FIRE_SHIELD)) / 100;
  1017. fireShield.push_back(std::make_pair(def, fireShieldDamage));
  1018. }
  1019. return drainedLife;
  1020. }
  1021. void CGameHandler::sendGenericKilledLog(const CStack * defender, int32_t killed, bool multiple)
  1022. {
  1023. if(killed > 0)
  1024. {
  1025. BattleLogMessage blm;
  1026. addGenericKilledLog(blm, defender, killed, multiple);
  1027. sendAndApply(&blm);
  1028. }
  1029. }
  1030. void CGameHandler::addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple)
  1031. {
  1032. if(killed > 0)
  1033. {
  1034. const int32_t txtIndex = (killed > 1) ? 379 : 378;
  1035. std::string formatString = VLC->generaltexth->allTexts[txtIndex];
  1036. // these default h3 texts have unnecessary new lines, so get rid of them before displaying (and trim just in case, trimming newlines does not works for some reason)
  1037. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\n'), formatString.end());
  1038. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\r'), formatString.end());
  1039. boost::algorithm::trim(formatString);
  1040. boost::format txt(formatString);
  1041. if(killed > 1)
  1042. {
  1043. txt % killed % (multiple ? VLC->generaltexth->allTexts[43] : defender->unitType()->getNamePluralTranslated()); // creatures perish
  1044. }
  1045. else //killed == 1
  1046. {
  1047. txt % (multiple ? VLC->generaltexth->allTexts[42] : defender->unitType()->getNameSingularTranslated()); // creature perishes
  1048. }
  1049. MetaString line;
  1050. line.appendRawString(txt.str());
  1051. blm.lines.push_back(std::move(line));
  1052. }
  1053. }
  1054. void CGameHandler::handleClientDisconnection(std::shared_ptr<CConnection> c)
  1055. {
  1056. if(lobby->state == EServerState::SHUTDOWN || !gs || !gs->scenarioOps)
  1057. return;
  1058. for(auto & playerConnections : connections)
  1059. {
  1060. PlayerColor playerId = playerConnections.first;
  1061. auto * playerSettings = gs->scenarioOps->getPlayersSettings(playerId.getNum());
  1062. if(!playerSettings)
  1063. continue;
  1064. auto playerConnection = vstd::find(playerConnections.second, c);
  1065. if(playerConnection != playerConnections.second.end())
  1066. {
  1067. std::string messageText = boost::str(boost::format("%s (cid %d) was disconnected") % playerSettings->name % c->connectionID);
  1068. playerMessages->broadcastMessage(playerId, messageText);
  1069. }
  1070. }
  1071. }
  1072. void CGameHandler::handleReceivedPack(CPackForServer * pack)
  1073. {
  1074. //prepare struct informing that action was applied
  1075. auto sendPackageResponse = [&](bool succesfullyApplied)
  1076. {
  1077. PackageApplied applied;
  1078. applied.player = pack->player;
  1079. applied.result = succesfullyApplied;
  1080. applied.packType = typeList.getTypeID(pack);
  1081. applied.requestID = pack->requestID;
  1082. pack->c->sendPack(&applied);
  1083. };
  1084. CBaseForGHApply * apply = applier->getApplier(typeList.getTypeID(pack)); //and appropriate applier object
  1085. if(isBlockedByQueries(pack, pack->player))
  1086. {
  1087. sendPackageResponse(false);
  1088. }
  1089. else if(apply)
  1090. {
  1091. const bool result = apply->applyOnGH(this, this->gs, pack);
  1092. if(result)
  1093. logGlobal->trace("Message %s successfully applied!", typeid(*pack).name());
  1094. else
  1095. complain((boost::format("Got false in applying %s... that request must have been fishy!")
  1096. % typeid(*pack).name()).str());
  1097. sendPackageResponse(true);
  1098. }
  1099. else
  1100. {
  1101. logGlobal->error("Message cannot be applied, cannot find applier (unregistered type)!");
  1102. sendPackageResponse(false);
  1103. }
  1104. vstd::clear_pointer(pack);
  1105. }
  1106. int CGameHandler::moveStack(int stack, BattleHex dest)
  1107. {
  1108. int ret = 0;
  1109. const CStack *curStack = gs->curB->battleGetStackByID(stack),
  1110. *stackAtEnd = gs->curB->battleGetStackByPos(dest);
  1111. assert(curStack);
  1112. assert(dest < GameConstants::BFIELD_SIZE);
  1113. if (gs->curB->tacticDistance)
  1114. {
  1115. assert(gs->curB->isInTacticRange(dest));
  1116. }
  1117. auto start = curStack->getPosition();
  1118. if (start == dest)
  1119. return 0;
  1120. //initing necessary tables
  1121. auto accessibility = getAccesibility(curStack);
  1122. std::set<BattleHex> passed;
  1123. //Ignore obstacles on starting position
  1124. passed.insert(curStack->getPosition());
  1125. if(curStack->doubleWide())
  1126. passed.insert(curStack->occupiedHex());
  1127. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  1128. if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
  1129. {
  1130. BattleHex shifted = dest.cloneInDirection(curStack->destShiftDir(), false);
  1131. if(accessibility.accessible(shifted, curStack))
  1132. dest = shifted;
  1133. }
  1134. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
  1135. {
  1136. complain("Given destination is not accessible!");
  1137. return 0;
  1138. }
  1139. bool canUseGate = false;
  1140. auto dbState = gs->curB->si.gateState;
  1141. if(battleGetSiegeLevel() > 0 && curStack->unitSide() == BattleSide::DEFENDER &&
  1142. dbState != EGateState::DESTROYED &&
  1143. dbState != EGateState::BLOCKED)
  1144. {
  1145. canUseGate = true;
  1146. }
  1147. std::pair< std::vector<BattleHex>, int > path = gs->curB->getPath(start, dest, curStack);
  1148. ret = path.second;
  1149. int creSpeed = curStack->speed(0, true);
  1150. if (gs->curB->tacticDistance > 0 && creSpeed > 0)
  1151. creSpeed = GameConstants::BFIELD_SIZE;
  1152. bool hasWideMoat = vstd::contains_if(battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  1153. {
  1154. return obst->obstacleType == CObstacleInstance::MOAT;
  1155. });
  1156. auto isGateDrawbridgeHex = [&](BattleHex hex) -> bool
  1157. {
  1158. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  1159. return true;
  1160. if (hex == ESiegeHex::GATE_OUTER)
  1161. return true;
  1162. if (hex == ESiegeHex::GATE_INNER)
  1163. return true;
  1164. return false;
  1165. };
  1166. auto occupyGateDrawbridgeHex = [&](BattleHex hex) -> bool
  1167. {
  1168. if (isGateDrawbridgeHex(hex))
  1169. return true;
  1170. if (curStack->doubleWide())
  1171. {
  1172. BattleHex otherHex = curStack->occupiedHex(hex);
  1173. if (otherHex.isValid() && isGateDrawbridgeHex(otherHex))
  1174. return true;
  1175. }
  1176. return false;
  1177. };
  1178. if (curStack->hasBonusOfType(BonusType::FLYING))
  1179. {
  1180. if (path.second <= creSpeed && path.first.size() > 0)
  1181. {
  1182. if (canUseGate && dbState != EGateState::OPENED &&
  1183. occupyGateDrawbridgeHex(dest))
  1184. {
  1185. BattleUpdateGateState db;
  1186. db.state = EGateState::OPENED;
  1187. sendAndApply(&db);
  1188. }
  1189. //inform clients about move
  1190. BattleStackMoved sm;
  1191. sm.stack = curStack->unitId();
  1192. std::vector<BattleHex> tiles;
  1193. tiles.push_back(path.first[0]);
  1194. sm.tilesToMove = tiles;
  1195. sm.distance = path.second;
  1196. sm.teleporting = false;
  1197. sendAndApply(&sm);
  1198. }
  1199. }
  1200. else //for non-flying creatures
  1201. {
  1202. std::vector<BattleHex> tiles;
  1203. const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0);
  1204. int v = (int)path.first.size()-1;
  1205. path.first.push_back(start);
  1206. // check if gate need to be open or closed at some point
  1207. BattleHex openGateAtHex, gateMayCloseAtHex;
  1208. if (canUseGate)
  1209. {
  1210. for (int i = (int)path.first.size()-1; i >= 0; i--)
  1211. {
  1212. auto needOpenGates = [&](BattleHex hex) -> bool
  1213. {
  1214. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  1215. return true;
  1216. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] == ESiegeHex::GATE_OUTER)
  1217. return true;
  1218. else if (hex == ESiegeHex::GATE_OUTER || hex == ESiegeHex::GATE_INNER)
  1219. return true;
  1220. return false;
  1221. };
  1222. auto hex = path.first[i];
  1223. if (!openGateAtHex.isValid() && dbState != EGateState::OPENED)
  1224. {
  1225. if (needOpenGates(hex))
  1226. openGateAtHex = path.first[i+1];
  1227. //TODO we need find batter way to handle double-wide stacks
  1228. //currently if only second occupied stack part is standing on gate / bridge hex then stack will start to wait for bridge to lower before it's needed. Though this is just a visual bug.
  1229. if (curStack->doubleWide())
  1230. {
  1231. BattleHex otherHex = curStack->occupiedHex(hex);
  1232. if (otherHex.isValid() && needOpenGates(otherHex))
  1233. openGateAtHex = path.first[i+2];
  1234. }
  1235. //gate may be opened and then closed during stack movement, but not other way around
  1236. if (openGateAtHex.isValid())
  1237. dbState = EGateState::OPENED;
  1238. }
  1239. if (!gateMayCloseAtHex.isValid() && dbState != EGateState::CLOSED)
  1240. {
  1241. if (hex == ESiegeHex::GATE_INNER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  1242. {
  1243. gateMayCloseAtHex = path.first[i-1];
  1244. }
  1245. if (hasWideMoat)
  1246. {
  1247. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  1248. {
  1249. gateMayCloseAtHex = path.first[i-1];
  1250. }
  1251. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 &&
  1252. path.first[i-1] != ESiegeHex::GATE_INNER &&
  1253. path.first[i-1] != ESiegeHex::GATE_BRIDGE)
  1254. {
  1255. gateMayCloseAtHex = path.first[i-1];
  1256. }
  1257. }
  1258. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_INNER)
  1259. {
  1260. gateMayCloseAtHex = path.first[i-1];
  1261. }
  1262. }
  1263. }
  1264. }
  1265. bool stackIsMoving = true;
  1266. while(stackIsMoving)
  1267. {
  1268. if (v<tilesToMove)
  1269. {
  1270. logGlobal->error("Movement terminated abnormally");
  1271. break;
  1272. }
  1273. bool gateStateChanging = false;
  1274. //special handling for opening gate on from starting hex
  1275. if (openGateAtHex.isValid() && openGateAtHex == start)
  1276. gateStateChanging = true;
  1277. else
  1278. {
  1279. for (bool obstacleHit = false; (!obstacleHit) && (!gateStateChanging) && (v >= tilesToMove); --v)
  1280. {
  1281. BattleHex hex = path.first[v];
  1282. tiles.push_back(hex);
  1283. if ((openGateAtHex.isValid() && openGateAtHex == hex) ||
  1284. (gateMayCloseAtHex.isValid() && gateMayCloseAtHex == hex))
  1285. {
  1286. gateStateChanging = true;
  1287. }
  1288. //if we walked onto something, finalize this portion of stack movement check into obstacle
  1289. if(!battleGetAllObstaclesOnPos(hex, false).empty())
  1290. obstacleHit = true;
  1291. if (curStack->doubleWide())
  1292. {
  1293. BattleHex otherHex = curStack->occupiedHex(hex);
  1294. //two hex creature hit obstacle by backside
  1295. auto obstacle2 = battleGetAllObstaclesOnPos(otherHex, false);
  1296. if(otherHex.isValid() && !obstacle2.empty())
  1297. obstacleHit = true;
  1298. }
  1299. if(!obstacleHit)
  1300. passed.insert(hex);
  1301. }
  1302. }
  1303. if (!tiles.empty())
  1304. {
  1305. //commit movement
  1306. BattleStackMoved sm;
  1307. sm.stack = curStack->unitId();
  1308. sm.distance = path.second;
  1309. sm.teleporting = false;
  1310. sm.tilesToMove = tiles;
  1311. sendAndApply(&sm);
  1312. tiles.clear();
  1313. }
  1314. //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end
  1315. if (curStack->getPosition() != dest)
  1316. {
  1317. if(stackIsMoving && start != curStack->getPosition())
  1318. {
  1319. stackIsMoving = handleObstacleTriggersForUnit(*spellEnv, *curStack, passed);
  1320. passed.insert(curStack->getPosition());
  1321. if(curStack->doubleWide())
  1322. passed.insert(curStack->occupiedHex());
  1323. }
  1324. if (gateStateChanging)
  1325. {
  1326. if (curStack->getPosition() == openGateAtHex)
  1327. {
  1328. openGateAtHex = BattleHex();
  1329. //only open gate if stack is still alive
  1330. if (curStack->alive())
  1331. {
  1332. BattleUpdateGateState db;
  1333. db.state = EGateState::OPENED;
  1334. sendAndApply(&db);
  1335. }
  1336. }
  1337. else if (curStack->getPosition() == gateMayCloseAtHex)
  1338. {
  1339. gateMayCloseAtHex = BattleHex();
  1340. updateGateState();
  1341. }
  1342. }
  1343. }
  1344. else
  1345. //movement finished normally: we reached destination
  1346. stackIsMoving = false;
  1347. }
  1348. }
  1349. //handle last hex separately for deviation
  1350. if (VLC->settings()->getBoolean(EGameSettings::COMBAT_ONE_HEX_TRIGGERS_OBSTACLES))
  1351. {
  1352. if (dest == battle::Unit::occupiedHex(start, curStack->doubleWide(), curStack->unitSide())
  1353. || start == battle::Unit::occupiedHex(dest, curStack->doubleWide(), curStack->unitSide()))
  1354. passed.clear(); //Just empty passed, obstacles will handled automatically
  1355. }
  1356. //handling obstacle on the final field (separate, because it affects both flying and walking stacks)
  1357. handleObstacleTriggersForUnit(*spellEnv, *curStack, passed);
  1358. return ret;
  1359. }
  1360. CGameHandler::CGameHandler()
  1361. : turnTimerHandler(*this)
  1362. {}
  1363. CGameHandler::CGameHandler(CVCMIServer * lobby)
  1364. : lobby(lobby)
  1365. , heroPool(std::make_unique<HeroPoolProcessor>(this))
  1366. , playerMessages(std::make_unique<PlayerMessageProcessor>(this))
  1367. , complainNoCreatures("No creatures to split")
  1368. , complainNotEnoughCreatures("Cannot split that stack, not enough creatures!")
  1369. , complainInvalidSlot("Invalid slot accessed!")
  1370. , turnTimerHandler(*this)
  1371. {
  1372. QID = 1;
  1373. IObjectInterface::cb = this;
  1374. applier = std::make_shared<CApplier<CBaseForGHApply>>();
  1375. registerTypesServerPacks(*applier);
  1376. visitObjectAfterVictory = false;
  1377. spellEnv = new ServerSpellCastEnvironment(this);
  1378. }
  1379. CGameHandler::~CGameHandler()
  1380. {
  1381. if (battleThread)
  1382. {
  1383. //Setting battleMadeAction is needed because battleThread waits for the action to continue the main loop
  1384. battleMadeAction.setn(true);
  1385. battleThread->join();
  1386. }
  1387. delete spellEnv;
  1388. delete gs;
  1389. }
  1390. void CGameHandler::reinitScripting()
  1391. {
  1392. serverEventBus = std::make_unique<events::EventBus>();
  1393. #if SCRIPTING_ENABLED
  1394. serverScripts.reset(new scripting::PoolImpl(this, spellEnv));
  1395. #endif
  1396. }
  1397. void CGameHandler::init(StartInfo *si)
  1398. {
  1399. if (si->seedToBeUsed == 0)
  1400. {
  1401. si->seedToBeUsed = static_cast<ui32>(std::time(nullptr));
  1402. }
  1403. CMapService mapService;
  1404. gs = new CGameState();
  1405. gs->preInit(VLC);
  1406. logGlobal->info("Gamestate created!");
  1407. gs->init(&mapService, si);
  1408. logGlobal->info("Gamestate initialized!");
  1409. // reset seed, so that clients can't predict any following random values
  1410. getRandomGenerator().resetSeed();
  1411. for (auto & elem : gs->players)
  1412. {
  1413. states.addPlayer(elem.first);
  1414. }
  1415. reinitScripting();
  1416. }
  1417. static bool evntCmp(const CMapEvent &a, const CMapEvent &b)
  1418. {
  1419. return a.earlierThan(b);
  1420. }
  1421. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false, bool clear = false)
  1422. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  1423. const PlayerState * p = getPlayerState(town->tempOwner);
  1424. if (!p)
  1425. {
  1426. assert(town->tempOwner == PlayerColor::NEUTRAL);
  1427. return;
  1428. }
  1429. if (forced || town->creatures.at(GameConstants::CREATURES_PER_TOWN).second.empty())//we need to change creature
  1430. {
  1431. SetAvailableCreatures ssi;
  1432. ssi.tid = town->id;
  1433. ssi.creatures = town->creatures;
  1434. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.clear();//remove old one
  1435. const std::vector<ConstTransitivePtr<CGDwelling> > &dwellings = p->dwellings;
  1436. if (dwellings.empty())//no dwellings - just remove
  1437. {
  1438. sendAndApply(&ssi);
  1439. return;
  1440. }
  1441. auto dwelling = *RandomGeneratorUtil::nextItem(dwellings, getRandomGenerator());
  1442. // for multi-creature dwellings like Golem Factory
  1443. auto creatureId = RandomGeneratorUtil::nextItem(dwelling->creatures, getRandomGenerator())->second[0];
  1444. if (clear)
  1445. {
  1446. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = std::max(1, (VLC->creh->objects.at(creatureId)->getGrowth())/2);
  1447. }
  1448. else
  1449. {
  1450. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = VLC->creh->objects.at(creatureId)->getGrowth();
  1451. }
  1452. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.push_back(creatureId);
  1453. sendAndApply(&ssi);
  1454. }
  1455. }
  1456. void CGameHandler::newTurn()
  1457. {
  1458. logGlobal->trace("Turn %d", gs->day+1);
  1459. NewTurn n;
  1460. n.specialWeek = NewTurn::NO_ACTION;
  1461. n.creatureid = CreatureID::NONE;
  1462. n.day = gs->day + 1;
  1463. bool firstTurn = !getDate(Date::DAY);
  1464. bool newWeek = getDate(Date::DAY_OF_WEEK) == 7; //day numbers are confusing, as day was not yet switched
  1465. bool newMonth = getDate(Date::DAY_OF_MONTH) == 28;
  1466. std::map<PlayerColor, si32> hadGold;//starting gold - for buildings like dwarven treasury
  1467. if (firstTurn)
  1468. {
  1469. for (auto obj : gs->map->objects)
  1470. {
  1471. if (obj && obj->ID == Obj::PRISON) //give imprisoned hero 0 exp to level him up. easiest to do at this point
  1472. {
  1473. changePrimSkill (getHero(obj->id), PrimarySkill::EXPERIENCE, 0);
  1474. }
  1475. }
  1476. }
  1477. if (newWeek && !firstTurn)
  1478. {
  1479. n.specialWeek = NewTurn::NORMAL;
  1480. bool deityOfFireBuilt = false;
  1481. for (const CGTownInstance *t : gs->map->towns)
  1482. {
  1483. if (t->hasBuilt(BuildingID::GRAIL, ETownType::INFERNO))
  1484. {
  1485. deityOfFireBuilt = true;
  1486. break;
  1487. }
  1488. }
  1489. if (deityOfFireBuilt)
  1490. {
  1491. n.specialWeek = NewTurn::DEITYOFFIRE;
  1492. n.creatureid = CreatureID::IMP;
  1493. }
  1494. else if(VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_RANDOM_SPECIAL_WEEKS))
  1495. {
  1496. int monthType = getRandomGenerator().nextInt(99);
  1497. if (newMonth) //new month
  1498. {
  1499. if (monthType < 40) //double growth
  1500. {
  1501. n.specialWeek = NewTurn::DOUBLE_GROWTH;
  1502. if (VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_ALL_FOR_DOUBLE_MONTH))
  1503. {
  1504. n.creatureid = VLC->creh->pickRandomMonster(getRandomGenerator());
  1505. }
  1506. else if (VLC->creh->doubledCreatures.size())
  1507. {
  1508. n.creatureid = *RandomGeneratorUtil::nextItem(VLC->creh->doubledCreatures, getRandomGenerator());
  1509. }
  1510. else
  1511. {
  1512. complain("Cannot find creature that can be spawned!");
  1513. n.specialWeek = NewTurn::NORMAL;
  1514. }
  1515. }
  1516. else if (monthType < 50)
  1517. n.specialWeek = NewTurn::PLAGUE;
  1518. }
  1519. else //it's a week, but not full month
  1520. {
  1521. if (monthType < 25)
  1522. {
  1523. n.specialWeek = NewTurn::BONUS_GROWTH; //+5
  1524. std::pair<int, CreatureID> newMonster(54, CreatureID());
  1525. do
  1526. {
  1527. newMonster.second = VLC->creh->pickRandomMonster(getRandomGenerator());
  1528. } while (VLC->creh->objects[newMonster.second] &&
  1529. (*VLC->townh)[VLC->creatures()->getById(newMonster.second)->getFaction()]->town == nullptr); // find first non neutral creature
  1530. n.creatureid = newMonster.second;
  1531. }
  1532. }
  1533. }
  1534. }
  1535. for (auto & elem : gs->players)
  1536. {
  1537. if (elem.first == PlayerColor::NEUTRAL)
  1538. continue;
  1539. else if (elem.first >= PlayerColor::PLAYER_LIMIT)
  1540. assert(0); //illegal player number!
  1541. std::pair<PlayerColor, si32> playerGold(elem.first, elem.second.resources[EGameResID::GOLD]);
  1542. hadGold.insert(playerGold);
  1543. if (newWeek) //new heroes in tavern
  1544. heroPool->onNewWeek(elem.first);
  1545. n.res[elem.first] = elem.second.resources;
  1546. if(!firstTurn && newWeek) //weekly crystal generation if 1 or more crystal dragons in any hero army or town garrison
  1547. {
  1548. bool hasCrystalGenCreature = false;
  1549. for(CGHeroInstance * hero : elem.second.heroes)
  1550. {
  1551. for(auto stack : hero->stacks)
  1552. {
  1553. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  1554. {
  1555. hasCrystalGenCreature = true;
  1556. break;
  1557. }
  1558. }
  1559. }
  1560. if(!hasCrystalGenCreature) //not found in armies, check towns
  1561. {
  1562. for(CGTownInstance * town : elem.second.towns)
  1563. {
  1564. for(auto stack : town->stacks)
  1565. {
  1566. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  1567. {
  1568. hasCrystalGenCreature = true;
  1569. break;
  1570. }
  1571. }
  1572. }
  1573. }
  1574. if(hasCrystalGenCreature)
  1575. n.res[elem.first][EGameResID::CRYSTAL] += 3;
  1576. }
  1577. for (CGHeroInstance *h : (elem).second.heroes)
  1578. {
  1579. if (h->visitedTown)
  1580. giveSpells(h->visitedTown, h);
  1581. NewTurn::Hero hth;
  1582. hth.id = h->id;
  1583. auto ti = std::make_unique<TurnInfo>(h, 1);
  1584. // TODO: this code executed when bonuses of previous day not yet updated (this happen in NewTurn::applyGs). See issue 2356
  1585. hth.move = h->movementPointsLimitCached(gs->map->getTile(h->visitablePos()).terType->isLand(), ti.get());
  1586. hth.mana = h->getManaNewTurn();
  1587. n.heroes.insert(hth);
  1588. if (!firstTurn) //not first day
  1589. {
  1590. for (int k = 0; k < GameConstants::RESOURCE_QUANTITY; k++)
  1591. {
  1592. n.res[elem.first][k] += h->valOfBonuses(BonusType::GENERATE_RESOURCE, k);
  1593. }
  1594. }
  1595. }
  1596. }
  1597. for (CGTownInstance *t : gs->map->towns)
  1598. {
  1599. PlayerColor player = t->tempOwner;
  1600. handleTownEvents(t, n);
  1601. if (newWeek) //first day of week
  1602. {
  1603. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  1604. setPortalDwelling(t, true, (n.specialWeek == NewTurn::PLAGUE ? true : false)); //set creatures for Portal of Summoning
  1605. if (!firstTurn)
  1606. if (t->hasBuilt(BuildingSubID::TREASURY) && player < PlayerColor::PLAYER_LIMIT)
  1607. n.res[player][EGameResID::GOLD] += hadGold.at(player)/10; //give 10% of starting gold
  1608. if (!vstd::contains(n.cres, t->id))
  1609. {
  1610. n.cres[t->id].tid = t->id;
  1611. n.cres[t->id].creatures = t->creatures;
  1612. }
  1613. auto & sac = n.cres.at(t->id);
  1614. for (int k=0; k < GameConstants::CREATURES_PER_TOWN; k++) //creature growths
  1615. {
  1616. if (!t->creatures.at(k).second.empty()) // there are creatures at this level
  1617. {
  1618. ui32 &availableCount = sac.creatures.at(k).first;
  1619. const CCreature *cre = VLC->creh->objects.at(t->creatures.at(k).second.back());
  1620. if (n.specialWeek == NewTurn::PLAGUE)
  1621. availableCount = t->creatures.at(k).first / 2; //halve their number, no growth
  1622. else
  1623. {
  1624. if (firstTurn) //first day of game: use only basic growths
  1625. availableCount = cre->getGrowth();
  1626. else
  1627. availableCount += t->creatureGrowth(k);
  1628. //Deity of fire week - upgrade both imps and upgrades
  1629. if (n.specialWeek == NewTurn::DEITYOFFIRE && vstd::contains(t->creatures.at(k).second, n.creatureid))
  1630. availableCount += 15;
  1631. if (cre->getId() == n.creatureid) //bonus week, effect applies only to identical creatures
  1632. {
  1633. if (n.specialWeek == NewTurn::DOUBLE_GROWTH)
  1634. availableCount *= 2;
  1635. else if (n.specialWeek == NewTurn::BONUS_GROWTH)
  1636. availableCount += 5;
  1637. }
  1638. }
  1639. }
  1640. }
  1641. }
  1642. if (!firstTurn && player < PlayerColor::PLAYER_LIMIT)//not the first day and town not neutral
  1643. {
  1644. n.res[player] = n.res[player] + t->dailyIncome();
  1645. }
  1646. if(t->hasBuilt(BuildingID::GRAIL)
  1647. && t->town->buildings.at(BuildingID::GRAIL)->height == CBuilding::HEIGHT_SKYSHIP)
  1648. {
  1649. // Skyship, probably easier to handle same as Veil of darkness
  1650. //do it every new day after veils apply
  1651. if (player != PlayerColor::NEUTRAL) //do not reveal fow for neutral player
  1652. {
  1653. FoWChange fw;
  1654. fw.mode = 1;
  1655. fw.player = player;
  1656. // find all hidden tiles
  1657. const auto fow = getPlayerTeam(player)->fogOfWarMap;
  1658. auto shape = fow->shape();
  1659. for(size_t z = 0; z < shape[0]; z++)
  1660. for(size_t x = 0; x < shape[1]; x++)
  1661. for(size_t y = 0; y < shape[2]; y++)
  1662. if (!(*fow)[z][x][y])
  1663. fw.tiles.insert(int3(x, y, z));
  1664. sendAndApply (&fw);
  1665. }
  1666. }
  1667. if (t->hasBonusOfType (BonusType::DARKNESS))
  1668. {
  1669. for (auto & player : gs->players)
  1670. {
  1671. if (getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  1672. getPlayerRelations(player.first, t->tempOwner) == PlayerRelations::ENEMIES)
  1673. changeFogOfWar(t->visitablePos(), t->getBonusLocalFirst(Selector::type()(BonusType::DARKNESS))->val, player.first, true);
  1674. }
  1675. }
  1676. }
  1677. if (newMonth)
  1678. {
  1679. SetAvailableArtifacts saa;
  1680. saa.id = -1;
  1681. pickAllowedArtsSet(saa.arts, getRandomGenerator());
  1682. sendAndApply(&saa);
  1683. }
  1684. sendAndApply(&n);
  1685. if (newWeek)
  1686. {
  1687. //spawn wandering monsters
  1688. if (newMonth && (n.specialWeek == NewTurn::DOUBLE_GROWTH || n.specialWeek == NewTurn::DEITYOFFIRE))
  1689. {
  1690. spawnWanderingMonsters(n.creatureid);
  1691. }
  1692. //new week info popup
  1693. if (!firstTurn)
  1694. {
  1695. InfoWindow iw;
  1696. switch (n.specialWeek)
  1697. {
  1698. case NewTurn::DOUBLE_GROWTH:
  1699. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 131);
  1700. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1701. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1702. break;
  1703. case NewTurn::PLAGUE:
  1704. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 132);
  1705. break;
  1706. case NewTurn::BONUS_GROWTH:
  1707. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 134);
  1708. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1709. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1710. break;
  1711. case NewTurn::DEITYOFFIRE:
  1712. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 135);
  1713. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  1714. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  1715. iw.text.replacePositiveNumber(15); //%+d 15
  1716. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 43); //%s familiar
  1717. iw.text.replacePositiveNumber(15); //%+d 15
  1718. break;
  1719. default:
  1720. if (newMonth)
  1721. {
  1722. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (130));
  1723. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(32, 41));
  1724. }
  1725. else
  1726. {
  1727. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (133));
  1728. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(43, 57));
  1729. }
  1730. }
  1731. for (auto & elem : gs->players)
  1732. {
  1733. iw.player = elem.first;
  1734. sendAndApply(&iw);
  1735. }
  1736. }
  1737. }
  1738. logGlobal->trace("Info about turn %d has been sent!", n.day);
  1739. handleTimeEvents();
  1740. //call objects
  1741. for (auto & elem : gs->map->objects)
  1742. {
  1743. if (elem)
  1744. elem->newTurn(getRandomGenerator());
  1745. }
  1746. synchronizeArtifactHandlerLists(); //new day events may have changed them. TODO better of managing that
  1747. }
  1748. void CGameHandler::run(bool resume)
  1749. {
  1750. LOG_TRACE_PARAMS(logGlobal, "resume=%d", resume);
  1751. using namespace boost::posix_time;
  1752. for (auto cc : lobby->connections)
  1753. {
  1754. auto players = lobby->getAllClientPlayers(cc->connectionID);
  1755. std::stringstream sbuffer;
  1756. sbuffer << "Connection " << cc->connectionID << " will handle " << players.size() << " player: ";
  1757. for (PlayerColor color : players)
  1758. {
  1759. sbuffer << color << " ";
  1760. {
  1761. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1762. connections[color].insert(cc);
  1763. }
  1764. }
  1765. logGlobal->info(sbuffer.str());
  1766. }
  1767. #if SCRIPTING_ENABLED
  1768. services()->scripts()->run(serverScripts);
  1769. #endif
  1770. if(resume)
  1771. events::GameResumed::defaultExecute(serverEventBus.get());
  1772. auto playerTurnOrder = generatePlayerTurnOrder();
  1773. if(!resume)
  1774. for(auto & playerColor : playerTurnOrder)
  1775. turnTimerHandler.onGameplayStart(gs->players[playerColor]);
  1776. while(lobby->state == EServerState::GAMEPLAY)
  1777. {
  1778. if(!resume)
  1779. {
  1780. newTurn();
  1781. events::TurnStarted::defaultExecute(serverEventBus.get());
  1782. }
  1783. std::list<PlayerColor>::iterator it;
  1784. if (resume)
  1785. {
  1786. it = std::find(playerTurnOrder.begin(), playerTurnOrder.end(), gs->currentPlayer);
  1787. }
  1788. else
  1789. {
  1790. it = playerTurnOrder.begin();
  1791. }
  1792. resume = false;
  1793. for (; (it != playerTurnOrder.end()) && (lobby->state == EServerState::GAMEPLAY) ; it++)
  1794. {
  1795. auto playerColor = *it;
  1796. auto onGetTurn = [&](events::PlayerGotTurn & event)
  1797. {
  1798. //if player runs out of time, he shouldn't get the turn (especially AI)
  1799. //pre-trigger may change anything, should check before each player
  1800. //TODO: is it enough to check only one player?
  1801. checkVictoryLossConditionsForAll();
  1802. auto player = event.getPlayer();
  1803. const PlayerState * playerState = &gs->players[player];
  1804. if(playerState->status != EPlayerStatus::INGAME)
  1805. {
  1806. event.setPlayer(PlayerColor::CANNOT_DETERMINE);
  1807. }
  1808. else
  1809. {
  1810. states.setFlag(player, &PlayerStatus::makingTurn, true);
  1811. YourTurn yt;
  1812. yt.player = player;
  1813. //Change local daysWithoutCastle counter for local interface message //TODO: needed?
  1814. yt.daysWithoutCastle = playerState->daysWithoutCastle;
  1815. applyAndSend(&yt);
  1816. turnTimerHandler.onPlayerGetTurn(gs->players[player]);
  1817. }
  1818. };
  1819. events::PlayerGotTurn::defaultExecute(serverEventBus.get(), onGetTurn, playerColor);
  1820. if(playerColor != PlayerColor::CANNOT_DETERMINE)
  1821. {
  1822. //wait till turn is done
  1823. const int waitTime = 100; //ms
  1824. boost::unique_lock<boost::mutex> lock(states.mx);
  1825. while(states.players.at(playerColor).makingTurn && lobby->state == EServerState::GAMEPLAY)
  1826. {
  1827. turnTimerHandler.onPlayerMakingTurn(gs->players[playerColor], waitTime);
  1828. if(gs->curB)
  1829. {
  1830. turnTimerHandler.onBattleLoop(gs->players[gs->curB->getSidePlayer(BattleSide::ATTACKER)], waitTime);
  1831. turnTimerHandler.onBattleLoop(gs->players[gs->curB->getSidePlayer(BattleSide::DEFENDER)], waitTime);
  1832. }
  1833. static time_duration p = milliseconds(waitTime);
  1834. states.cv.timed_wait(lock, p);
  1835. }
  1836. }
  1837. }
  1838. //additional check that game is not finished
  1839. bool activePlayer = false;
  1840. for (auto player : playerTurnOrder)
  1841. {
  1842. if (gs->players[player].status == EPlayerStatus::INGAME)
  1843. activePlayer = true;
  1844. }
  1845. if(!activePlayer)
  1846. lobby->state = EServerState::GAMEPLAY_ENDED;
  1847. }
  1848. }
  1849. std::list<PlayerColor> CGameHandler::generatePlayerTurnOrder() const
  1850. {
  1851. // Generate player turn order
  1852. std::list<PlayerColor> playerTurnOrder;
  1853. for (const auto & player : gs->players) // add human players first
  1854. {
  1855. if (player.second.human)
  1856. playerTurnOrder.push_back(player.first);
  1857. }
  1858. for (const auto & player : gs->players) // then add non-human players
  1859. {
  1860. if (!player.second.human)
  1861. playerTurnOrder.push_back(player.first);
  1862. }
  1863. return playerTurnOrder;
  1864. }
  1865. void CGameHandler::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town)
  1866. {
  1867. battleResult.set(nullptr);
  1868. const auto & t = *getTile(tile);
  1869. TerrainId terrain = t.terType->getId();
  1870. if (gs->map->isCoastalTile(tile)) //coastal tile is always ground
  1871. terrain = ETerrainId::SAND;
  1872. BattleField terType = gs->battleGetBattlefieldType(tile, getRandomGenerator());
  1873. if (heroes[0] && heroes[0]->boat && heroes[1] && heroes[1]->boat)
  1874. terType = BattleField(*VLC->identifiers()->getIdentifier("core", "battlefield.ship_to_ship"));
  1875. //send info about battles
  1876. BattleStart bs;
  1877. bs.info = BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  1878. engageIntoBattle(bs.info->sides[0].color);
  1879. engageIntoBattle(bs.info->sides[1].color);
  1880. auto lastBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(bs.info->sides[0].color));
  1881. bs.info->replayAllowed = lastBattleQuery == nullptr && !bs.info->sides[1].color.isValidPlayer();
  1882. sendAndApply(&bs);
  1883. }
  1884. void CGameHandler::checkBattleStateChanges()
  1885. {
  1886. //check if drawbridge state need to be changes
  1887. if (battleGetSiegeLevel() > 0)
  1888. updateGateState();
  1889. //check if battle ended
  1890. if (auto result = battleIsFinished())
  1891. {
  1892. setBattleResult(BattleResult::NORMAL, *result);
  1893. }
  1894. }
  1895. void CGameHandler::giveSpells(const CGTownInstance *t, const CGHeroInstance *h)
  1896. {
  1897. if (!h->hasSpellbook())
  1898. return; //hero hasn't spellbook
  1899. ChangeSpells cs;
  1900. cs.hid = h->id;
  1901. cs.learn = true;
  1902. if (t->hasBuilt(BuildingID::GRAIL, ETownType::CONFLUX) && t->hasBuilt(BuildingID::MAGES_GUILD_1))
  1903. {
  1904. // Aurora Borealis give spells of all levels even if only level 1 mages guild built
  1905. for (int i = 0; i < h->maxSpellLevel(); i++)
  1906. {
  1907. std::vector<SpellID> spells;
  1908. getAllowedSpells(spells, i+1);
  1909. for (auto & spell : spells)
  1910. cs.spells.insert(spell);
  1911. }
  1912. }
  1913. else
  1914. {
  1915. for (int i = 0; i < std::min(t->mageGuildLevel(), h->maxSpellLevel()); i++)
  1916. {
  1917. for (int j = 0; j < t->spellsAtLevel(i+1, true) && j < t->spells.at(i).size(); j++)
  1918. {
  1919. if (!h->spellbookContainsSpell(t->spells.at(i).at(j)))
  1920. cs.spells.insert(t->spells.at(i).at(j));
  1921. }
  1922. }
  1923. }
  1924. if (!cs.spells.empty())
  1925. sendAndApply(&cs);
  1926. }
  1927. bool CGameHandler::removeObject(const CGObjectInstance * obj)
  1928. {
  1929. if (!obj || !getObj(obj->id))
  1930. {
  1931. logGlobal->error("Something wrong, that object already has been removed or hasn't existed!");
  1932. return false;
  1933. }
  1934. RemoveObject ro;
  1935. ro.id = obj->id;
  1936. sendAndApply(&ro);
  1937. checkVictoryLossConditionsForAll(); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1938. return true;
  1939. }
  1940. bool CGameHandler::moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit, PlayerColor asker)
  1941. {
  1942. const CGHeroInstance *h = getHero(hid);
  1943. // not turn of that hero or player can't simply teleport hero (at least not with this function)
  1944. if (!h || (asker != PlayerColor::NEUTRAL && (teleporting || h->getOwner() != gs->currentPlayer)))
  1945. {
  1946. if(h && getStartInfo()->turnTimerInfo.isEnabled() && gs->players[h->getOwner()].turnTimer.turnTimer == 0)
  1947. return true; //timer expired, no error
  1948. logGlobal->error("Illegal call to move hero!");
  1949. return false;
  1950. }
  1951. logGlobal->trace("Player %d (%s) wants to move hero %d from %s to %s", asker, asker.getStr(), hid.getNum(), h->pos.toString(), dst.toString());
  1952. const int3 hmpos = h->convertToVisitablePos(dst);
  1953. if (!gs->map->isInTheMap(hmpos))
  1954. {
  1955. logGlobal->error("Destination tile is outside the map!");
  1956. return false;
  1957. }
  1958. const TerrainTile t = *getTile(hmpos);
  1959. const int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1960. const bool embarking = !h->boat && !t.visitableObjects.empty() && t.visitableObjects.back()->ID == Obj::BOAT;
  1961. const bool disembarking = h->boat
  1962. && t.terType->isLand()
  1963. && (dst == h->pos
  1964. || (h->boat->layer == EPathfindingLayer::SAIL && !t.blocked));
  1965. //result structure for start - movement failed, no move points used
  1966. TryMoveHero tmh;
  1967. tmh.id = hid;
  1968. tmh.start = h->pos;
  1969. tmh.end = dst;
  1970. tmh.result = TryMoveHero::FAILED;
  1971. tmh.movePoints = h->movementPointsRemaining();
  1972. //check if destination tile is available
  1973. auto pathfinderHelper = std::make_unique<CPathfinderHelper>(gs, h, PathfinderOptions());
  1974. auto ti = pathfinderHelper->getTurnInfo();
  1975. const bool canFly = pathfinderHelper->hasBonusOfType(BonusType::FLYING_MOVEMENT) || (h->boat && h->boat->layer == EPathfindingLayer::AIR);
  1976. const bool canWalkOnSea = pathfinderHelper->hasBonusOfType(BonusType::WATER_WALKING) || (h->boat && h->boat->layer == EPathfindingLayer::WATER);
  1977. const int cost = pathfinderHelper->getMovementCost(h->visitablePos(), hmpos, nullptr, nullptr, h->movementPointsRemaining());
  1978. //it's a rock or blocked and not visitable tile
  1979. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1980. if (((!t.terType->isPassable() || (t.blocked && !t.visitable && !canFly))
  1981. && complain("Cannot move hero, destination tile is blocked!"))
  1982. || ((!h->boat && !canWalkOnSea && !canFly && t.terType->isWater() && (t.visitableObjects.size() < 1 || !t.visitableObjects.back()->isCoastVisitable())) //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)
  1983. && complain("Cannot move hero, destination tile is on water!"))
  1984. || ((h->boat && h->boat->layer == EPathfindingLayer::SAIL && t.terType->isLand() && t.blocked)
  1985. && complain("Cannot disembark hero, tile is blocked!"))
  1986. || ((distance(h->pos, dst) >= 1.5 && !teleporting)
  1987. && complain("Tiles are not neighboring!"))
  1988. || ((h->inTownGarrison)
  1989. && complain("Can not move garrisoned hero!"))
  1990. || (((int)h->movementPointsRemaining() < cost && dst != h->pos && !teleporting)
  1991. && complain("Hero doesn't have any movement points left!"))
  1992. || ((transit && !canFly && !CGTeleport::isTeleport(t.topVisitableObj()))
  1993. && complain("Hero cannot transit over this tile!"))
  1994. /*|| (states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1995. && complain("Cannot move hero during the battle"))*/)
  1996. {
  1997. //send info about movement failure
  1998. sendAndApply(&tmh);
  1999. return false;
  2000. }
  2001. //several generic blocks of code
  2002. // should be called if hero changes tile but before applying TryMoveHero package
  2003. auto leaveTile = [&]()
  2004. {
  2005. for (CGObjectInstance *obj : gs->map->getTile(int3(h->pos.x-1, h->pos.y, h->pos.z)).visitableObjects)
  2006. {
  2007. obj->onHeroLeave(h);
  2008. }
  2009. this->getTilesInRange(tmh.fowRevealed, h->getSightCenter()+(tmh.end-tmh.start), h->getSightRadius(), h->tempOwner, 1);
  2010. };
  2011. auto doMove = [&](TryMoveHero::EResult result, EGuardLook lookForGuards,
  2012. EVisitDest visitDest, ELEaveTile leavingTile) -> bool
  2013. {
  2014. LOG_TRACE_PARAMS(logGlobal, "Hero %s starts movement from %s to %s", h->getNameTranslated() % tmh.start.toString() % tmh.end.toString());
  2015. auto moveQuery = std::make_shared<CHeroMovementQuery>(this, tmh, h);
  2016. queries.addQuery(moveQuery);
  2017. if (leavingTile == LEAVING_TILE)
  2018. leaveTile();
  2019. if (isInTheMap(guardPos))
  2020. tmh.attackedFrom = std::make_optional(guardPos);
  2021. tmh.result = result;
  2022. sendAndApply(&tmh);
  2023. if (visitDest == VISIT_DEST && t.topVisitableObj() && t.topVisitableObj()->id == h->id)
  2024. { // Hero should be always able to visit any object he staying on even if there guards around
  2025. visitObjectOnTile(t, h);
  2026. }
  2027. else if (lookForGuards == CHECK_FOR_GUARDS && isInTheMap(guardPos))
  2028. {
  2029. const TerrainTile &guardTile = *gs->getTile(guardPos);
  2030. objectVisited(guardTile.visitableObjects.back(), h);
  2031. moveQuery->visitDestAfterVictory = visitDest==VISIT_DEST;
  2032. }
  2033. else if (visitDest == VISIT_DEST)
  2034. {
  2035. visitObjectOnTile(t, h);
  2036. }
  2037. if(!transit)
  2038. {
  2039. for(auto topQuery = queries.topQuery(h->tempOwner); true; topQuery = queries.topQuery(h->tempOwner))
  2040. {
  2041. moveQuery = std::dynamic_pointer_cast<CHeroMovementQuery>(topQuery);
  2042. if(moveQuery)
  2043. queries.popIfTop(moveQuery);
  2044. else
  2045. break;
  2046. }
  2047. }
  2048. logGlobal->trace("Hero %s ends movement", h->getNameTranslated());
  2049. return result != TryMoveHero::FAILED;
  2050. };
  2051. //interaction with blocking object (like resources)
  2052. auto blockingVisit = [&]() -> bool
  2053. {
  2054. for (CGObjectInstance *obj : t.visitableObjects)
  2055. {
  2056. if(h->boat && !obj->isBlockedVisitable() && !h->boat->onboardVisitAllowed)
  2057. return doMove(TryMoveHero::SUCCESS, this->IGNORE_GUARDS, DONT_VISIT_DEST, REMAINING_ON_TILE);
  2058. if (obj != h && obj->isBlockedVisitable() && !obj->passableFor(h->tempOwner))
  2059. {
  2060. EVisitDest visitDest = VISIT_DEST;
  2061. if(h->boat && !h->boat->onboardVisitAllowed)
  2062. visitDest = DONT_VISIT_DEST;
  2063. return doMove(TryMoveHero::BLOCKING_VISIT, this->IGNORE_GUARDS, visitDest, REMAINING_ON_TILE);
  2064. }
  2065. }
  2066. return false;
  2067. };
  2068. if (!transit && embarking)
  2069. {
  2070. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, false, ti);
  2071. return doMove(TryMoveHero::EMBARK, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  2072. // In H3 embark ignore guards
  2073. }
  2074. if (disembarking)
  2075. {
  2076. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, true, ti);
  2077. return doMove(TryMoveHero::DISEMBARK, CHECK_FOR_GUARDS, VISIT_DEST, LEAVING_TILE);
  2078. }
  2079. if (teleporting)
  2080. {
  2081. if (blockingVisit()) // e.g. hero on the other side of teleporter
  2082. return true;
  2083. doMove(TryMoveHero::TELEPORTATION, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  2084. // visit town for town portal \ castle gates
  2085. // do not use generic visitObjectOnTile to avoid double-teleporting
  2086. // if this moveHero call was triggered by teleporter
  2087. if (!t.visitableObjects.empty())
  2088. {
  2089. if (CGTownInstance * town = dynamic_cast<CGTownInstance *>(t.visitableObjects.back()))
  2090. town->onHeroVisit(h);
  2091. }
  2092. return true;
  2093. }
  2094. //still here? it is standard movement!
  2095. {
  2096. tmh.movePoints = (int)h->movementPointsRemaining() >= cost
  2097. ? h->movementPointsRemaining() - cost
  2098. : 0;
  2099. EGuardLook lookForGuards = CHECK_FOR_GUARDS;
  2100. EVisitDest visitDest = VISIT_DEST;
  2101. if (transit)
  2102. {
  2103. if (CGTeleport::isTeleport(t.topVisitableObj()))
  2104. visitDest = DONT_VISIT_DEST;
  2105. if (canFly)
  2106. {
  2107. lookForGuards = IGNORE_GUARDS;
  2108. visitDest = DONT_VISIT_DEST;
  2109. }
  2110. }
  2111. else if (blockingVisit())
  2112. return true;
  2113. if(h->boat && !h->boat->onboardAssaultAllowed)
  2114. lookForGuards = IGNORE_GUARDS;
  2115. doMove(TryMoveHero::SUCCESS, lookForGuards, visitDest, LEAVING_TILE);
  2116. return true;
  2117. }
  2118. }
  2119. bool CGameHandler::teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker)
  2120. {
  2121. const CGHeroInstance *h = getHero(hid);
  2122. const CGTownInstance *t = getTown(dstid);
  2123. if (!h || !t || h->getOwner() != gs->currentPlayer)
  2124. COMPLAIN_RET("Invalid call to teleportHero!");
  2125. const CGTownInstance *from = h->visitedTown;
  2126. if (((h->getOwner() != t->getOwner())
  2127. && complain("Cannot teleport hero to another player"))
  2128. || (from->town->faction->getId() != t->town->faction->getId()
  2129. && complain("Source town and destination town should belong to the same faction"))
  2130. || ((!from || !from->hasBuilt(BuildingSubID::CASTLE_GATE))
  2131. && complain("Hero must be in town with Castle gate for teleporting"))
  2132. || (!t->hasBuilt(BuildingSubID::CASTLE_GATE)
  2133. && complain("Cannot teleport hero to town without Castle gate in it")))
  2134. return false;
  2135. int3 pos = h->convertFromVisitablePos(t->visitablePos());
  2136. moveHero(hid,pos,1);
  2137. return true;
  2138. }
  2139. void CGameHandler::setOwner(const CGObjectInstance * obj, const PlayerColor owner)
  2140. {
  2141. PlayerColor oldOwner = getOwner(obj->id);
  2142. SetObjectProperty sop(obj->id, ObjProperty::OWNER, owner.getNum());
  2143. sendAndApply(&sop);
  2144. std::set<PlayerColor> playerColors = {owner, oldOwner};
  2145. checkVictoryLossConditions(playerColors);
  2146. const CGTownInstance * town = dynamic_cast<const CGTownInstance *>(obj);
  2147. if (town) //town captured
  2148. {
  2149. if (owner < PlayerColor::PLAYER_LIMIT) //new owner is real player
  2150. {
  2151. if (town->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  2152. setPortalDwelling(town, true, false);
  2153. }
  2154. if (oldOwner < PlayerColor::PLAYER_LIMIT) //old owner is real player
  2155. {
  2156. if (getPlayerState(oldOwner)->towns.empty() && getPlayerState(oldOwner)->status != EPlayerStatus::LOSER) //previous player lost last last town
  2157. {
  2158. InfoWindow iw;
  2159. iw.player = oldOwner;
  2160. iw.text.appendLocalString(EMetaText::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.
  2161. iw.text.replaceLocalString(EMetaText::COLOR, oldOwner.getNum());
  2162. sendAndApply(&iw);
  2163. }
  2164. }
  2165. }
  2166. const PlayerState * p = getPlayerState(owner);
  2167. if ((obj->ID == Obj::CREATURE_GENERATOR1 || obj->ID == Obj::CREATURE_GENERATOR4) && p && p->dwellings.size()==1)//first dwelling captured
  2168. {
  2169. for (const CGTownInstance * t : getPlayerState(owner)->towns)
  2170. {
  2171. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  2172. setPortalDwelling(t);//set initial creatures for all portals of summoning
  2173. }
  2174. }
  2175. }
  2176. void CGameHandler::showBlockingDialog(BlockingDialog *iw)
  2177. {
  2178. auto dialogQuery = std::make_shared<CBlockingDialogQuery>(this, *iw);
  2179. queries.addQuery(dialogQuery);
  2180. iw->queryID = dialogQuery->queryID;
  2181. sendToAllClients(iw);
  2182. }
  2183. void CGameHandler::showTeleportDialog(TeleportDialog *iw)
  2184. {
  2185. auto dialogQuery = std::make_shared<CTeleportDialogQuery>(this, *iw);
  2186. queries.addQuery(dialogQuery);
  2187. iw->queryID = dialogQuery->queryID;
  2188. sendToAllClients(iw);
  2189. }
  2190. void CGameHandler::giveResource(PlayerColor player, GameResID which, int val) //TODO: cap according to Bersy's suggestion
  2191. {
  2192. if (!val) return; //don't waste time on empty call
  2193. TResources resources;
  2194. resources[which] = val;
  2195. giveResources(player, resources);
  2196. }
  2197. void CGameHandler::giveResources(PlayerColor player, TResources resources)
  2198. {
  2199. SetResources sr;
  2200. sr.abs = false;
  2201. sr.player = player;
  2202. sr.res = resources;
  2203. sendAndApply(&sr);
  2204. }
  2205. void CGameHandler::giveCreatures(const CArmedInstance *obj, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove)
  2206. {
  2207. COMPLAIN_RET_IF(!creatures.stacksCount(), "Strange, giveCreatures called without args!");
  2208. COMPLAIN_RET_IF(obj->stacksCount(), "Cannot give creatures from not-cleared object!");
  2209. COMPLAIN_RET_IF(creatures.stacksCount() > GameConstants::ARMY_SIZE, "Too many stacks to give!");
  2210. //first we move creatures to give to make them army of object-source
  2211. for (auto & elem : creatures.Slots())
  2212. {
  2213. addToSlot(StackLocation(obj, obj->getSlotFor(elem.second->type)), elem.second->type, elem.second->count);
  2214. }
  2215. tryJoiningArmy(obj, h, remove, true);
  2216. }
  2217. void CGameHandler::takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures)
  2218. {
  2219. std::vector<CStackBasicDescriptor> cres = creatures;
  2220. if (cres.size() <= 0)
  2221. return;
  2222. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  2223. for (CStackBasicDescriptor &sbd : cres)
  2224. {
  2225. TQuantity collected = 0;
  2226. while(collected < sbd.count)
  2227. {
  2228. bool foundSth = false;
  2229. for (auto i = obj->Slots().begin(); i != obj->Slots().end(); i++)
  2230. {
  2231. if (i->second->type == sbd.type)
  2232. {
  2233. TQuantity take = std::min(sbd.count - collected, i->second->count); //collect as much cres as we can
  2234. changeStackCount(StackLocation(obj, i->first), -take, false);
  2235. collected += take;
  2236. foundSth = true;
  2237. break;
  2238. }
  2239. }
  2240. if (!foundSth) //we went through the whole loop and haven't found appropriate cres
  2241. {
  2242. complain("Unexpected failure during taking creatures!");
  2243. return;
  2244. }
  2245. }
  2246. }
  2247. }
  2248. void CGameHandler::heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  2249. {
  2250. HeroVisitCastle vc;
  2251. vc.hid = hero->id;
  2252. vc.tid = obj->id;
  2253. vc.flags |= 1;
  2254. sendAndApply(&vc);
  2255. visitCastleObjects(obj, hero);
  2256. giveSpells (obj, hero);
  2257. checkVictoryLossConditionsForPlayer(hero->tempOwner); //transported artifact?
  2258. }
  2259. void CGameHandler::visitCastleObjects(const CGTownInstance * t, const CGHeroInstance * h)
  2260. {
  2261. for (auto building : t->bonusingBuildings)
  2262. building->onHeroVisit(h);
  2263. }
  2264. void CGameHandler::stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  2265. {
  2266. HeroVisitCastle vc;
  2267. vc.hid = hero->id;
  2268. vc.tid = obj->id;
  2269. sendAndApply(&vc);
  2270. }
  2271. void CGameHandler::removeArtifact(const ArtifactLocation &al)
  2272. {
  2273. EraseArtifact ea;
  2274. ea.al = al;
  2275. sendAndApply(&ea);
  2276. }
  2277. void CGameHandler::startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile,
  2278. const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank,
  2279. const CGTownInstance *town) //use hero=nullptr for no hero
  2280. {
  2281. if(gs->curB)
  2282. gs->curB.dellNull();
  2283. static const CArmedInstance *armies[2];
  2284. armies[0] = army1;
  2285. armies[1] = army2;
  2286. static const CGHeroInstance*heroes[2];
  2287. heroes[0] = hero1;
  2288. heroes[1] = hero2;
  2289. setupBattle(tile, armies, heroes, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  2290. auto lastBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(gs->curB->sides[0].color));
  2291. //existing battle query for retying auto-combat
  2292. if(lastBattleQuery)
  2293. {
  2294. for(int i : {0, 1})
  2295. {
  2296. if(heroes[i])
  2297. {
  2298. SetMana restoreInitialMana;
  2299. restoreInitialMana.val = lastBattleQuery->initialHeroMana[i];
  2300. restoreInitialMana.hid = heroes[i]->id;
  2301. sendAndApply(&restoreInitialMana);
  2302. }
  2303. }
  2304. lastBattleQuery->bi = gs->curB;
  2305. lastBattleQuery->result = std::nullopt;
  2306. lastBattleQuery->belligerents[0] = gs->curB->sides[0].armyObject;
  2307. lastBattleQuery->belligerents[1] = gs->curB->sides[1].armyObject;
  2308. }
  2309. auto nextBattleQuery = std::make_shared<CBattleQuery>(this, gs->curB);
  2310. for(int i : {0, 1})
  2311. {
  2312. if(heroes[i])
  2313. {
  2314. nextBattleQuery->initialHeroMana[i] = heroes[i]->mana;
  2315. }
  2316. }
  2317. queries.addQuery(nextBattleQuery);
  2318. this->battleThread = std::make_unique<boost::thread>(boost::thread(&CGameHandler::runBattle, this));
  2319. }
  2320. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank)
  2321. {
  2322. startBattlePrimary(army1, army2, tile,
  2323. army1->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army1) : nullptr,
  2324. army2->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army2) : nullptr,
  2325. creatureBank);
  2326. }
  2327. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank)
  2328. {
  2329. startBattleI(army1, army2, army2->visitablePos(), creatureBank);
  2330. }
  2331. void CGameHandler::changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells)
  2332. {
  2333. ChangeSpells cs;
  2334. cs.hid = hero->id;
  2335. cs.spells = spells;
  2336. cs.learn = give;
  2337. sendAndApply(&cs);
  2338. }
  2339. void CGameHandler::giveHeroBonus(GiveBonus * bonus)
  2340. {
  2341. sendAndApply(bonus);
  2342. }
  2343. void CGameHandler::setMovePoints(SetMovePoints * smp)
  2344. {
  2345. sendAndApply(smp);
  2346. }
  2347. void CGameHandler::setManaPoints(ObjectInstanceID hid, int val)
  2348. {
  2349. SetMana sm;
  2350. sm.hid = hid;
  2351. sm.val = val;
  2352. sm.absolute = true;
  2353. sendAndApply(&sm);
  2354. }
  2355. void CGameHandler::giveHero(ObjectInstanceID id, PlayerColor player, ObjectInstanceID boatId)
  2356. {
  2357. GiveHero gh;
  2358. gh.id = id;
  2359. gh.player = player;
  2360. gh.boatId = boatId;
  2361. sendAndApply(&gh);
  2362. //Reveal fow around new hero, especially released from Prison
  2363. auto h = getHero(id);
  2364. changeFogOfWar(h->pos, h->getSightRadius(), player, false);
  2365. }
  2366. void CGameHandler::changeObjPos(ObjectInstanceID objid, int3 newPos)
  2367. {
  2368. ChangeObjPos cop;
  2369. cop.objid = objid;
  2370. cop.nPos = newPos;
  2371. sendAndApply(&cop);
  2372. }
  2373. void CGameHandler::useScholarSkill(ObjectInstanceID fromHero, ObjectInstanceID toHero)
  2374. {
  2375. const CGHeroInstance * h1 = getHero(fromHero);
  2376. const CGHeroInstance * h2 = getHero(toHero);
  2377. int h1_scholarSpellLevel = h1->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  2378. int h2_scholarSpellLevel = h2->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  2379. if (h1_scholarSpellLevel < h2_scholarSpellLevel)
  2380. {
  2381. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  2382. std::swap(fromHero, toHero);
  2383. }
  2384. int ScholarSpellLevel = std::max(h1_scholarSpellLevel, h2_scholarSpellLevel);//heroes can trade up to this level
  2385. if (!ScholarSpellLevel || !h1->hasSpellbook() || !h2->hasSpellbook())
  2386. return;//no scholar skill or no spellbook
  2387. int h1Lvl = std::min(ScholarSpellLevel, h1->maxSpellLevel()),
  2388. h2Lvl = std::min(ScholarSpellLevel, h2->maxSpellLevel());//heroes can receive this levels
  2389. ChangeSpells cs1;
  2390. cs1.learn = true;
  2391. cs1.hid = toHero;//giving spells to first hero
  2392. for (auto it : h1->getSpellsInSpellbook())
  2393. if (h2Lvl >= it.toSpell()->level && !h2->spellbookContainsSpell(it))//hero can learn it and don't have it yet
  2394. cs1.spells.insert(it);//spell to learn
  2395. ChangeSpells cs2;
  2396. cs2.learn = true;
  2397. cs2.hid = fromHero;
  2398. for (auto it : h2->getSpellsInSpellbook())
  2399. if (h1Lvl >= it.toSpell()->level && !h1->spellbookContainsSpell(it))
  2400. cs2.spells.insert(it);
  2401. if (!cs1.spells.empty() || !cs2.spells.empty())//create a message
  2402. {
  2403. int ScholarSkillLevel = std::max(h1->getSecSkillLevel(SecondarySkill::SCHOLAR),
  2404. h2->getSecSkillLevel(SecondarySkill::SCHOLAR));
  2405. InfoWindow iw;
  2406. iw.player = h1->tempOwner;
  2407. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, 18, ScholarSkillLevel, 0);
  2408. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  2409. iw.text.replaceRawString(h1->getNameTranslated());
  2410. if (!cs2.spells.empty())//if found new spell - apply
  2411. {
  2412. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 140);//learns
  2413. int size = static_cast<int>(cs2.spells.size());
  2414. for (auto it : cs2.spells)
  2415. {
  2416. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  2417. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  2418. switch (size--)
  2419. {
  2420. case 2:
  2421. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  2422. case 1:
  2423. break;
  2424. default:
  2425. iw.text.appendRawString(", ");
  2426. }
  2427. }
  2428. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 142);//from %s
  2429. iw.text.replaceRawString(h2->getNameTranslated());
  2430. sendAndApply(&cs2);
  2431. }
  2432. if (!cs1.spells.empty() && !cs2.spells.empty())
  2433. {
  2434. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);//and
  2435. }
  2436. if (!cs1.spells.empty())
  2437. {
  2438. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 147);//teaches
  2439. int size = static_cast<int>(cs1.spells.size());
  2440. for (auto it : cs1.spells)
  2441. {
  2442. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  2443. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  2444. switch (size--)
  2445. {
  2446. case 2:
  2447. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  2448. case 1:
  2449. break;
  2450. default:
  2451. iw.text.appendRawString(", ");
  2452. }
  2453. }
  2454. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 148);//from %s
  2455. iw.text.replaceRawString(h2->getNameTranslated());
  2456. sendAndApply(&cs1);
  2457. }
  2458. sendAndApply(&iw);
  2459. }
  2460. }
  2461. void CGameHandler::heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  2462. {
  2463. auto h1 = getHero(hero1), h2 = getHero(hero2);
  2464. if (getPlayerRelations(h1->getOwner(), h2->getOwner()))
  2465. {
  2466. auto exchange = std::make_shared<CGarrisonDialogQuery>(this, h1, h2);
  2467. ExchangeDialog hex;
  2468. hex.queryID = exchange->queryID;
  2469. hex.player = h1->getOwner();
  2470. hex.hero1 = hero1;
  2471. hex.hero2 = hero2;
  2472. sendAndApply(&hex);
  2473. useScholarSkill(hero1,hero2);
  2474. queries.addQuery(exchange);
  2475. }
  2476. }
  2477. void CGameHandler::sendToAllClients(CPackForClient * pack)
  2478. {
  2479. logNetwork->trace("\tSending to all clients: %s", typeid(*pack).name());
  2480. for (auto c : lobby->connections)
  2481. {
  2482. if(!c->isOpen())
  2483. continue;
  2484. c->sendPack(pack);
  2485. }
  2486. }
  2487. void CGameHandler::sendAndApply(CPackForClient * pack)
  2488. {
  2489. sendToAllClients(pack);
  2490. gs->apply(pack);
  2491. logNetwork->trace("\tApplied on gs: %s", typeid(*pack).name());
  2492. }
  2493. void CGameHandler::applyAndSend(CPackForClient * pack)
  2494. {
  2495. gs->apply(pack);
  2496. sendToAllClients(pack);
  2497. }
  2498. void CGameHandler::sendAndApply(CGarrisonOperationPack * pack)
  2499. {
  2500. sendAndApply(static_cast<CPackForClient *>(pack));
  2501. checkVictoryLossConditionsForAll();
  2502. }
  2503. void CGameHandler::sendAndApply(SetResources * pack)
  2504. {
  2505. sendAndApply(static_cast<CPackForClient *>(pack));
  2506. checkVictoryLossConditionsForPlayer(pack->player);
  2507. }
  2508. void CGameHandler::sendAndApply(NewStructures * pack)
  2509. {
  2510. sendAndApply(static_cast<CPackForClient *>(pack));
  2511. checkVictoryLossConditionsForPlayer(getTown(pack->tid)->tempOwner);
  2512. }
  2513. bool CGameHandler::isPlayerOwns(CPackForServer * pack, ObjectInstanceID id)
  2514. {
  2515. return getPlayerAt(pack->c) == getOwner(id);
  2516. }
  2517. void CGameHandler::throwNotAllowedAction(CPackForServer * pack)
  2518. {
  2519. if(pack->c)
  2520. playerMessages->sendSystemMessage(pack->c, "You are not allowed to perform this action!");
  2521. logNetwork->error("Player is not allowed to perform this action!");
  2522. throw ExceptionNotAllowedAction();
  2523. }
  2524. void CGameHandler::wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer)
  2525. {
  2526. std::ostringstream oss;
  2527. oss << "You were identified as player " << getPlayerAt(pack->c) << " while expecting " << expectedplayer;
  2528. logNetwork->error(oss.str());
  2529. if(pack->c)
  2530. playerMessages->sendSystemMessage(pack->c, oss.str());
  2531. }
  2532. void CGameHandler::throwOnWrongOwner(CPackForServer * pack, ObjectInstanceID id)
  2533. {
  2534. if(!isPlayerOwns(pack, id))
  2535. {
  2536. wrongPlayerMessage(pack, getOwner(id));
  2537. throwNotAllowedAction(pack);
  2538. }
  2539. }
  2540. void CGameHandler::throwOnWrongPlayer(CPackForServer * pack, PlayerColor player)
  2541. {
  2542. if(!hasPlayerAt(player, pack->c) && player != getPlayerAt(pack->c))
  2543. {
  2544. wrongPlayerMessage(pack, player);
  2545. throwNotAllowedAction(pack);
  2546. }
  2547. }
  2548. void CGameHandler::throwAndComplain(CPackForServer * pack, std::string txt)
  2549. {
  2550. complain(txt);
  2551. throwNotAllowedAction(pack);
  2552. }
  2553. void CGameHandler::save(const std::string & filename)
  2554. {
  2555. logGlobal->info("Saving to %s", filename);
  2556. const auto stem = FileInfo::GetPathStem(filename);
  2557. const auto savefname = stem.to_string() + ".vsgm1";
  2558. CResourceHandler::get("local")->createResource(savefname);
  2559. try
  2560. {
  2561. {
  2562. CSaveFile save(*CResourceHandler::get("local")->getResourceName(ResourceID(stem.to_string(), EResType::SAVEGAME)));
  2563. saveCommonState(save);
  2564. logGlobal->info("Saving server state");
  2565. save << *this;
  2566. }
  2567. logGlobal->info("Game has been successfully saved!");
  2568. }
  2569. catch(std::exception &e)
  2570. {
  2571. logGlobal->error("Failed to save game: %s", e.what());
  2572. }
  2573. }
  2574. bool CGameHandler::load(const std::string & filename)
  2575. {
  2576. logGlobal->info("Loading from %s", filename);
  2577. const auto stem = FileInfo::GetPathStem(filename);
  2578. reinitScripting();
  2579. try
  2580. {
  2581. {
  2582. CLoadFile lf(*CResourceHandler::get()->getResourceName(ResourceID(stem.to_string(), EResType::SAVEGAME)), MINIMAL_SERIALIZATION_VERSION);
  2583. loadCommonState(lf);
  2584. logGlobal->info("Loading server state");
  2585. lf >> *this;
  2586. }
  2587. logGlobal->info("Game has been successfully loaded!");
  2588. }
  2589. catch(const ModIncompatibility & e)
  2590. {
  2591. logGlobal->error("Failed to load game: %s", e.what());
  2592. auto errorMsg = VLC->generaltexth->translate("vcmi.server.errors.modsIncompatibility") + '\n';
  2593. errorMsg += e.what();
  2594. lobby->announceMessage(errorMsg);
  2595. return false;
  2596. }
  2597. catch(const std::exception & e)
  2598. {
  2599. logGlobal->error("Failed to load game: %s", e.what());
  2600. return false;
  2601. }
  2602. gs->preInit(VLC);
  2603. gs->updateOnLoad(lobby->si.get());
  2604. return true;
  2605. }
  2606. bool CGameHandler::bulkSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner, si32 howMany)
  2607. {
  2608. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  2609. return false;
  2610. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  2611. const CCreatureSet & creatureSet = *army;
  2612. if((!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  2613. || (howMany < 1 && complain("Invalid split parameter!")))
  2614. {
  2615. return false;
  2616. }
  2617. auto actualAmount = army->getStackCount(slotSrc);
  2618. if(actualAmount <= howMany && complain(complainNotEnoughCreatures)) // '<=' because it's not intended just for moving a stack
  2619. return false;
  2620. auto freeSlots = creatureSet.getFreeSlots();
  2621. if(freeSlots.empty() && complain("No empty stacks"))
  2622. return false;
  2623. BulkRebalanceStacks bulkRS;
  2624. for(auto slot : freeSlots)
  2625. {
  2626. RebalanceStacks rs;
  2627. rs.srcArmy = army->id;
  2628. rs.dstArmy = army->id;
  2629. rs.srcSlot = slotSrc;
  2630. rs.dstSlot = slot;
  2631. rs.count = howMany;
  2632. bulkRS.moves.push_back(rs);
  2633. actualAmount -= howMany;
  2634. if(actualAmount <= howMany)
  2635. break;
  2636. }
  2637. sendAndApply(&bulkRS);
  2638. return true;
  2639. }
  2640. bool CGameHandler::bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner)
  2641. {
  2642. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  2643. return false;
  2644. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  2645. const CCreatureSet & creatureSet = *army;
  2646. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  2647. return false;
  2648. auto actualAmount = creatureSet.getStackCount(slotSrc);
  2649. if(actualAmount < 1 && complain(complainNoCreatures))
  2650. return false;
  2651. auto currentCreature = creatureSet.getCreature(slotSrc);
  2652. if(!currentCreature && complain(complainNoCreatures))
  2653. return false;
  2654. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, slotSrc);
  2655. if(!creatureSlots.size())
  2656. return false;
  2657. BulkRebalanceStacks bulkRS;
  2658. for(auto slot : creatureSlots)
  2659. {
  2660. RebalanceStacks rs;
  2661. rs.srcArmy = army->id;
  2662. rs.dstArmy = army->id;
  2663. rs.srcSlot = slot;
  2664. rs.dstSlot = slotSrc;
  2665. rs.count = creatureSet.getStackCount(slot);
  2666. bulkRS.moves.push_back(rs);
  2667. }
  2668. sendAndApply(&bulkRS);
  2669. return true;
  2670. }
  2671. bool CGameHandler::bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot)
  2672. {
  2673. if(!srcSlot.validSlot() && complain(complainInvalidSlot))
  2674. return false;
  2675. const CArmedInstance * armySrc = static_cast<const CArmedInstance*>(getObjInstance(srcArmy));
  2676. const CCreatureSet & setSrc = *armySrc;
  2677. if(!vstd::contains(setSrc.stacks, srcSlot) && complain(complainNoCreatures))
  2678. return false;
  2679. const CArmedInstance * armyDest = static_cast<const CArmedInstance*>(getObjInstance(destArmy));
  2680. const CCreatureSet & setDest = *armyDest;
  2681. auto freeSlots = setDest.getFreeSlotsQueue();
  2682. typedef std::map<SlotID, std::pair<SlotID, TQuantity>> TRebalanceMap;
  2683. TRebalanceMap moves;
  2684. auto srcQueue = setSrc.getCreatureQueue(srcSlot); // Exclude srcSlot, it should be moved last
  2685. auto slotsLeft = setSrc.stacksCount();
  2686. auto destMap = setDest.getCreatureMap();
  2687. TMapCreatureSlot::key_compare keyComp = destMap.key_comp();
  2688. while(!srcQueue.empty())
  2689. {
  2690. auto pair = srcQueue.top();
  2691. srcQueue.pop();
  2692. auto currCreature = pair.first;
  2693. auto currSlot = pair.second;
  2694. const auto quantity = setSrc.getStackCount(currSlot);
  2695. TMapCreatureSlot::iterator lb = destMap.lower_bound(currCreature);
  2696. const bool alreadyExists = (lb != destMap.end() && !(keyComp(currCreature, lb->first)));
  2697. if(!alreadyExists)
  2698. {
  2699. if(freeSlots.empty())
  2700. continue;
  2701. auto currFreeSlot = freeSlots.front();
  2702. freeSlots.pop();
  2703. destMap.insert(lb, TMapCreatureSlot::value_type(currCreature, currFreeSlot));
  2704. }
  2705. moves.insert(std::make_pair(currSlot, std::make_pair(destMap[currCreature], quantity)));
  2706. slotsLeft--;
  2707. }
  2708. if(slotsLeft == 1)
  2709. {
  2710. auto lastCreature = setSrc.getCreature(srcSlot);
  2711. auto slotToMove = SlotID();
  2712. // Try to find a slot for last creature
  2713. if(destMap.find(lastCreature) == destMap.end())
  2714. {
  2715. if(!freeSlots.empty())
  2716. slotToMove = freeSlots.front();
  2717. }
  2718. else
  2719. {
  2720. slotToMove = destMap[lastCreature];
  2721. }
  2722. if(slotToMove != SlotID())
  2723. {
  2724. const bool needsLastStack = armySrc->needsLastStack();
  2725. const auto quantity = setSrc.getStackCount(srcSlot) - (needsLastStack ? 1 : 0);
  2726. moves.insert(std::make_pair(srcSlot, std::make_pair(slotToMove, quantity)));
  2727. }
  2728. }
  2729. BulkRebalanceStacks bulkRS;
  2730. for(auto & move : moves)
  2731. {
  2732. RebalanceStacks rs;
  2733. rs.srcArmy = armySrc->id;
  2734. rs.dstArmy = armyDest->id;
  2735. rs.srcSlot = move.first;
  2736. rs.dstSlot = move.second.first;
  2737. rs.count = move.second.second;
  2738. bulkRS.moves.push_back(rs);
  2739. }
  2740. sendAndApply(&bulkRS);
  2741. return true;
  2742. }
  2743. bool CGameHandler::bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner)
  2744. {
  2745. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  2746. return false;
  2747. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  2748. const CCreatureSet & creatureSet = *army;
  2749. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  2750. return false;
  2751. auto actualAmount = creatureSet.getStackCount(slotSrc);
  2752. if(actualAmount <= 1 && complain(complainNoCreatures))
  2753. return false;
  2754. auto freeSlot = creatureSet.getFreeSlot();
  2755. auto currentCreature = creatureSet.getCreature(slotSrc);
  2756. if(freeSlot == SlotID() && creatureSet.isCreatureBalanced(currentCreature))
  2757. return true;
  2758. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, SlotID(-1), 1); // Ignore slots where's only 1 creature, don't ignore slotSrc
  2759. TQuantity totalCreatures = 0;
  2760. for(auto slot : creatureSlots)
  2761. totalCreatures += creatureSet.getStackCount(slot);
  2762. if(totalCreatures <= 1 && complain("Total creatures number is invalid"))
  2763. return false;
  2764. if(freeSlot != SlotID())
  2765. creatureSlots.push_back(freeSlot);
  2766. if(creatureSlots.empty() && complain("No available slots for smart rebalancing"))
  2767. return false;
  2768. const auto totalCreatureSlots = creatureSlots.size();
  2769. const auto rem = totalCreatures % totalCreatureSlots;
  2770. const auto quotient = totalCreatures / totalCreatureSlots;
  2771. // totalCreatures == rem * (quotient + 1) + (totalCreatureSlots - rem) * quotient;
  2772. // Proof: r(q+1)+(s-r)q = rq+r+qs-rq = r+qs = total, where total/s = q+r/s
  2773. BulkSmartRebalanceStacks bulkSRS;
  2774. if(freeSlot != SlotID())
  2775. {
  2776. RebalanceStacks rs;
  2777. rs.srcArmy = rs.dstArmy = army->id;
  2778. rs.srcSlot = slotSrc;
  2779. rs.dstSlot = freeSlot;
  2780. rs.count = 1;
  2781. bulkSRS.moves.push_back(rs);
  2782. }
  2783. auto currSlot = 0;
  2784. auto check = 0;
  2785. for(auto slot : creatureSlots)
  2786. {
  2787. ChangeStackCount csc;
  2788. csc.army = army->id;
  2789. csc.slot = slot;
  2790. csc.count = (currSlot < rem)
  2791. ? quotient + 1
  2792. : quotient;
  2793. csc.absoluteValue = true;
  2794. bulkSRS.changes.push_back(csc);
  2795. currSlot++;
  2796. check += csc.count;
  2797. }
  2798. if(check != totalCreatures)
  2799. {
  2800. complain((boost::format("Failure: totalCreatures=%d but check=%d") % totalCreatures % check).str());
  2801. return false;
  2802. }
  2803. sendAndApply(&bulkSRS);
  2804. return true;
  2805. }
  2806. bool CGameHandler::arrangeStacks(ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player)
  2807. {
  2808. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id1)),
  2809. * s2 = static_cast<const CArmedInstance *>(getObjInstance(id2));
  2810. const CCreatureSet &S1 = *s1, &S2 = *s2;
  2811. StackLocation sl1(s1, p1), sl2(s2, p2);
  2812. if (!sl1.slot.validSlot() || !sl2.slot.validSlot())
  2813. {
  2814. complain(complainInvalidSlot);
  2815. return false;
  2816. }
  2817. if (!isAllowedExchange(id1,id2))
  2818. {
  2819. complain("Cannot exchange stacks between these two objects!\n");
  2820. return false;
  2821. }
  2822. // We can always put stacks into locked garrison, but not take them out of it
  2823. auto notRemovable = [&](const CArmedInstance * army)
  2824. {
  2825. if (id1 != id2) // Stack arrangement inside locked garrison is allowed
  2826. {
  2827. auto g = dynamic_cast<const CGGarrison *>(army);
  2828. if (g && !g->removableUnits)
  2829. {
  2830. complain("Stacks in this garrison are not removable!\n");
  2831. return true;
  2832. }
  2833. }
  2834. return false;
  2835. };
  2836. if (what==1) //swap
  2837. {
  2838. if (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s1->getStackCount(p1))
  2839. || ((s2->tempOwner != player && s2->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)))
  2840. {
  2841. complain("Can't take troops from another player!");
  2842. return false;
  2843. }
  2844. if (sl1.army == sl2.army && sl1.slot == sl2.slot)
  2845. {
  2846. complain("Cannot swap stacks - slots are the same!");
  2847. return false;
  2848. }
  2849. if (!s1->slotEmpty(p1) && !s2->slotEmpty(p2))
  2850. {
  2851. if (notRemovable(sl1.army) || notRemovable(sl2.army))
  2852. return false;
  2853. }
  2854. if (s1->slotEmpty(p1) && notRemovable(sl2.army))
  2855. return false;
  2856. else if (s2->slotEmpty(p2) && notRemovable(sl1.army))
  2857. return false;
  2858. swapStacks(sl1, sl2);
  2859. }
  2860. else if (what==2)//merge
  2861. {
  2862. if ((s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot merge different creatures stacks!"))
  2863. || (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)) && complain("Can't take troops from another player!")))
  2864. return false;
  2865. if (s1->slotEmpty(p1) || s2->slotEmpty(p2))
  2866. {
  2867. complain("Cannot merge empty stack!");
  2868. return false;
  2869. }
  2870. else if (notRemovable(sl1.army))
  2871. return false;
  2872. moveStack(sl1, sl2);
  2873. }
  2874. else if (what==3) //split
  2875. {
  2876. const int countToMove = val - s2->getStackCount(p2);
  2877. const int countLeftOnSrc = s1->getStackCount(p1) - countToMove;
  2878. if ( (s1->tempOwner != player && countLeftOnSrc < s1->getStackCount(p1))
  2879. || (s2->tempOwner != player && val < s2->getStackCount(p2)))
  2880. {
  2881. complain("Can't move troops of another player!");
  2882. return false;
  2883. }
  2884. //general conditions checking
  2885. if ((!vstd::contains(S1.stacks,p1) && complain(complainNoCreatures))
  2886. || (val<1 && complain(complainNoCreatures)) )
  2887. {
  2888. return false;
  2889. }
  2890. if (vstd::contains(S2.stacks,p2)) //dest. slot not free - it must be "rebalancing"...
  2891. {
  2892. int total = s1->getStackCount(p1) + s2->getStackCount(p2);
  2893. if ((total < val && complain("Cannot split that stack, not enough creatures!"))
  2894. || (s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot rebalance different creatures stacks!"))
  2895. )
  2896. {
  2897. return false;
  2898. }
  2899. if (notRemovable(sl1.army))
  2900. {
  2901. if (s1->getStackCount(p1) > countLeftOnSrc)
  2902. return false;
  2903. }
  2904. else if (notRemovable(sl2.army))
  2905. {
  2906. if (s2->getStackCount(p1) < countLeftOnSrc)
  2907. return false;
  2908. }
  2909. moveStack(sl1, sl2, countToMove);
  2910. //S2.slots[p2]->count = val;
  2911. //S1.slots[p1]->count = total - val;
  2912. }
  2913. else //split one stack to the two
  2914. {
  2915. if (s1->getStackCount(p1) < val)//not enough creatures
  2916. {
  2917. complain(complainNotEnoughCreatures);
  2918. return false;
  2919. }
  2920. if (notRemovable(sl1.army))
  2921. return false;
  2922. moveStack(sl1, sl2, val);
  2923. }
  2924. }
  2925. return true;
  2926. }
  2927. bool CGameHandler::hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const
  2928. {
  2929. return connections.at(player).count(c);
  2930. }
  2931. PlayerColor CGameHandler::getPlayerAt(std::shared_ptr<CConnection> c) const
  2932. {
  2933. std::set<PlayerColor> all;
  2934. for (auto i=connections.cbegin(); i!=connections.cend(); i++)
  2935. if(vstd::contains(i->second, c))
  2936. all.insert(i->first);
  2937. switch(all.size())
  2938. {
  2939. case 0:
  2940. return PlayerColor::NEUTRAL;
  2941. case 1:
  2942. return *all.begin();
  2943. default:
  2944. {
  2945. //if we have more than one player at this connection, try to pick active one
  2946. if (vstd::contains(all, gs->currentPlayer))
  2947. return gs->currentPlayer;
  2948. else
  2949. return PlayerColor::CANNOT_DETERMINE; //cannot say which player is it
  2950. }
  2951. }
  2952. }
  2953. bool CGameHandler::disbandCreature(ObjectInstanceID id, SlotID pos)
  2954. {
  2955. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id));
  2956. if (!vstd::contains(s1->stacks,pos))
  2957. {
  2958. complain("Illegal call to disbandCreature - no such stack in army!");
  2959. return false;
  2960. }
  2961. eraseStack(StackLocation(s1, pos));
  2962. return true;
  2963. }
  2964. bool CGameHandler::buildStructure(ObjectInstanceID tid, BuildingID requestedID, bool force)
  2965. {
  2966. const CGTownInstance * t = getTown(tid);
  2967. if(!t)
  2968. COMPLAIN_RETF("No such town (ID=%s)!", tid);
  2969. if(!t->town->buildings.count(requestedID))
  2970. COMPLAIN_RETF("Town of faction %s does not have info about building ID=%s!", t->town->faction->getNameTranslated() % requestedID);
  2971. if(t->hasBuilt(requestedID))
  2972. COMPLAIN_RETF("Building %s is already built in %s", t->town->buildings.at(requestedID)->getNameTranslated() % t->getNameTranslated());
  2973. const CBuilding * requestedBuilding = t->town->buildings.at(requestedID);
  2974. //Vector with future list of built building and buildings in auto-mode that are not yet built.
  2975. std::vector<const CBuilding*> remainingAutoBuildings;
  2976. std::set<BuildingID> buildingsThatWillBe;
  2977. //Check validity of request
  2978. if(!force)
  2979. {
  2980. switch(requestedBuilding->mode)
  2981. {
  2982. case CBuilding::BUILD_NORMAL :
  2983. if (canBuildStructure(t, requestedID) != EBuildingState::ALLOWED)
  2984. COMPLAIN_RET("Cannot build that building!");
  2985. break;
  2986. case CBuilding::BUILD_AUTO :
  2987. case CBuilding::BUILD_SPECIAL:
  2988. COMPLAIN_RET("This building can not be constructed normally!");
  2989. case CBuilding::BUILD_GRAIL :
  2990. if(requestedBuilding->mode == CBuilding::BUILD_GRAIL) //needs grail
  2991. {
  2992. if(!t->visitingHero || !t->visitingHero->hasArt(ArtifactID::GRAIL))
  2993. COMPLAIN_RET("Cannot build this without grail!")
  2994. else
  2995. removeArtifact(ArtifactLocation(t->visitingHero, t->visitingHero->getArtPos(ArtifactID::GRAIL, false)));
  2996. }
  2997. break;
  2998. }
  2999. }
  3000. //Performs stuff that has to be done before new building is built
  3001. auto processBeforeBuiltStructure = [t, this](const BuildingID buildingID)
  3002. {
  3003. if(buildingID >= BuildingID::DWELL_FIRST) //dwelling
  3004. {
  3005. int level = (buildingID - BuildingID::DWELL_FIRST) % GameConstants::CREATURES_PER_TOWN;
  3006. int upgradeNumber = (buildingID - BuildingID::DWELL_FIRST) / GameConstants::CREATURES_PER_TOWN;
  3007. if(upgradeNumber >= t->town->creatures.at(level).size())
  3008. {
  3009. complain(boost::str(boost::format("Error ecountered when building dwelling (bid=%s):"
  3010. "no creature found (upgrade number %d, level %d!")
  3011. % buildingID % upgradeNumber % level));
  3012. return;
  3013. }
  3014. CCreature * crea = VLC->creh->objects.at(t->town->creatures.at(level).at(upgradeNumber));
  3015. SetAvailableCreatures ssi;
  3016. ssi.tid = t->id;
  3017. ssi.creatures = t->creatures;
  3018. if (ssi.creatures[level].second.empty()) // first creature in a dwelling
  3019. ssi.creatures[level].first = crea->getGrowth();
  3020. ssi.creatures[level].second.push_back(crea->getId());
  3021. sendAndApply(&ssi);
  3022. }
  3023. if(t->town->buildings.at(buildingID)->subId == BuildingSubID::PORTAL_OF_SUMMONING)
  3024. {
  3025. setPortalDwelling(t);
  3026. }
  3027. };
  3028. //Performs stuff that has to be done after new building is built
  3029. auto processAfterBuiltStructure = [t, this](const BuildingID buildingID)
  3030. {
  3031. auto isMageGuild = (buildingID <= BuildingID::MAGES_GUILD_5 && buildingID >= BuildingID::MAGES_GUILD_1);
  3032. auto isLibrary = isMageGuild ? false
  3033. : t->town->buildings.at(buildingID)->subId == BuildingSubID::EBuildingSubID::LIBRARY;
  3034. if(isMageGuild || isLibrary || (t->subID == ETownType::CONFLUX && buildingID == BuildingID::GRAIL))
  3035. {
  3036. if(t->visitingHero)
  3037. giveSpells(t,t->visitingHero);
  3038. if(t->garrisonHero)
  3039. giveSpells(t,t->garrisonHero);
  3040. }
  3041. };
  3042. //Checks if all requirements will be met with expected building list "buildingsThatWillBe"
  3043. auto areRequirementsFullfilled = [&](const BuildingID & buildID)
  3044. {
  3045. return buildingsThatWillBe.count(buildID);
  3046. };
  3047. //Init the vectors
  3048. for(auto & build : t->town->buildings)
  3049. {
  3050. if(t->hasBuilt(build.first))
  3051. {
  3052. buildingsThatWillBe.insert(build.first);
  3053. }
  3054. else
  3055. {
  3056. if(build.second->mode == CBuilding::BUILD_AUTO) //not built auto building
  3057. remainingAutoBuildings.push_back(build.second);
  3058. }
  3059. }
  3060. //Prepare structure (list of building ids will be filled later)
  3061. NewStructures ns;
  3062. ns.tid = tid;
  3063. ns.builded = force ? t->builded : (t->builded+1);
  3064. std::queue<const CBuilding*> buildingsToAdd;
  3065. buildingsToAdd.push(requestedBuilding);
  3066. while(!buildingsToAdd.empty())
  3067. {
  3068. auto b = buildingsToAdd.front();
  3069. buildingsToAdd.pop();
  3070. ns.bid.insert(b->bid);
  3071. buildingsThatWillBe.insert(b->bid);
  3072. remainingAutoBuildings -= b;
  3073. for(auto autoBuilding : remainingAutoBuildings)
  3074. {
  3075. auto actualRequirements = t->genBuildingRequirements(autoBuilding->bid);
  3076. if(actualRequirements.test(areRequirementsFullfilled))
  3077. buildingsToAdd.push(autoBuilding);
  3078. }
  3079. }
  3080. // FIXME: it's done before NewStructures applied because otherwise town window wont be properly updated on client. That should be actually fixed on client and not on server.
  3081. for(auto builtID : ns.bid)
  3082. processBeforeBuiltStructure(builtID);
  3083. //Take cost
  3084. if(!force)
  3085. giveResources(t->tempOwner, -requestedBuilding->resources);
  3086. //We know what has been built, apply changes. Do this as final step to properly update town window
  3087. sendAndApply(&ns);
  3088. //Other post-built events. To some logic like giving spells to work gamestate changes for new building must be already in place!
  3089. for(auto builtID : ns.bid)
  3090. processAfterBuiltStructure(builtID);
  3091. // now when everything is built - reveal tiles for lookout tower
  3092. FoWChange fw;
  3093. fw.player = t->tempOwner;
  3094. fw.mode = 1;
  3095. getTilesInRange(fw.tiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, 1);
  3096. sendAndApply(&fw);
  3097. if(t->visitingHero)
  3098. visitCastleObjects(t, t->visitingHero);
  3099. if(t->garrisonHero)
  3100. visitCastleObjects(t, t->garrisonHero);
  3101. checkVictoryLossConditionsForPlayer(t->tempOwner);
  3102. return true;
  3103. }
  3104. bool CGameHandler::razeStructure (ObjectInstanceID tid, BuildingID bid)
  3105. {
  3106. ///incomplete, simply erases target building
  3107. const CGTownInstance * t = getTown(tid);
  3108. if (!vstd::contains(t->builtBuildings, bid))
  3109. return false;
  3110. RazeStructures rs;
  3111. rs.tid = tid;
  3112. rs.bid.insert(bid);
  3113. rs.destroyed = t->destroyed + 1;
  3114. sendAndApply(&rs);
  3115. //TODO: Remove dwellers
  3116. // if (t->subID == 4 && bid == 17) //Veil of Darkness
  3117. // {
  3118. // RemoveBonus rb(RemoveBonus::TOWN);
  3119. // rb.whoID = t->id;
  3120. // rb.source = BonusSource::TOWN_STRUCTURE;
  3121. // rb.id = 17;
  3122. // sendAndApply(&rb);
  3123. // }
  3124. return true;
  3125. }
  3126. bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dstid, CreatureID crid, ui32 cram, si32 fromLvl)
  3127. {
  3128. const CGDwelling * dw = static_cast<const CGDwelling *>(getObj(objid));
  3129. const CArmedInstance *dst = nullptr;
  3130. const CCreature *c = VLC->creh->objects.at(crid);
  3131. const bool warMachine = c->warMachine != ArtifactID::NONE;
  3132. //TODO: test for owning
  3133. //TODO: check if dst can recruit objects (e.g. hero is actually visiting object, town and source are same, etc)
  3134. dst = dynamic_cast<const CArmedInstance*>(getObj(dstid));
  3135. assert(dw && dst);
  3136. //verify
  3137. bool found = false;
  3138. int level = 0;
  3139. for (; level < dw->creatures.size(); level++) //iterate through all levels
  3140. {
  3141. if ((fromLvl != -1) && (level !=fromLvl))
  3142. continue;
  3143. const auto &cur = dw->creatures.at(level); //current level info <amount, list of cr. ids>
  3144. int i = 0;
  3145. for (; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  3146. if (cur.second.at(i) == crid)
  3147. break;
  3148. if (i < cur.second.size())
  3149. {
  3150. found = true;
  3151. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  3152. break;
  3153. }
  3154. }
  3155. SlotID slot = dst->getSlotFor(crid);
  3156. if ((!found && complain("Cannot recruit: no such creatures!"))
  3157. || ((si32)cram > VLC->creh->objects.at(crid)->maxAmount(getPlayerState(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!"))
  3158. || (cram<=0 && complain("Cannot recruit: cram <= 0!"))
  3159. || (!slot.validSlot() && !warMachine && complain("Cannot recruit: no available slot!")))
  3160. {
  3161. return false;
  3162. }
  3163. //recruit
  3164. giveResources(dst->tempOwner, -(c->getFullRecruitCost() * cram));
  3165. SetAvailableCreatures sac;
  3166. sac.tid = objid;
  3167. sac.creatures = dw->creatures;
  3168. sac.creatures[level].first -= cram;
  3169. sendAndApply(&sac);
  3170. if (warMachine)
  3171. {
  3172. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(dst);
  3173. COMPLAIN_RET_FALSE_IF(!h, "Only hero can buy war machines");
  3174. ArtifactID artId = c->warMachine;
  3175. COMPLAIN_RET_FALSE_IF(artId == ArtifactID::CATAPULT, "Catapult cannot be recruited!");
  3176. const CArtifact * art = artId.toArtifact();
  3177. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid war machine artifact");
  3178. return giveHeroNewArtifact(h, art);
  3179. }
  3180. else
  3181. {
  3182. addToSlot(StackLocation(dst, slot), c, cram);
  3183. }
  3184. return true;
  3185. }
  3186. bool CGameHandler::upgradeCreature(ObjectInstanceID objid, SlotID pos, CreatureID upgID)
  3187. {
  3188. const CArmedInstance * obj = static_cast<const CArmedInstance *>(getObjInstance(objid));
  3189. if (!obj->hasStackAtSlot(pos))
  3190. {
  3191. COMPLAIN_RET("Cannot upgrade, no stack at slot " + boost::to_string(pos));
  3192. }
  3193. UpgradeInfo ui;
  3194. fillUpgradeInfo(obj, pos, ui);
  3195. PlayerColor player = obj->tempOwner;
  3196. const PlayerState *p = getPlayerState(player);
  3197. int crQuantity = obj->stacks.at(pos)->count;
  3198. int newIDpos= vstd::find_pos(ui.newID, upgID);//get position of new id in UpgradeInfo
  3199. //check if upgrade is possible
  3200. if ((ui.oldID<0 || newIDpos == -1) && complain("That upgrade is not possible!"))
  3201. {
  3202. return false;
  3203. }
  3204. TResources totalCost = ui.cost.at(newIDpos) * crQuantity;
  3205. //check if player has enough resources
  3206. if (!p->resources.canAfford(totalCost))
  3207. COMPLAIN_RET("Cannot upgrade, not enough resources!");
  3208. //take resources
  3209. giveResources(player, -totalCost);
  3210. //upgrade creature
  3211. changeStackType(StackLocation(obj, pos), VLC->creh->objects.at(upgID));
  3212. return true;
  3213. }
  3214. bool CGameHandler::changeStackType(const StackLocation &sl, const CCreature *c)
  3215. {
  3216. if (!sl.army->hasStackAtSlot(sl.slot))
  3217. COMPLAIN_RET("Cannot find a stack to change type");
  3218. SetStackType sst;
  3219. sst.army = sl.army->id;
  3220. sst.slot = sl.slot;
  3221. sst.type = c->getId();
  3222. sendAndApply(&sst);
  3223. return true;
  3224. }
  3225. void CGameHandler::moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging)
  3226. {
  3227. assert(src->canBeMergedWith(*dst, allowMerging));
  3228. while(src->stacksCount())//while there are unmoved creatures
  3229. {
  3230. auto i = src->Slots().begin(); //iterator to stack to move
  3231. StackLocation sl(src, i->first); //location of stack to move
  3232. SlotID pos = dst->getSlotFor(i->second->type);
  3233. if (!pos.validSlot())
  3234. {
  3235. //try to merge two other stacks to make place
  3236. std::pair<SlotID, SlotID> toMerge;
  3237. if (dst->mergableStacks(toMerge, i->first) && allowMerging)
  3238. {
  3239. moveStack(StackLocation(dst, toMerge.first), StackLocation(dst, toMerge.second)); //merge toMerge.first into toMerge.second
  3240. assert(!dst->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  3241. moveStack(sl, StackLocation(dst, toMerge.first)); //move stack to freed slot
  3242. }
  3243. else
  3244. {
  3245. complain("Unexpected failure during an attempt to move army from " + src->nodeName() + " to " + dst->nodeName() + "!");
  3246. return;
  3247. }
  3248. }
  3249. else
  3250. {
  3251. moveStack(sl, StackLocation(dst, pos));
  3252. }
  3253. }
  3254. }
  3255. bool CGameHandler::swapGarrisonOnSiege(ObjectInstanceID tid)
  3256. {
  3257. const CGTownInstance * town = getTown(tid);
  3258. if(!town->garrisonHero == !town->visitingHero)
  3259. return false;
  3260. SetHeroesInTown intown;
  3261. intown.tid = tid;
  3262. if(town->garrisonHero) //garrison -> vising
  3263. {
  3264. intown.garrison = ObjectInstanceID();
  3265. intown.visiting = town->garrisonHero->id;
  3266. }
  3267. else //visiting -> garrison
  3268. {
  3269. if(town->armedGarrison())
  3270. town->mergeGarrisonOnSiege();
  3271. intown.visiting = ObjectInstanceID();
  3272. intown.garrison = town->visitingHero->id;
  3273. }
  3274. sendAndApply(&intown);
  3275. return true;
  3276. }
  3277. bool CGameHandler::garrisonSwap(ObjectInstanceID tid)
  3278. {
  3279. const CGTownInstance * town = getTown(tid);
  3280. if (!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  3281. {
  3282. if (!town->visitingHero->canBeMergedWith(*town))
  3283. {
  3284. complain("Cannot make garrison swap, not enough free slots!");
  3285. return false;
  3286. }
  3287. moveArmy(town, town->visitingHero, true);
  3288. SetHeroesInTown intown;
  3289. intown.tid = tid;
  3290. intown.visiting = ObjectInstanceID();
  3291. intown.garrison = town->visitingHero->id;
  3292. sendAndApply(&intown);
  3293. return true;
  3294. }
  3295. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  3296. {
  3297. //check if moving hero out of town will break 8 wandering heroes limit
  3298. if (getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  3299. {
  3300. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  3301. return false;
  3302. }
  3303. SetHeroesInTown intown;
  3304. intown.tid = tid;
  3305. intown.garrison = ObjectInstanceID();
  3306. intown.visiting = town->garrisonHero->id;
  3307. sendAndApply(&intown);
  3308. return true;
  3309. }
  3310. else if (!!town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  3311. {
  3312. SetHeroesInTown intown;
  3313. intown.tid = tid;
  3314. intown.garrison = town->visitingHero->id;
  3315. intown.visiting = town->garrisonHero->id;
  3316. sendAndApply(&intown);
  3317. return true;
  3318. }
  3319. else
  3320. {
  3321. complain("Cannot swap garrison hero!");
  3322. return false;
  3323. }
  3324. }
  3325. // With the amount of changes done to the function, it's more like transferArtifacts.
  3326. // 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.
  3327. bool CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2)
  3328. {
  3329. ArtifactLocation src = al1, dst = al2;
  3330. const PlayerColor srcPlayer = src.owningPlayer(), dstPlayer = dst.owningPlayer();
  3331. const CArmedInstance *srcObj = src.relatedObj(), *dstObj = dst.relatedObj();
  3332. // Make sure exchange is even possible between the two heroes.
  3333. if(!isAllowedExchange(srcObj->id, dstObj->id))
  3334. COMPLAIN_RET("That heroes cannot make any exchange!");
  3335. const CArtifactInstance *srcArtifact = src.getArt();
  3336. const CArtifactInstance *destArtifact = dst.getArt();
  3337. const bool isDstSlotBackpack = ArtifactUtils::isSlotBackpack(dst.slot);
  3338. if(srcArtifact == nullptr)
  3339. COMPLAIN_RET("No artifact to move!");
  3340. if(destArtifact && srcPlayer != dstPlayer && !isDstSlotBackpack)
  3341. COMPLAIN_RET("Can't touch artifact on hero of another player!");
  3342. // Check if src/dest slots are appropriate for the artifacts exchanged.
  3343. // Moving to the backpack is always allowed.
  3344. if((!srcArtifact || !isDstSlotBackpack)
  3345. && srcArtifact && !srcArtifact->canBePutAt(dst, true))
  3346. COMPLAIN_RET("Cannot move artifact!");
  3347. auto srcSlot = src.getSlot();
  3348. auto dstSlot = dst.getSlot();
  3349. if((srcSlot && srcSlot->locked) || (dstSlot && dstSlot->locked))
  3350. COMPLAIN_RET("Cannot move artifact locks.");
  3351. if(isDstSlotBackpack && srcArtifact->artType->isBig())
  3352. COMPLAIN_RET("Cannot put big artifacts in backpack!");
  3353. if(src.slot == ArtifactPosition::MACH4 || dst.slot == ArtifactPosition::MACH4)
  3354. COMPLAIN_RET("Cannot move catapult!");
  3355. if(isDstSlotBackpack)
  3356. {
  3357. if(!ArtifactUtils::isBackpackFreeSlots(dst.getHolderArtSet()))
  3358. COMPLAIN_RET("Backpack is full!");
  3359. vstd::amin(dst.slot, GameConstants::BACKPACK_START + dst.getHolderArtSet()->artifactsInBackpack.size());
  3360. }
  3361. if(!(src.slot == ArtifactPosition::TRANSITION_POS && dst.slot == ArtifactPosition::TRANSITION_POS))
  3362. {
  3363. if(src.slot == dst.slot && src.artHolder == dst.artHolder)
  3364. COMPLAIN_RET("Won't move artifact: Dest same as source!");
  3365. // Check if dst slot is occupied
  3366. if(!isDstSlotBackpack && destArtifact)
  3367. {
  3368. // Previous artifact must be removed first
  3369. moveArtifact(dst, ArtifactLocation(dst.artHolder, ArtifactPosition::TRANSITION_POS));
  3370. }
  3371. try
  3372. {
  3373. auto hero = std::get<ConstTransitivePtr<CGHeroInstance>>(dst.artHolder);
  3374. if(ArtifactUtils::checkSpellbookIsNeeded(hero, srcArtifact->artType->getId(), dst.slot))
  3375. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3376. }
  3377. catch(const std::bad_variant_access &)
  3378. {
  3379. // object other than hero received an art - ignore
  3380. }
  3381. MoveArtifact ma(&src, &dst);
  3382. if(dst.slot == ArtifactPosition::TRANSITION_POS)
  3383. ma.askAssemble = false;
  3384. sendAndApply(&ma);
  3385. }
  3386. return true;
  3387. }
  3388. bool CGameHandler::bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap)
  3389. {
  3390. // Make sure exchange is even possible between the two heroes.
  3391. if(!isAllowedExchange(srcHero, dstHero))
  3392. COMPLAIN_RET("That heroes cannot make any exchange!");
  3393. auto psrcHero = getHero(srcHero);
  3394. auto pdstHero = getHero(dstHero);
  3395. if((!psrcHero) || (!pdstHero))
  3396. COMPLAIN_RET("bulkMoveArtifacts: wrong hero's ID");
  3397. BulkMoveArtifacts ma(static_cast<ConstTransitivePtr<CGHeroInstance>>(psrcHero),
  3398. static_cast<ConstTransitivePtr<CGHeroInstance>>(pdstHero), swap);
  3399. auto & slotsSrcDst = ma.artsPack0;
  3400. auto & slotsDstSrc = ma.artsPack1;
  3401. // Temporary fitting set for artifacts. Used to select available slots before sending data.
  3402. CArtifactFittingSet artFittingSet(pdstHero->bearerType());
  3403. auto moveArtifact = [this, &artFittingSet](const CArtifactInstance * artifact,
  3404. ArtifactPosition srcSlot, const CGHeroInstance * dstHero,
  3405. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  3406. {
  3407. assert(artifact);
  3408. auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, artifact->getTypeId());
  3409. if(dstSlot != ArtifactPosition::PRE_FIRST)
  3410. {
  3411. artFittingSet.putArtifact(dstSlot, static_cast<ConstTransitivePtr<CArtifactInstance>>(artifact));
  3412. slots.push_back(BulkMoveArtifacts::LinkedSlots(srcSlot, dstSlot));
  3413. if(ArtifactUtils::checkSpellbookIsNeeded(dstHero, artifact->getTypeId(), dstSlot))
  3414. giveHeroNewArtifact(dstHero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3415. }
  3416. };
  3417. if(swap)
  3418. {
  3419. auto moveArtsWorn = [moveArtifact](const CGHeroInstance * srcHero, const CGHeroInstance * dstHero,
  3420. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  3421. {
  3422. for(auto & artifact : srcHero->artifactsWorn)
  3423. {
  3424. if(ArtifactUtils::isArtRemovable(artifact))
  3425. moveArtifact(artifact.second.getArt(), artifact.first, dstHero, slots);
  3426. }
  3427. };
  3428. auto moveArtsInBackpack = [](const CArtifactSet * artSet,
  3429. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  3430. {
  3431. for(auto & slotInfo : artSet->artifactsInBackpack)
  3432. {
  3433. auto slot = artSet->getArtPos(slotInfo.artifact);
  3434. slots.push_back(BulkMoveArtifacts::LinkedSlots(slot, slot));
  3435. }
  3436. };
  3437. // Move over artifacts that are worn srcHero -> dstHero
  3438. moveArtsWorn(psrcHero, pdstHero, slotsSrcDst);
  3439. artFittingSet.artifactsWorn.clear();
  3440. // Move over artifacts that are worn dstHero -> srcHero
  3441. moveArtsWorn(pdstHero, psrcHero, slotsDstSrc);
  3442. // Move over artifacts that are in backpack srcHero -> dstHero
  3443. moveArtsInBackpack(psrcHero, slotsSrcDst);
  3444. // Move over artifacts that are in backpack dstHero -> srcHero
  3445. moveArtsInBackpack(pdstHero, slotsDstSrc);
  3446. }
  3447. else
  3448. {
  3449. artFittingSet.artifactsInBackpack = pdstHero->artifactsInBackpack;
  3450. artFittingSet.artifactsWorn = pdstHero->artifactsWorn;
  3451. // Move over artifacts that are worn
  3452. for(auto & artInfo : psrcHero->artifactsWorn)
  3453. {
  3454. if(ArtifactUtils::isArtRemovable(artInfo))
  3455. {
  3456. moveArtifact(psrcHero->getArt(artInfo.first), artInfo.first, pdstHero, slotsSrcDst);
  3457. }
  3458. }
  3459. // Move over artifacts that are in backpack
  3460. for(auto & slotInfo : psrcHero->artifactsInBackpack)
  3461. {
  3462. moveArtifact(psrcHero->getArt(psrcHero->getArtPos(slotInfo.artifact)),
  3463. psrcHero->getArtPos(slotInfo.artifact), pdstHero, slotsSrcDst);
  3464. }
  3465. }
  3466. sendAndApply(&ma);
  3467. return true;
  3468. }
  3469. /**
  3470. * Assembles or disassembles a combination artifact.
  3471. * @param heroID ID of hero holding the artifact(s).
  3472. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  3473. * @param assemble True for assembly operation, false for disassembly.
  3474. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  3475. * artifact to assemble to. Otherwise it's not used.
  3476. */
  3477. bool CGameHandler::assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  3478. {
  3479. const CGHeroInstance * hero = getHero(heroID);
  3480. const CArtifactInstance * destArtifact = hero->getArt(artifactSlot);
  3481. if(!destArtifact)
  3482. COMPLAIN_RET("assembleArtifacts: there is no such artifact instance!");
  3483. if(assemble)
  3484. {
  3485. CArtifact * combinedArt = VLC->arth->objects[assembleTo];
  3486. if(!combinedArt->isCombined())
  3487. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to assemble is not a combined artifacts!");
  3488. if (!vstd::contains(ArtifactUtils::assemblyPossibilities(hero, destArtifact->getTypeId(),
  3489. ArtifactUtils::isSlotEquipment(artifactSlot)), combinedArt))
  3490. {
  3491. COMPLAIN_RET("assembleArtifacts: It's impossible to assemble requested artifact!");
  3492. }
  3493. if(ArtifactUtils::checkSpellbookIsNeeded(hero, assembleTo, artifactSlot))
  3494. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3495. AssembledArtifact aa;
  3496. aa.al = ArtifactLocation(hero, artifactSlot);
  3497. aa.builtArt = combinedArt;
  3498. sendAndApply(&aa);
  3499. }
  3500. else
  3501. {
  3502. if(!destArtifact->isCombined())
  3503. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is not a combined artifact!");
  3504. if(ArtifactUtils::isSlotBackpack(artifactSlot)
  3505. && !ArtifactUtils::isBackpackFreeSlots(hero, destArtifact->artType->getConstituents().size() - 1))
  3506. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble but backpack is full!");
  3507. DisassembledArtifact da;
  3508. da.al = ArtifactLocation(hero, artifactSlot);
  3509. sendAndApply(&da);
  3510. }
  3511. return true;
  3512. }
  3513. bool CGameHandler::eraseArtifactByClient(const ArtifactLocation & al)
  3514. {
  3515. const auto * hero = getHero(al.relatedObj()->id);
  3516. if(hero == nullptr)
  3517. COMPLAIN_RET("eraseArtifactByClient: wrong hero's ID");
  3518. const auto * art = al.getArt();
  3519. if(art == nullptr)
  3520. COMPLAIN_RET("Cannot remove artifact!");
  3521. if(al.getArt()->artType->canBePutAt(hero) || al.slot != ArtifactPosition::TRANSITION_POS)
  3522. COMPLAIN_RET("Illegal artifact removal request");
  3523. removeArtifact(al);
  3524. return true;
  3525. }
  3526. bool CGameHandler::buyArtifact(ObjectInstanceID hid, ArtifactID aid)
  3527. {
  3528. const CGHeroInstance * hero = getHero(hid);
  3529. COMPLAIN_RET_FALSE_IF(nullptr == hero, "Invalid hero index");
  3530. const CGTownInstance * town = hero->visitedTown;
  3531. COMPLAIN_RET_FALSE_IF(nullptr == town, "Hero not in town");
  3532. if (aid==ArtifactID::SPELLBOOK)
  3533. {
  3534. if ((!town->hasBuilt(BuildingID::MAGES_GUILD_1) && complain("Cannot buy a spellbook, no mage guild in the town!"))
  3535. || (getResource(hero->getOwner(), EGameResID::GOLD) < GameConstants::SPELLBOOK_GOLD_COST && complain("Cannot buy a spellbook, not enough gold!"))
  3536. || (hero->getArt(ArtifactPosition::SPELLBOOK) && complain("Cannot buy a spellbook, hero already has a one!"))
  3537. )
  3538. return false;
  3539. giveResource(hero->getOwner(),EGameResID::GOLD,-GameConstants::SPELLBOOK_GOLD_COST);
  3540. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3541. assert(hero->getArt(ArtifactPosition::SPELLBOOK));
  3542. giveSpells(town,hero);
  3543. return true;
  3544. }
  3545. else
  3546. {
  3547. const CArtifact * art = aid.toArtifact();
  3548. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid artifact index to buy");
  3549. COMPLAIN_RET_FALSE_IF(art->getWarMachine() == CreatureID::NONE, "War machine artifact required");
  3550. COMPLAIN_RET_FALSE_IF(hero->hasArt(aid),"Hero already has this machine!");
  3551. const int price = art->getPrice();
  3552. COMPLAIN_RET_FALSE_IF(getPlayerState(hero->getOwner())->resources[EGameResID::GOLD] < price, "Not enough gold!");
  3553. if ((town->hasBuilt(BuildingID::BLACKSMITH) && town->town->warMachine == aid)
  3554. || (town->hasBuilt(BuildingSubID::BALLISTA_YARD) && aid == ArtifactID::BALLISTA))
  3555. {
  3556. giveResource(hero->getOwner(),EGameResID::GOLD,-price);
  3557. return giveHeroNewArtifact(hero, art);
  3558. }
  3559. else
  3560. COMPLAIN_RET("This machine is unavailable here!");
  3561. }
  3562. }
  3563. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid)
  3564. {
  3565. if(!h)
  3566. COMPLAIN_RET("Only hero can buy artifacts!");
  3567. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_ARTIFACT), aid))
  3568. COMPLAIN_RET("That artifact is unavailable!");
  3569. int b1, b2;
  3570. m->getOffer(rid, aid, b1, b2, EMarketMode::RESOURCE_ARTIFACT);
  3571. if (getResource(h->tempOwner, rid) < b1)
  3572. COMPLAIN_RET("You can't afford to buy this artifact!");
  3573. giveResource(h->tempOwner, rid, -b1);
  3574. SetAvailableArtifacts saa;
  3575. if(dynamic_cast<const CGTownInstance *>(m))
  3576. {
  3577. saa.id = -1;
  3578. saa.arts = CGTownInstance::merchantArtifacts;
  3579. }
  3580. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m)) //black market
  3581. {
  3582. saa.id = bm->id.getNum();
  3583. saa.arts = bm->artifacts;
  3584. }
  3585. else
  3586. COMPLAIN_RET("Wrong marktet...");
  3587. bool found = false;
  3588. for (const CArtifact *&art : saa.arts)
  3589. {
  3590. if (art && art->getId() == aid)
  3591. {
  3592. art = nullptr;
  3593. found = true;
  3594. break;
  3595. }
  3596. }
  3597. if (!found)
  3598. COMPLAIN_RET("Cannot find selected artifact on the list");
  3599. sendAndApply(&saa);
  3600. giveHeroNewArtifact(h, VLC->arth->objects[aid], ArtifactPosition::FIRST_AVAILABLE);
  3601. return true;
  3602. }
  3603. bool CGameHandler::sellArtifact(const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid)
  3604. {
  3605. COMPLAIN_RET_FALSE_IF((!h), "Only hero can sell artifacts!");
  3606. const CArtifactInstance *art = h->getArtByInstanceId(aid);
  3607. COMPLAIN_RET_FALSE_IF((!art), "There is no artifact to sell!");
  3608. COMPLAIN_RET_FALSE_IF((!art->artType->isTradable()), "Cannot sell a war machine or spellbook!");
  3609. int resVal = 0, dump = 1;
  3610. m->getOffer(art->artType->getId(), rid, dump, resVal, EMarketMode::ARTIFACT_RESOURCE);
  3611. removeArtifact(ArtifactLocation(h, h->getArtPos(art)));
  3612. giveResource(h->tempOwner, rid, resVal);
  3613. return true;
  3614. }
  3615. bool CGameHandler::buySecSkill(const IMarket *m, const CGHeroInstance *h, SecondarySkill skill)
  3616. {
  3617. if (!h)
  3618. COMPLAIN_RET("You need hero to buy a skill!");
  3619. if (h->getSecSkillLevel(SecondarySkill(skill)))
  3620. COMPLAIN_RET("Hero already know this skill");
  3621. if (!h->canLearnSkill())
  3622. COMPLAIN_RET("Hero can't learn any more skills");
  3623. if (!h->canLearnSkill(skill))
  3624. COMPLAIN_RET("The hero can't learn this skill!");
  3625. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_SKILL), skill))
  3626. COMPLAIN_RET("That skill is unavailable!");
  3627. if (getResource(h->tempOwner, EGameResID::GOLD) < GameConstants::SKILL_GOLD_COST)//TODO: remove hardcoded resource\summ?
  3628. COMPLAIN_RET("You can't afford to buy this skill");
  3629. giveResource(h->tempOwner, EGameResID::GOLD, -GameConstants::SKILL_GOLD_COST);
  3630. changeSecSkill(h, skill, 1, true);
  3631. return true;
  3632. }
  3633. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2)
  3634. {
  3635. TResourceCap r1 = getPlayerState(player)->resources[id1];
  3636. vstd::amin(val, r1); //can't trade more resources than have
  3637. int b1, b2; //base quantities for trade
  3638. market->getOffer(id1, id2, b1, b2, EMarketMode::RESOURCE_RESOURCE);
  3639. int units = val / b1; //how many base quantities we trade
  3640. if (val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  3641. {
  3642. COMPLAIN_RET("Invalid deal, not all offered units of resource were used.");
  3643. }
  3644. giveResource(player, GameResID(id1), - b1 * units);
  3645. giveResource(player, GameResID(id2), b2 * units);
  3646. return true;
  3647. }
  3648. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID)
  3649. {
  3650. if(!hero)
  3651. COMPLAIN_RET("Only hero can sell creatures!");
  3652. if (!vstd::contains(hero->Slots(), slot))
  3653. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  3654. const CStackInstance &s = hero->getStack(slot);
  3655. if (s.count < (TQuantity)count //can't sell more creatures than have
  3656. || (hero->stacksCount() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack
  3657. {
  3658. COMPLAIN_RET("Not enough creatures in army!");
  3659. }
  3660. int b1, b2; //base quantities for trade
  3661. market->getOffer(s.type->getId(), resourceID, b1, b2, EMarketMode::CREATURE_RESOURCE);
  3662. int units = count / b1; //how many base quantities we trade
  3663. if (count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  3664. {
  3665. //TODO: complain?
  3666. assert(0);
  3667. }
  3668. changeStackCount(StackLocation(hero, slot), -(TQuantity)count);
  3669. giveResource(hero->tempOwner, resourceID, b2 * units);
  3670. return true;
  3671. }
  3672. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot)
  3673. {
  3674. const CArmedInstance *army = nullptr;
  3675. if (hero)
  3676. army = hero;
  3677. else
  3678. army = dynamic_cast<const CGTownInstance *>(market);
  3679. if (!army)
  3680. COMPLAIN_RET("Incorrect call to transform in undead!");
  3681. if (!army->hasStackAtSlot(slot))
  3682. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  3683. const CStackInstance &s = army->getStack(slot);
  3684. //resulting creature - bone dragons or skeletons
  3685. CreatureID resCreature = CreatureID::SKELETON;
  3686. if ((s.hasBonusOfType(BonusType::DRAGON_NATURE)
  3687. && !(s.hasBonusOfType(BonusType::UNDEAD)))
  3688. || (s.getCreatureID() == CreatureID::HYDRA)
  3689. || (s.getCreatureID() == CreatureID::CHAOS_HYDRA))
  3690. resCreature = CreatureID::BONE_DRAGON;
  3691. changeStackType(StackLocation(army, slot), resCreature.toCreature());
  3692. return true;
  3693. }
  3694. bool CGameHandler::sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2)
  3695. {
  3696. const PlayerState *p2 = getPlayerState(r2, false);
  3697. if (!p2 || p2->status != EPlayerStatus::INGAME)
  3698. {
  3699. complain("Dest player must be in game!");
  3700. return false;
  3701. }
  3702. TResourceCap curRes1 = getPlayerState(player)->resources[r1];
  3703. vstd::amin(val, curRes1);
  3704. giveResource(player, r1, -(int)val);
  3705. giveResource(r2, r1, val);
  3706. return true;
  3707. }
  3708. bool CGameHandler::setFormation(ObjectInstanceID hid, ui8 formation)
  3709. {
  3710. const CGHeroInstance *h = getHero(hid);
  3711. if (!h)
  3712. {
  3713. logGlobal->error("Hero doesn't exist!");
  3714. return false;
  3715. }
  3716. ChangeFormation cf;
  3717. cf.hid = hid;
  3718. cf.formation = formation;
  3719. sendAndApply(&cf);
  3720. return true;
  3721. }
  3722. bool CGameHandler::queryReply(QueryID qid, const JsonNode & answer, PlayerColor player)
  3723. {
  3724. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3725. logGlobal->trace("Player %s attempts answering query %d with answer:", player, qid);
  3726. logGlobal->trace(answer.toJson());
  3727. auto topQuery = queries.topQuery(player);
  3728. COMPLAIN_RET_FALSE_IF(!topQuery, "This player doesn't have any queries!");
  3729. if(topQuery->queryID != qid)
  3730. {
  3731. auto currentQuery = queries.getQuery(qid);
  3732. if(currentQuery != nullptr && currentQuery->endsByPlayerAnswer())
  3733. currentQuery->setReply(answer);
  3734. COMPLAIN_RET("This player top query has different ID!"); //topQuery->queryID != qid
  3735. }
  3736. COMPLAIN_RET_FALSE_IF(!topQuery->endsByPlayerAnswer(), "This query cannot be ended by player's answer!");
  3737. topQuery->setReply(answer);
  3738. queries.popQuery(topQuery);
  3739. return true;
  3740. }
  3741. static EndAction end_action;
  3742. void CGameHandler::updateGateState()
  3743. {
  3744. // GATE_BRIDGE - leftmost tile, located over moat
  3745. // GATE_OUTER - central tile, mostly covered by gate image
  3746. // GATE_INNER - rightmost tile, inside the walls
  3747. // GATE_OUTER or GATE_INNER:
  3748. // - if defender moves unit on these tiles, bridge will open
  3749. // - if there is a creature (dead or alive) on these tiles, bridge will always remain open
  3750. // - blocked to attacker if bridge is closed
  3751. // GATE_BRIDGE
  3752. // - if there is a unit or corpse here, bridge can't open (and can't close in fortress)
  3753. // - if Force Field is cast here, bridge can't open (but can close, in any town)
  3754. // - deals moat damage to attacker if bridge is closed (fortress only)
  3755. bool hasForceFieldOnBridge = !battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), true).empty();
  3756. bool hasStackAtGateInner = gs->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_INNER), false) != nullptr;
  3757. bool hasStackAtGateOuter = gs->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_OUTER), false) != nullptr;
  3758. bool hasStackAtGateBridge = gs->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_BRIDGE), false) != nullptr;
  3759. bool hasWideMoat = vstd::contains_if(battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  3760. {
  3761. return obst->obstacleType == CObstacleInstance::MOAT;
  3762. });
  3763. BattleUpdateGateState db;
  3764. db.state = gs->curB->si.gateState;
  3765. if (gs->curB->si.wallState[EWallPart::GATE] == EWallState::DESTROYED)
  3766. {
  3767. db.state = EGateState::DESTROYED;
  3768. }
  3769. else if (db.state == EGateState::OPENED)
  3770. {
  3771. bool hasStackOnLongBridge = hasStackAtGateBridge && hasWideMoat;
  3772. bool gateCanClose = !hasStackAtGateInner && !hasStackAtGateOuter && !hasStackOnLongBridge;
  3773. if (gateCanClose)
  3774. db.state = EGateState::CLOSED;
  3775. else
  3776. db.state = EGateState::OPENED;
  3777. }
  3778. else // CLOSED or BLOCKED
  3779. {
  3780. bool gateBlocked = hasForceFieldOnBridge || hasStackAtGateBridge;
  3781. if (gateBlocked)
  3782. db.state = EGateState::BLOCKED;
  3783. else
  3784. db.state = EGateState::CLOSED;
  3785. }
  3786. if (db.state != gs->curB->si.gateState)
  3787. sendAndApply(&db);
  3788. }
  3789. bool CGameHandler::makeBattleAction(BattleAction &ba)
  3790. {
  3791. boost::unique_lock lock(battleActionMutex);
  3792. bool ok = true;
  3793. battle::Target target = ba.getTarget(gs->curB);
  3794. const CStack * stack = battleGetStackByID(ba.stackNumber); //may be nullptr if action is not about stack
  3795. const bool isAboutActiveStack = stack && (ba.stackNumber == gs->curB->getActiveStackID());
  3796. logGlobal->trace("Making action: %s", ba.toString());
  3797. switch(ba.actionType)
  3798. {
  3799. case EActionType::WALK: //walk
  3800. case EActionType::DEFEND: //defend
  3801. case EActionType::WAIT: //wait
  3802. case EActionType::WALK_AND_ATTACK: //walk or attack
  3803. case EActionType::SHOOT: //shoot
  3804. case EActionType::CATAPULT: //catapult
  3805. case EActionType::STACK_HEAL: //healing with First Aid Tent
  3806. case EActionType::MONSTER_SPELL:
  3807. if (!stack)
  3808. {
  3809. complain("No such stack!");
  3810. return false;
  3811. }
  3812. if (!stack->alive())
  3813. {
  3814. complain("This stack is dead: " + stack->nodeName());
  3815. return false;
  3816. }
  3817. if (battleTacticDist())
  3818. {
  3819. if (stack && stack->unitSide() != battleGetTacticsSide())
  3820. {
  3821. complain("This is not a stack of side that has tactics!");
  3822. return false;
  3823. }
  3824. }
  3825. else if (!isAboutActiveStack)
  3826. {
  3827. complain("Action has to be about active stack!");
  3828. return false;
  3829. }
  3830. }
  3831. auto wrapAction = [this](BattleAction &ba)
  3832. {
  3833. StartAction startAction(ba);
  3834. sendAndApply(&startAction);
  3835. return vstd::makeScopeGuard([&]()
  3836. {
  3837. sendAndApply(&end_action);
  3838. });
  3839. };
  3840. switch(ba.actionType)
  3841. {
  3842. case EActionType::END_TACTIC_PHASE: //wait
  3843. case EActionType::BAD_MORALE:
  3844. case EActionType::NO_ACTION:
  3845. {
  3846. auto wrapper = wrapAction(ba);
  3847. break;
  3848. }
  3849. case EActionType::WALK:
  3850. {
  3851. auto wrapper = wrapAction(ba);
  3852. if(target.size() < 1)
  3853. {
  3854. complain("Destination required for move action.");
  3855. ok = false;
  3856. break;
  3857. }
  3858. int walkedTiles = moveStack(ba.stackNumber, target.at(0).hexValue); //move
  3859. if (!walkedTiles)
  3860. complain("Stack failed movement!");
  3861. break;
  3862. }
  3863. case EActionType::DEFEND:
  3864. {
  3865. //defensive stance, TODO: filter out spell boosts from bonus (stone skin etc.)
  3866. SetStackEffect sse;
  3867. Bonus defenseBonusToAdd(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 20, -1, PrimarySkill::DEFENSE, BonusValueType::PERCENT_TO_ALL);
  3868. Bonus bonus2(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, stack->valOfBonuses(BonusType::DEFENSIVE_STANCE),
  3869. -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  3870. Bonus alternativeWeakCreatureBonus(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 1, -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  3871. BonusList defence = *stack->getBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, PrimarySkill::DEFENSE));
  3872. int oldDefenceValue = defence.totalValue();
  3873. defence.push_back(std::make_shared<Bonus>(defenseBonusToAdd));
  3874. defence.push_back(std::make_shared<Bonus>(bonus2));
  3875. int difference = defence.totalValue() - oldDefenceValue;
  3876. std::vector<Bonus> buffer;
  3877. if(difference == 0) //give replacement bonus for creatures not reaching 5 defense points (20% of def becomes 0)
  3878. {
  3879. difference = 1;
  3880. buffer.push_back(alternativeWeakCreatureBonus);
  3881. }
  3882. else
  3883. {
  3884. buffer.push_back(defenseBonusToAdd);
  3885. }
  3886. buffer.push_back(bonus2);
  3887. sse.toUpdate.push_back(std::make_pair(ba.stackNumber, buffer));
  3888. sendAndApply(&sse);
  3889. BattleLogMessage message;
  3890. MetaString text;
  3891. stack->addText(text, EMetaText::GENERAL_TXT, 120);
  3892. stack->addNameReplacement(text);
  3893. text.replaceNumber(difference);
  3894. message.lines.push_back(text);
  3895. sendAndApply(&message);
  3896. //don't break - we share code with next case
  3897. }
  3898. [[fallthrough]];
  3899. case EActionType::WAIT:
  3900. {
  3901. auto wrapper = wrapAction(ba);
  3902. break;
  3903. }
  3904. case EActionType::RETREAT: //retreat/flee
  3905. {
  3906. if (!gs->curB->battleCanFlee(gs->curB->sides.at(ba.side).color))
  3907. complain("Cannot retreat!");
  3908. else
  3909. setBattleResult(BattleResult::ESCAPE, !ba.side); //surrendering side loses
  3910. break;
  3911. }
  3912. case EActionType::SURRENDER:
  3913. {
  3914. PlayerColor player = gs->curB->sides.at(ba.side).color;
  3915. int cost = gs->curB->battleGetSurrenderCost(player);
  3916. if (cost < 0)
  3917. complain("Cannot surrender!");
  3918. else if (getResource(player, EGameResID::GOLD) < cost)
  3919. complain("Not enough gold to surrender!");
  3920. else
  3921. {
  3922. giveResource(player, EGameResID::GOLD, -cost);
  3923. setBattleResult(BattleResult::SURRENDER, !ba.side); //surrendering side loses
  3924. }
  3925. break;
  3926. }
  3927. case EActionType::WALK_AND_ATTACK: //walk or attack
  3928. {
  3929. auto wrapper = wrapAction(ba);
  3930. if(!stack)
  3931. {
  3932. complain("No attacker");
  3933. ok = false;
  3934. break;
  3935. }
  3936. if(target.size() < 2)
  3937. {
  3938. complain("Two destinations required for attack action.");
  3939. ok = false;
  3940. break;
  3941. }
  3942. BattleHex attackPos = target.at(0).hexValue;
  3943. BattleHex destinationTile = target.at(1).hexValue;
  3944. const CStack * destinationStack = gs->curB->battleGetStackByPos(destinationTile, true);
  3945. if(!destinationStack)
  3946. {
  3947. complain("Invalid target to attack");
  3948. ok = false;
  3949. break;
  3950. }
  3951. BattleHex startingPos = stack->getPosition();
  3952. int distance = moveStack(ba.stackNumber, attackPos);
  3953. logGlobal->trace("%s will attack %s", stack->nodeName(), destinationStack->nodeName());
  3954. if(stack->getPosition() != attackPos
  3955. && !(stack->doubleWide() && (stack->getPosition() == attackPos.cloneInDirection(stack->destShiftDir(), false)))
  3956. )
  3957. {
  3958. // we were not able to reach destination tile, nor occupy specified hex
  3959. // abort attack attempt, but treat this case as legal - we may have stepped onto a quicksands/mine
  3960. break;
  3961. }
  3962. if(destinationStack && stack->unitId() == destinationStack->unitId()) //we should just move, it will be handled by following check
  3963. {
  3964. destinationStack = nullptr;
  3965. }
  3966. if(!destinationStack)
  3967. {
  3968. complain("Unit can not attack itself");
  3969. ok = false;
  3970. break;
  3971. }
  3972. if(!CStack::isMeleeAttackPossible(stack, destinationStack))
  3973. {
  3974. complain("Attack cannot be performed!");
  3975. ok = false;
  3976. break;
  3977. }
  3978. //attack
  3979. int totalAttacks = stack->totalAttacks.getMeleeValue();
  3980. //TODO: move to CUnitState
  3981. const auto * attackingHero = gs->curB->battleGetFightingHero(ba.side);
  3982. if(attackingHero)
  3983. {
  3984. totalAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, stack->creatureIndex());
  3985. }
  3986. const bool firstStrike = destinationStack->hasBonusOfType(BonusType::FIRST_STRIKE);
  3987. const bool retaliation = destinationStack->ableToRetaliate();
  3988. for (int i = 0; i < totalAttacks; ++i)
  3989. {
  3990. //first strike
  3991. if(i == 0 && firstStrike && retaliation)
  3992. {
  3993. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, false, true);
  3994. }
  3995. //move can cause death, eg. by walking into the moat, first strike can cause death or paralysis/petrification
  3996. if(stack->alive() && !stack->hasBonusOfType(BonusType::NOT_ACTIVE) && destinationStack->alive())
  3997. {
  3998. makeAttack(stack, destinationStack, (i ? 0 : distance), destinationTile, i==0, false, false);//no distance travelled on second attack
  3999. }
  4000. //counterattack
  4001. //we check retaliation twice, so if it unblocked during attack it will work only on next attack
  4002. if(stack->alive()
  4003. && !stack->hasBonusOfType(BonusType::BLOCKS_RETALIATION)
  4004. && (i == 0 && !firstStrike)
  4005. && retaliation && destinationStack->ableToRetaliate())
  4006. {
  4007. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, false, true);
  4008. }
  4009. }
  4010. //return
  4011. if(stack->hasBonusOfType(BonusType::RETURN_AFTER_STRIKE)
  4012. && target.size() == 3
  4013. && startingPos != stack->getPosition()
  4014. && startingPos == target.at(2).hexValue
  4015. && stack->alive())
  4016. {
  4017. moveStack(ba.stackNumber, startingPos);
  4018. //NOTE: curStack->unitId() == ba.stackNumber (rev 1431)
  4019. }
  4020. break;
  4021. }
  4022. case EActionType::SHOOT:
  4023. {
  4024. if(target.size() < 1)
  4025. {
  4026. complain("Destination required for shot action.");
  4027. ok = false;
  4028. break;
  4029. }
  4030. auto destination = target.at(0).hexValue;
  4031. const CStack * destinationStack = gs->curB->battleGetStackByPos(destination);
  4032. if (!gs->curB->battleCanShoot(stack, destination))
  4033. {
  4034. complain("Cannot shoot!");
  4035. break;
  4036. }
  4037. if (!destinationStack)
  4038. {
  4039. complain("No target to shoot!");
  4040. break;
  4041. }
  4042. auto wrapper = wrapAction(ba);
  4043. makeAttack(stack, destinationStack, 0, destination, true, true, false);
  4044. //ranged counterattack
  4045. if (destinationStack->hasBonusOfType(BonusType::RANGED_RETALIATION)
  4046. && !stack->hasBonusOfType(BonusType::BLOCKS_RANGED_RETALIATION)
  4047. && destinationStack->ableToRetaliate()
  4048. && gs->curB->battleCanShoot(destinationStack, stack->getPosition())
  4049. && stack->alive()) //attacker may have died (fire shield)
  4050. {
  4051. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, true, true);
  4052. }
  4053. //allow more than one additional attack
  4054. int totalRangedAttacks = stack->totalAttacks.getRangedValue();
  4055. //TODO: move to CUnitState
  4056. const auto * attackingHero = gs->curB->battleGetFightingHero(ba.side);
  4057. if(attackingHero)
  4058. {
  4059. totalRangedAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, stack->creatureIndex());
  4060. }
  4061. for(int i = 1; i < totalRangedAttacks; ++i)
  4062. {
  4063. if(
  4064. stack->alive()
  4065. && destinationStack->alive()
  4066. && stack->shots.canUse()
  4067. )
  4068. {
  4069. makeAttack(stack, destinationStack, 0, destination, false, true, false);
  4070. }
  4071. }
  4072. break;
  4073. }
  4074. case EActionType::CATAPULT:
  4075. {
  4076. auto wrapper = wrapAction(ba);
  4077. const CStack * shooter = gs->curB->battleGetStackByID(ba.stackNumber);
  4078. std::shared_ptr<const Bonus> catapultAbility = stack->getBonusLocalFirst(Selector::type()(BonusType::CATAPULT));
  4079. if(!catapultAbility || catapultAbility->subtype < 0)
  4080. {
  4081. complain("We do not know how to shoot :P");
  4082. }
  4083. else
  4084. {
  4085. const CSpell * spell = SpellID(catapultAbility->subtype).toSpell();
  4086. spells::BattleCast parameters(gs->curB, shooter, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can shot infinitely by catapult
  4087. auto shotLevel = stack->valOfBonuses(Selector::typeSubtype(BonusType::CATAPULT_EXTRA_SHOTS, catapultAbility->subtype));
  4088. parameters.setSpellLevel(shotLevel);
  4089. parameters.cast(spellEnv, target);
  4090. }
  4091. //finish by scope guard
  4092. break;
  4093. }
  4094. case EActionType::STACK_HEAL: //healing with First Aid Tent
  4095. {
  4096. auto wrapper = wrapAction(ba);
  4097. const CStack * healer = gs->curB->battleGetStackByID(ba.stackNumber);
  4098. if(target.size() < 1)
  4099. {
  4100. complain("Destination required for heal action.");
  4101. ok = false;
  4102. break;
  4103. }
  4104. const battle::Unit * destStack = nullptr;
  4105. std::shared_ptr<const Bonus> healerAbility = stack->getBonusLocalFirst(Selector::type()(BonusType::HEALER));
  4106. if(target.at(0).unitValue)
  4107. destStack = target.at(0).unitValue;
  4108. else
  4109. destStack = gs->curB->battleGetUnitByPos(target.at(0).hexValue);
  4110. if(healer == nullptr || destStack == nullptr || !healerAbility || healerAbility->subtype < 0)
  4111. {
  4112. complain("There is either no healer, no destination, or healer cannot heal :P");
  4113. }
  4114. else
  4115. {
  4116. const CSpell * spell = SpellID(healerAbility->subtype).toSpell();
  4117. spells::BattleCast parameters(gs->curB, healer, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can heal infinitely by first aid tent
  4118. auto dest = battle::Destination(destStack, target.at(0).hexValue);
  4119. parameters.setSpellLevel(0);
  4120. parameters.cast(spellEnv, {dest});
  4121. }
  4122. break;
  4123. }
  4124. case EActionType::MONSTER_SPELL:
  4125. {
  4126. auto wrapper = wrapAction(ba);
  4127. const CStack * stack = gs->curB->battleGetStackByID(ba.stackNumber);
  4128. SpellID spellID = SpellID(ba.actionSubtype);
  4129. std::shared_ptr<const Bonus> randSpellcaster = stack->getBonus(Selector::type()(BonusType::RANDOM_SPELLCASTER));
  4130. std::shared_ptr<const Bonus> spellcaster = stack->getBonus(Selector::typeSubtype(BonusType::SPELLCASTER, spellID));
  4131. //TODO special bonus for genies ability
  4132. if (randSpellcaster && battleGetRandomStackSpell(getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_AIMED) < 0)
  4133. spellID = battleGetRandomStackSpell(getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_GENIE);
  4134. if (spellID < 0)
  4135. complain("That stack can't cast spells!");
  4136. else
  4137. {
  4138. const CSpell * spell = SpellID(spellID).toSpell();
  4139. spells::BattleCast parameters(gs->curB, stack, spells::Mode::CREATURE_ACTIVE, spell);
  4140. int32_t spellLvl = 0;
  4141. if(spellcaster)
  4142. vstd::amax(spellLvl, spellcaster->val);
  4143. if(randSpellcaster)
  4144. vstd::amax(spellLvl, randSpellcaster->val);
  4145. parameters.setSpellLevel(spellLvl);
  4146. parameters.cast(spellEnv, target);
  4147. }
  4148. break;
  4149. }
  4150. }
  4151. if(ba.actionType == EActionType::WAIT || ba.actionType == EActionType::DEFEND
  4152. || ba.actionType == EActionType::SHOOT || ba.actionType == EActionType::MONSTER_SPELL)
  4153. handleObstacleTriggersForUnit(*spellEnv, *stack);
  4154. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  4155. battleMadeAction.setn(true);
  4156. return ok;
  4157. }
  4158. bool CGameHandler::makeCustomAction(BattleAction & ba)
  4159. {
  4160. boost::unique_lock lock(battleActionMutex);
  4161. switch(ba.actionType)
  4162. {
  4163. case EActionType::HERO_SPELL:
  4164. {
  4165. COMPLAIN_RET_FALSE_IF(ba.side > 1, "Side must be 0 or 1!");
  4166. const CGHeroInstance *h = gs->curB->battleGetFightingHero(ba.side);
  4167. COMPLAIN_RET_FALSE_IF((!h), "Wrong caster!");
  4168. const CSpell * s = SpellID(ba.actionSubtype).toSpell();
  4169. if (!s)
  4170. {
  4171. logGlobal->error("Wrong spell id (%d)!", ba.actionSubtype);
  4172. return false;
  4173. }
  4174. spells::BattleCast parameters(gs->curB, h, spells::Mode::HERO, s);
  4175. spells::detail::ProblemImpl problem;
  4176. auto m = s->battleMechanics(&parameters);
  4177. if(!m->canBeCast(problem))//todo: should we check aimed cast?
  4178. {
  4179. logGlobal->warn("Spell cannot be cast!");
  4180. std::vector<std::string> texts;
  4181. problem.getAll(texts);
  4182. for(auto s : texts)
  4183. logGlobal->warn(s);
  4184. return false;
  4185. }
  4186. StartAction start_action(ba);
  4187. sendAndApply(&start_action); //start spell casting
  4188. parameters.cast(spellEnv, ba.getTarget(gs->curB));
  4189. sendAndApply(&end_action);
  4190. if (!gs->curB->battleGetStackByID(gs->curB->activeStack))
  4191. {
  4192. battleMadeAction.setn(true);
  4193. }
  4194. checkBattleStateChanges();
  4195. if (battleResult.get())
  4196. {
  4197. battleMadeAction.setn(true);
  4198. //battle will be ended by startBattle function
  4199. //endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  4200. }
  4201. return true;
  4202. }
  4203. }
  4204. return false;
  4205. }
  4206. void CGameHandler::stackEnchantedTrigger(const CStack * st)
  4207. {
  4208. auto bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTED)));
  4209. for(auto b : bl)
  4210. {
  4211. const CSpell * sp = SpellID(b->subtype).toSpell();
  4212. if(!sp)
  4213. continue;
  4214. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  4215. const int32_t level = ((val > 3) ? (val - 3) : val);
  4216. spells::BattleCast battleCast(gs->curB, st, spells::Mode::PASSIVE, sp);
  4217. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  4218. battleCast.setEffectDuration(50);
  4219. battleCast.setSpellLevel(level);
  4220. spells::Target target;
  4221. if(val > 3)
  4222. {
  4223. for(auto s : gs->curB->battleGetAllStacks())
  4224. if(battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  4225. target.emplace_back(s);
  4226. }
  4227. else
  4228. {
  4229. target.emplace_back(st);
  4230. }
  4231. battleCast.applyEffects(spellEnv, target, false, true);
  4232. }
  4233. }
  4234. void CGameHandler::stackTurnTrigger(const CStack *st)
  4235. {
  4236. BattleTriggerEffect bte;
  4237. bte.stackID = st->unitId();
  4238. bte.effect = -1;
  4239. bte.val = 0;
  4240. bte.additionalInfo = 0;
  4241. if (st->alive())
  4242. {
  4243. //unbind
  4244. if (st->hasBonus(Selector::type()(BonusType::BIND_EFFECT)))
  4245. {
  4246. bool unbind = true;
  4247. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::BIND_EFFECT)));
  4248. auto adjacent = gs->curB->battleAdjacentUnits(st);
  4249. for (auto b : bl)
  4250. {
  4251. if(b->additionalInfo != CAddInfo::NONE)
  4252. {
  4253. const CStack * stack = gs->curB->battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  4254. if(stack)
  4255. {
  4256. if(vstd::contains(adjacent, stack)) //binding stack is still present
  4257. unbind = false;
  4258. }
  4259. }
  4260. else
  4261. {
  4262. unbind = false;
  4263. }
  4264. }
  4265. if (unbind)
  4266. {
  4267. BattleSetStackProperty ssp;
  4268. ssp.which = BattleSetStackProperty::UNBIND;
  4269. ssp.stackID = st->unitId();
  4270. sendAndApply(&ssp);
  4271. }
  4272. }
  4273. if (st->hasBonusOfType(BonusType::POISON))
  4274. {
  4275. std::shared_ptr<const Bonus> b = st->getBonusLocalFirst(Selector::source(BonusSource::SPELL_EFFECT, SpellID::POISON).And(Selector::type()(BonusType::STACK_HEALTH)));
  4276. if (b) //TODO: what if not?...
  4277. {
  4278. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  4279. if (bte.val < b->val) //(negative) poison effect increases - update it
  4280. {
  4281. bte.effect = vstd::to_underlying(BonusType::POISON);
  4282. sendAndApply(&bte);
  4283. }
  4284. }
  4285. }
  4286. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  4287. {
  4288. const PlayerColor opponent = gs->curB->otherPlayer(gs->curB->battleGetOwner(st));
  4289. const CGHeroInstance * opponentHero = gs->curB->getHero(opponent);
  4290. if(opponentHero)
  4291. {
  4292. ui32 manaDrained = st->valOfBonuses(BonusType::MANA_DRAIN);
  4293. vstd::amin(manaDrained, opponentHero->mana);
  4294. if(manaDrained)
  4295. {
  4296. bte.effect = vstd::to_underlying(BonusType::MANA_DRAIN);
  4297. bte.val = manaDrained;
  4298. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  4299. sendAndApply(&bte);
  4300. }
  4301. }
  4302. }
  4303. if (st->isLiving() && !st->hasBonusOfType(BonusType::FEARLESS))
  4304. {
  4305. bool fearsomeCreature = false;
  4306. for (CStack * stack : gs->curB->stacks)
  4307. {
  4308. if (battleMatchOwner(st, stack) && stack->alive() && stack->hasBonusOfType(BonusType::FEAR))
  4309. {
  4310. fearsomeCreature = true;
  4311. break;
  4312. }
  4313. }
  4314. if (fearsomeCreature)
  4315. {
  4316. if (getRandomGenerator().nextInt(99) < 10) //fixed 10%
  4317. {
  4318. bte.effect = vstd::to_underlying(BonusType::FEAR);
  4319. sendAndApply(&bte);
  4320. }
  4321. }
  4322. }
  4323. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTER)));
  4324. int side = gs->curB->whatSide(st->unitOwner());
  4325. if(st->canCast() && gs->curB->battleGetEnchanterCounter(side) == 0)
  4326. {
  4327. bool cast = false;
  4328. while(!bl.empty() && !cast)
  4329. {
  4330. auto bonus = *RandomGeneratorUtil::nextItem(bl, getRandomGenerator());
  4331. auto spellID = SpellID(bonus->subtype);
  4332. const CSpell * spell = SpellID(spellID).toSpell();
  4333. bl.remove_if([&bonus](const Bonus * b)
  4334. {
  4335. return b == bonus.get();
  4336. });
  4337. spells::BattleCast parameters(gs->curB, st, spells::Mode::ENCHANTER, spell);
  4338. parameters.setSpellLevel(bonus->val);
  4339. parameters.massive = true;
  4340. parameters.smart = true;
  4341. //todo: recheck effect level
  4342. if(parameters.castIfPossible(spellEnv, spells::Target(1, spells::Destination())))
  4343. {
  4344. cast = true;
  4345. int cooldown = bonus->additionalInfo[0];
  4346. BattleSetStackProperty ssp;
  4347. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  4348. ssp.absolute = false;
  4349. ssp.val = cooldown;
  4350. ssp.stackID = st->unitId();
  4351. sendAndApply(&ssp);
  4352. }
  4353. }
  4354. }
  4355. }
  4356. }
  4357. void CGameHandler::handleTimeEvents()
  4358. {
  4359. gs->map->events.sort(evntCmp);
  4360. while(gs->map->events.size() && gs->map->events.front().firstOccurence+1 == gs->day)
  4361. {
  4362. CMapEvent ev = gs->map->events.front();
  4363. for (int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
  4364. {
  4365. auto color = PlayerColor(player);
  4366. const PlayerState * pinfo = getPlayerState(color, false); //do not output error if player does not exist
  4367. if (pinfo //player exists
  4368. && (ev.players & 1<<player) //event is enabled to this player
  4369. && ((ev.computerAffected && !pinfo->human)
  4370. || (ev.humanAffected && pinfo->human)
  4371. )
  4372. )
  4373. {
  4374. //give resources
  4375. giveResources(color, ev.resources);
  4376. //prepare dialog
  4377. InfoWindow iw;
  4378. iw.player = color;
  4379. iw.text.appendRawString(ev.message);
  4380. for (int i=0; i<ev.resources.size(); i++)
  4381. {
  4382. if (ev.resources[i]) //if resource is changed, we add it to the dialog
  4383. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,ev.resources[i],0);
  4384. }
  4385. sendAndApply(&iw); //show dialog
  4386. }
  4387. } //PLAYERS LOOP
  4388. if (ev.nextOccurence)
  4389. {
  4390. gs->map->events.pop_front();
  4391. ev.firstOccurence += ev.nextOccurence;
  4392. auto it = gs->map->events.begin();
  4393. while(it != gs->map->events.end() && it->earlierThanOrEqual(ev))
  4394. it++;
  4395. gs->map->events.insert(it, ev);
  4396. }
  4397. else
  4398. {
  4399. gs->map->events.pop_front();
  4400. }
  4401. }
  4402. //TODO send only if changed
  4403. UpdateMapEvents ume;
  4404. ume.events = gs->map->events;
  4405. sendAndApply(&ume);
  4406. }
  4407. void CGameHandler::handleTownEvents(CGTownInstance * town, NewTurn &n)
  4408. {
  4409. town->events.sort(evntCmp);
  4410. while(town->events.size() && town->events.front().firstOccurence == gs->day)
  4411. {
  4412. PlayerColor player = town->tempOwner;
  4413. CCastleEvent ev = town->events.front();
  4414. const PlayerState * pinfo = getPlayerState(player, false);
  4415. if (pinfo //player exists
  4416. && (ev.players & 1<<player.getNum()) //event is enabled to this player
  4417. && ((ev.computerAffected && !pinfo->human)
  4418. || (ev.humanAffected && pinfo->human)))
  4419. {
  4420. // dialog
  4421. InfoWindow iw;
  4422. iw.player = player;
  4423. iw.text.appendRawString(ev.message);
  4424. if (ev.resources.nonZero())
  4425. {
  4426. TResources was = n.res[player];
  4427. n.res[player] += ev.resources;
  4428. n.res[player].amax(0);
  4429. for (int i=0; i<ev.resources.size(); i++)
  4430. if (ev.resources[i] && pinfo->resources[i] != n.res.at(player)[i]) //if resource had changed, we add it to the dialog
  4431. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,n.res.at(player)[i]-was[i],0);
  4432. }
  4433. for (auto & i : ev.buildings)
  4434. {
  4435. if (!town->hasBuilt(i))
  4436. {
  4437. buildStructure(town->id, i, true);
  4438. iw.components.emplace_back(Component::EComponentType::BUILDING, town->subID, i, 0);
  4439. }
  4440. }
  4441. if (!ev.creatures.empty() && !vstd::contains(n.cres, town->id))
  4442. {
  4443. n.cres[town->id].tid = town->id;
  4444. n.cres[town->id].creatures = town->creatures;
  4445. }
  4446. auto & sac = n.cres[town->id];
  4447. for (si32 i=0;i<ev.creatures.size();i++) //creature growths
  4448. {
  4449. if (!town->creatures.at(i).second.empty() && ev.creatures.at(i) > 0)//there is dwelling
  4450. {
  4451. sac.creatures[i].first += ev.creatures.at(i);
  4452. iw.components.emplace_back(Component::EComponentType::CREATURE,
  4453. town->creatures.at(i).second.back(), ev.creatures.at(i), 0);
  4454. }
  4455. }
  4456. sendAndApply(&iw); //show dialog
  4457. }
  4458. if (ev.nextOccurence)
  4459. {
  4460. town->events.pop_front();
  4461. ev.firstOccurence += ev.nextOccurence;
  4462. auto it = town->events.begin();
  4463. while(it != town->events.end() && it->earlierThanOrEqual(ev))
  4464. it++;
  4465. town->events.insert(it, ev);
  4466. }
  4467. else
  4468. {
  4469. town->events.pop_front();
  4470. }
  4471. }
  4472. //TODO send only if changed
  4473. UpdateCastleEvents uce;
  4474. uce.town = town->id;
  4475. uce.events = town->events;
  4476. sendAndApply(&uce);
  4477. }
  4478. bool CGameHandler::complain(const std::string &problem)
  4479. {
  4480. playerMessages->broadcastSystemMessage("Server encountered a problem: " + problem);
  4481. logGlobal->error(problem);
  4482. return true;
  4483. }
  4484. void CGameHandler::showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits)
  4485. {
  4486. //PlayerColor player = getOwner(hid);
  4487. auto upperArmy = dynamic_cast<const CArmedInstance*>(getObj(upobj));
  4488. auto lowerArmy = dynamic_cast<const CArmedInstance*>(getObj(hid));
  4489. assert(lowerArmy);
  4490. assert(upperArmy);
  4491. auto garrisonQuery = std::make_shared<CGarrisonDialogQuery>(this, upperArmy, lowerArmy);
  4492. queries.addQuery(garrisonQuery);
  4493. GarrisonDialog gd;
  4494. gd.hid = hid;
  4495. gd.objid = upobj;
  4496. gd.removableUnits = removableUnits;
  4497. gd.queryID = garrisonQuery->queryID;
  4498. sendAndApply(&gd);
  4499. }
  4500. void CGameHandler::showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId)
  4501. {
  4502. OpenWindow ow;
  4503. ow.window = EOpenWindowMode::THIEVES_GUILD;
  4504. ow.id1 = player.getNum();
  4505. ow.id2 = requestingObjId.getNum();
  4506. sendAndApply(&ow);
  4507. }
  4508. bool CGameHandler::isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2)
  4509. {
  4510. if (id1 == id2)
  4511. return true;
  4512. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  4513. if (!o1 || !o2)
  4514. return true; //arranging stacks within an object should be always allowed
  4515. if (o1 && o2)
  4516. {
  4517. if (o1->ID == Obj::TOWN)
  4518. {
  4519. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  4520. if (t->visitingHero == o2 || t->garrisonHero == o2)
  4521. return true;
  4522. }
  4523. if (o2->ID == Obj::TOWN)
  4524. {
  4525. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  4526. if (t->visitingHero == o1 || t->garrisonHero == o1)
  4527. return true;
  4528. }
  4529. if (o1->ID == Obj::HERO && o2->ID == Obj::HERO)
  4530. {
  4531. const CGHeroInstance *h1 = static_cast<const CGHeroInstance*>(o1);
  4532. const CGHeroInstance *h2 = static_cast<const CGHeroInstance*>(o2);
  4533. // two heroes in same town (garrisoned and visiting)
  4534. if (h1->visitedTown != nullptr && h2->visitedTown != nullptr && h1->visitedTown == h2->visitedTown)
  4535. return true;
  4536. }
  4537. //Ongoing garrison exchange - usually picking from top garison (from o1 to o2), but who knows
  4538. auto dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries.topQuery(o1->tempOwner));
  4539. if (!dialog)
  4540. {
  4541. dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries.topQuery(o2->tempOwner));
  4542. }
  4543. if (dialog)
  4544. {
  4545. auto topArmy = dialog->exchangingArmies.at(0);
  4546. auto bottomArmy = dialog->exchangingArmies.at(1);
  4547. if ((topArmy == o1 && bottomArmy == o2) || (bottomArmy == o1 && topArmy == o2))
  4548. return true;
  4549. }
  4550. }
  4551. return false;
  4552. }
  4553. void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInstance * h)
  4554. {
  4555. using events::ObjectVisitStarted;
  4556. logGlobal->debug("%s visits %s (%d:%d)", h->nodeName(), obj->getObjectName(), obj->ID, obj->subID);
  4557. std::shared_ptr<CObjectVisitQuery> visitQuery;
  4558. auto startVisit = [&](ObjectVisitStarted & event)
  4559. {
  4560. auto visitedObject = obj;
  4561. if(obj->ID == Obj::HERO)
  4562. {
  4563. auto visitedHero = static_cast<const CGHeroInstance *>(obj);
  4564. const auto visitedTown = visitedHero->visitedTown;
  4565. if(visitedTown)
  4566. {
  4567. const bool isEnemy = visitedHero->getOwner() != h->getOwner();
  4568. if(isEnemy && !visitedTown->isBattleOutsideTown(visitedHero))
  4569. visitedObject = visitedTown;
  4570. }
  4571. }
  4572. visitQuery = std::make_shared<CObjectVisitQuery>(this, visitedObject, h, visitedObject->visitablePos());
  4573. queries.addQuery(visitQuery); //TODO real visit pos
  4574. HeroVisit hv;
  4575. hv.objId = obj->id;
  4576. hv.heroId = h->id;
  4577. hv.player = h->tempOwner;
  4578. hv.starting = true;
  4579. sendAndApply(&hv);
  4580. obj->onHeroVisit(h);
  4581. };
  4582. ObjectVisitStarted::defaultExecute(serverEventBus.get(), startVisit, h->tempOwner, h->id, obj->id);
  4583. if(visitQuery)
  4584. queries.popIfTop(visitQuery); //visit ends here if no queries were created
  4585. }
  4586. void CGameHandler::objectVisitEnded(const CObjectVisitQuery & query)
  4587. {
  4588. using events::ObjectVisitEnded;
  4589. logGlobal->debug("%s visit ends.\n", query.visitingHero->nodeName());
  4590. auto endVisit = [&](ObjectVisitEnded & event)
  4591. {
  4592. HeroVisit hv;
  4593. hv.player = event.getPlayer();
  4594. hv.heroId = event.getHero();
  4595. hv.starting = false;
  4596. sendAndApply(&hv);
  4597. };
  4598. //TODO: ObjectVisitEnded should also have id of visited object,
  4599. //but this requires object being deleted only by `removeAfterVisit()` but not `removeObject()`
  4600. ObjectVisitEnded::defaultExecute(serverEventBus.get(), endVisit, query.players.front(), query.visitingHero->id);
  4601. }
  4602. bool CGameHandler::buildBoat(ObjectInstanceID objid, PlayerColor playerID)
  4603. {
  4604. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  4605. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  4606. {
  4607. complain("Cannot build boat in this shipyard!");
  4608. return false;
  4609. }
  4610. TResources boatCost;
  4611. obj->getBoatCost(boatCost);
  4612. TResources aviable = getPlayerState(playerID)->resources;
  4613. if (!aviable.canAfford(boatCost))
  4614. {
  4615. complain("Not enough resources to build a boat!");
  4616. return false;
  4617. }
  4618. int3 tile = obj->bestLocation();
  4619. if (!gs->map->isInTheMap(tile))
  4620. {
  4621. complain("Cannot find appropriate tile for a boat!");
  4622. return false;
  4623. }
  4624. giveResources(playerID, -boatCost);
  4625. createObject(tile, Obj::BOAT, obj->getBoatType().getNum());
  4626. return true;
  4627. }
  4628. void CGameHandler::engageIntoBattle(PlayerColor player)
  4629. {
  4630. //notify interfaces
  4631. PlayerBlocked pb;
  4632. pb.player = player;
  4633. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  4634. pb.startOrEnd = PlayerBlocked::BLOCKADE_STARTED;
  4635. sendAndApply(&pb);
  4636. }
  4637. void CGameHandler::checkVictoryLossConditions(const std::set<PlayerColor> & playerColors)
  4638. {
  4639. for (auto playerColor : playerColors)
  4640. {
  4641. if (getPlayerState(playerColor, false))
  4642. checkVictoryLossConditionsForPlayer(playerColor);
  4643. }
  4644. }
  4645. void CGameHandler::checkVictoryLossConditionsForAll()
  4646. {
  4647. std::set<PlayerColor> playerColors;
  4648. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  4649. {
  4650. playerColors.insert(PlayerColor(i));
  4651. }
  4652. checkVictoryLossConditions(playerColors);
  4653. }
  4654. void CGameHandler::checkVictoryLossConditionsForPlayer(PlayerColor player)
  4655. {
  4656. const PlayerState * p = getPlayerState(player);
  4657. if(!p || p->status != EPlayerStatus::INGAME) return;
  4658. auto victoryLossCheckResult = gs->checkForVictoryAndLoss(player);
  4659. if (victoryLossCheckResult.victory() || victoryLossCheckResult.loss())
  4660. {
  4661. InfoWindow iw;
  4662. getVictoryLossMessage(player, victoryLossCheckResult, iw);
  4663. sendAndApply(&iw);
  4664. PlayerEndsGame peg;
  4665. peg.player = player;
  4666. peg.victoryLossCheckResult = victoryLossCheckResult;
  4667. sendAndApply(&peg);
  4668. if (victoryLossCheckResult.victory())
  4669. {
  4670. //one player won -> all enemies lost
  4671. for (auto i = gs->players.cbegin(); i!=gs->players.cend(); i++)
  4672. {
  4673. if (i->first != player && getPlayerState(i->first)->status == EPlayerStatus::INGAME)
  4674. {
  4675. peg.player = i->first;
  4676. peg.victoryLossCheckResult = getPlayerRelations(player, i->first) == PlayerRelations::ALLIES ?
  4677. victoryLossCheckResult : victoryLossCheckResult.invert(); // ally of winner
  4678. InfoWindow iw;
  4679. getVictoryLossMessage(player, peg.victoryLossCheckResult, iw);
  4680. iw.player = i->first;
  4681. sendAndApply(&iw);
  4682. sendAndApply(&peg);
  4683. }
  4684. }
  4685. if(p->human)
  4686. {
  4687. lobby->state = EServerState::GAMEPLAY_ENDED;
  4688. }
  4689. }
  4690. else
  4691. {
  4692. //copy heroes vector to avoid iterator invalidation as removal change PlayerState
  4693. auto hlp = p->heroes;
  4694. for (auto h : hlp) //eliminate heroes
  4695. {
  4696. if (h.get())
  4697. removeObject(h);
  4698. }
  4699. //player lost -> all his objects become unflagged (neutral)
  4700. for (auto obj : gs->map->objects) //unflag objs
  4701. {
  4702. if (obj.get() && obj->tempOwner == player)
  4703. setOwner(obj, PlayerColor::NEUTRAL);
  4704. }
  4705. //eliminating one player may cause victory of another:
  4706. std::set<PlayerColor> playerColors;
  4707. //do not copy player state (CBonusSystemNode) by value
  4708. for (auto &p : gs->players) //players may have different colors, iterate over players and not integers
  4709. {
  4710. if (p.first != player)
  4711. playerColors.insert(p.first);
  4712. }
  4713. //notify all players
  4714. for (auto pc : playerColors)
  4715. {
  4716. if (getPlayerState(pc)->status == EPlayerStatus::INGAME)
  4717. {
  4718. InfoWindow iw;
  4719. getVictoryLossMessage(player, victoryLossCheckResult.invert(), iw);
  4720. iw.player = pc;
  4721. sendAndApply(&iw);
  4722. }
  4723. }
  4724. checkVictoryLossConditions(playerColors);
  4725. }
  4726. auto playerInfo = getPlayerState(gs->currentPlayer, false);
  4727. // If we are called before the actual game start, there might be no current player
  4728. if (playerInfo && playerInfo->status != EPlayerStatus::INGAME)
  4729. {
  4730. // If player making turn has lost his turn must be over as well
  4731. states.setFlag(gs->currentPlayer, &PlayerStatus::makingTurn, false);
  4732. }
  4733. }
  4734. }
  4735. void CGameHandler::getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const
  4736. {
  4737. out.player = player;
  4738. out.text = victoryLossCheckResult.messageToSelf;
  4739. out.text.replaceLocalString(EMetaText::COLOR, player.getNum());
  4740. out.components.emplace_back(Component::EComponentType::FLAG, player.getNum(), 0, 0);
  4741. }
  4742. bool CGameHandler::dig(const CGHeroInstance *h)
  4743. {
  4744. if (h->diggingStatus() != EDiggingStatus::CAN_DIG) //checks for terrain and movement
  4745. COMPLAIN_RETF("Hero cannot dig (error code %d)!", h->diggingStatus());
  4746. createObject(h->visitablePos(), Obj::HOLE, 0 );
  4747. //take MPs
  4748. SetMovePoints smp;
  4749. smp.hid = h->id;
  4750. smp.val = 0;
  4751. sendAndApply(&smp);
  4752. InfoWindow iw;
  4753. iw.type = EInfoWindowMode::AUTO;
  4754. iw.player = h->tempOwner;
  4755. if (gs->map->grailPos == h->visitablePos())
  4756. {
  4757. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  4758. iw.text.appendLocalString(EMetaText::ART_NAMES, ArtifactID::GRAIL);
  4759. iw.soundID = soundBase::ULTIMATEARTIFACT;
  4760. giveHeroNewArtifact(h, VLC->arth->objects[ArtifactID::GRAIL], ArtifactPosition::FIRST_AVAILABLE); //give grail
  4761. sendAndApply(&iw);
  4762. iw.soundID = soundBase::invalid;
  4763. iw.components.emplace_back(Component::EComponentType::ARTIFACT, ArtifactID::GRAIL, 0, 0);
  4764. iw.text.clear();
  4765. iw.text.appendLocalString(EMetaText::ART_DESCR, ArtifactID::GRAIL);
  4766. sendAndApply(&iw);
  4767. }
  4768. else
  4769. {
  4770. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  4771. iw.soundID = soundBase::Dig;
  4772. sendAndApply(&iw);
  4773. }
  4774. return true;
  4775. }
  4776. void CGameHandler::attackCasting(bool ranged, BonusType attackMode, const battle::Unit * attacker, const battle::Unit * defender)
  4777. {
  4778. if(attacker->hasBonusOfType(attackMode))
  4779. {
  4780. std::set<SpellID> spellsToCast;
  4781. TConstBonusListPtr spells = attacker->getBonuses(Selector::type()(attackMode));
  4782. for(const auto & sf : *spells)
  4783. {
  4784. spellsToCast.insert(SpellID(sf->subtype));
  4785. }
  4786. for(SpellID spellID : spellsToCast)
  4787. {
  4788. bool castMe = false;
  4789. if(!defender->alive())
  4790. {
  4791. logGlobal->debug("attackCasting: all attacked creatures have been killed");
  4792. return;
  4793. }
  4794. int32_t spellLevel = 0;
  4795. TConstBonusListPtr spellsByType = attacker->getBonuses(Selector::typeSubtype(attackMode, spellID));
  4796. for(const auto & sf : *spellsByType)
  4797. {
  4798. int meleeRanged;
  4799. if(sf->additionalInfo.size() < 2)
  4800. {
  4801. // legacy format
  4802. vstd::amax(spellLevel, sf->additionalInfo[0] % 1000);
  4803. meleeRanged = sf->additionalInfo[0] / 1000;
  4804. }
  4805. else
  4806. {
  4807. vstd::amax(spellLevel, sf->additionalInfo[0]);
  4808. meleeRanged = sf->additionalInfo[1];
  4809. }
  4810. if (meleeRanged == 0 || (meleeRanged == 1 && ranged) || (meleeRanged == 2 && !ranged))
  4811. castMe = true;
  4812. }
  4813. int chance = attacker->valOfBonuses((Selector::typeSubtype(attackMode, spellID)));
  4814. vstd::amin(chance, 100);
  4815. const CSpell * spell = SpellID(spellID).toSpell();
  4816. spells::AbilityCaster caster(attacker, spellLevel);
  4817. spells::Target target;
  4818. target.emplace_back(defender);
  4819. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  4820. auto m = spell->battleMechanics(&parameters);
  4821. spells::detail::ProblemImpl ignored;
  4822. if(!m->canBeCastAt(target, ignored))
  4823. continue;
  4824. //check if spell should be cast (probability handling)
  4825. if(getRandomGenerator().nextInt(99) >= chance)
  4826. continue;
  4827. //casting
  4828. if(castMe)
  4829. {
  4830. parameters.cast(spellEnv, target);
  4831. }
  4832. }
  4833. }
  4834. }
  4835. void CGameHandler::handleAttackBeforeCasting(bool ranged, const CStack * attacker, const CStack * defender)
  4836. {
  4837. attackCasting(ranged, BonusType::SPELL_BEFORE_ATTACK, attacker, defender); //no death stare / acid breath needed?
  4838. }
  4839. void CGameHandler::handleAfterAttackCasting(bool ranged, const CStack * attacker, const CStack * defender)
  4840. {
  4841. if(!attacker->alive() || !defender->alive()) // can be already dead
  4842. return;
  4843. attackCasting(ranged, BonusType::SPELL_AFTER_ATTACK, attacker, defender);
  4844. if(!defender->alive())
  4845. {
  4846. //don't try death stare or acid breath on dead stack (crash!)
  4847. return;
  4848. }
  4849. if(attacker->hasBonusOfType(BonusType::DEATH_STARE))
  4850. {
  4851. // mechanics of Death Stare as in H3:
  4852. // each gorgon have 10% chance to kill (counted separately in H3) -> binomial distribution
  4853. //original formula x = min(x, (gorgons_count + 9)/10);
  4854. double chanceToKill = attacker->valOfBonuses(BonusType::DEATH_STARE, 0) / 100.0f;
  4855. vstd::amin(chanceToKill, 1); //cap at 100%
  4856. std::binomial_distribution<> distribution(attacker->getCount(), chanceToKill);
  4857. int staredCreatures = distribution(getRandomGenerator().getStdGenerator());
  4858. double cap = 1 / std::max(chanceToKill, (double)(0.01));//don't divide by 0
  4859. int maxToKill = static_cast<int>((attacker->getCount() + cap - 1) / cap); //not much more than chance * count
  4860. vstd::amin(staredCreatures, maxToKill);
  4861. staredCreatures += (attacker->level() * attacker->valOfBonuses(BonusType::DEATH_STARE, 1)) / defender->level();
  4862. if(staredCreatures)
  4863. {
  4864. //TODO: death stare was not originally available for multiple-hex attacks, but...
  4865. const CSpell * spell = SpellID(SpellID::DEATH_STARE).toSpell();
  4866. spells::AbilityCaster caster(attacker, 0);
  4867. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  4868. spells::Target target;
  4869. target.emplace_back(defender);
  4870. parameters.setEffectValue(staredCreatures);
  4871. parameters.cast(spellEnv, target);
  4872. }
  4873. }
  4874. if(!defender->alive())
  4875. return;
  4876. int64_t acidDamage = 0;
  4877. TConstBonusListPtr acidBreath = attacker->getBonuses(Selector::type()(BonusType::ACID_BREATH));
  4878. for(const auto & b : *acidBreath)
  4879. {
  4880. if(b->additionalInfo[0] > getRandomGenerator().nextInt(99))
  4881. acidDamage += b->val;
  4882. }
  4883. if(acidDamage > 0)
  4884. {
  4885. const CSpell * spell = SpellID(SpellID::ACID_BREATH_DAMAGE).toSpell();
  4886. spells::AbilityCaster caster(attacker, 0);
  4887. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  4888. spells::Target target;
  4889. target.emplace_back(defender);
  4890. parameters.setEffectValue(acidDamage * attacker->getCount());
  4891. parameters.cast(spellEnv, target);
  4892. }
  4893. if(!defender->alive())
  4894. return;
  4895. if(attacker->hasBonusOfType(BonusType::TRANSMUTATION) && defender->isLiving()) //transmutation mechanics, similar to WoG werewolf ability
  4896. {
  4897. double chanceToTrigger = attacker->valOfBonuses(BonusType::TRANSMUTATION) / 100.0f;
  4898. vstd::amin(chanceToTrigger, 1); //cap at 100%
  4899. if(getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  4900. return;
  4901. int bonusAdditionalInfo = attacker->getBonus(Selector::type()(BonusType::TRANSMUTATION))->additionalInfo[0];
  4902. if(defender->unitType()->getId() == bonusAdditionalInfo ||
  4903. (bonusAdditionalInfo == CAddInfo::NONE && defender->unitType()->getId() == attacker->unitType()->getId()))
  4904. return;
  4905. battle::UnitInfo resurrectInfo;
  4906. resurrectInfo.id = gs->curB->battleNextUnitId();
  4907. resurrectInfo.summoned = false;
  4908. resurrectInfo.position = defender->getPosition();
  4909. resurrectInfo.side = defender->unitSide();
  4910. if(bonusAdditionalInfo != CAddInfo::NONE)
  4911. resurrectInfo.type = CreatureID(bonusAdditionalInfo);
  4912. else
  4913. resurrectInfo.type = attacker->creatureId();
  4914. if(attacker->hasBonusOfType((BonusType::TRANSMUTATION), 0))
  4915. resurrectInfo.count = std::max((defender->getCount() * defender->getMaxHealth()) / resurrectInfo.type.toCreature()->getMaxHealth(), 1u);
  4916. else if (attacker->hasBonusOfType((BonusType::TRANSMUTATION), 1))
  4917. resurrectInfo.count = defender->getCount();
  4918. else
  4919. return; //wrong subtype
  4920. BattleUnitsChanged addUnits;
  4921. addUnits.changedStacks.emplace_back(resurrectInfo.id, UnitChanges::EOperation::ADD);
  4922. resurrectInfo.save(addUnits.changedStacks.back().data);
  4923. BattleUnitsChanged removeUnits;
  4924. removeUnits.changedStacks.emplace_back(defender->unitId(), UnitChanges::EOperation::REMOVE);
  4925. sendAndApply(&removeUnits);
  4926. sendAndApply(&addUnits);
  4927. }
  4928. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0) || attacker->hasBonusOfType(BonusType::DESTRUCTION, 1))
  4929. {
  4930. double chanceToTrigger = 0;
  4931. int amountToDie = 0;
  4932. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0)) //killing by percentage
  4933. {
  4934. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 0) / 100.0f;
  4935. int percentageToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(0)))->additionalInfo[0];
  4936. amountToDie = static_cast<int>(defender->getCount() * percentageToDie * 0.01f);
  4937. }
  4938. else if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 1)) //killing by count
  4939. {
  4940. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 1) / 100.0f;
  4941. amountToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(1)))->additionalInfo[0];
  4942. }
  4943. vstd::amin(chanceToTrigger, 1); //cap trigger chance at 100%
  4944. if(getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  4945. return;
  4946. BattleStackAttacked bsa;
  4947. bsa.attackerID = -1;
  4948. bsa.stackAttacked = defender->unitId();
  4949. bsa.damageAmount = amountToDie * defender->getMaxHealth();
  4950. bsa.flags = BattleStackAttacked::SPELL_EFFECT;
  4951. bsa.spellID = SpellID::SLAYER;
  4952. defender->prepareAttacked(bsa, getRandomGenerator());
  4953. StacksInjured si;
  4954. si.stacks.push_back(bsa);
  4955. sendAndApply(&si);
  4956. sendGenericKilledLog(defender, bsa.killedAmount, false);
  4957. }
  4958. }
  4959. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  4960. {
  4961. if (!t.visitableObjects.empty())
  4962. {
  4963. //to prevent self-visiting heroes on space press
  4964. if (t.visitableObjects.back() != h)
  4965. objectVisited(t.visitableObjects.back(), h);
  4966. else if (t.visitableObjects.size() > 1)
  4967. objectVisited(*(t.visitableObjects.end()-2),h);
  4968. }
  4969. }
  4970. bool CGameHandler::sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count)
  4971. {
  4972. if (!hero)
  4973. COMPLAIN_RET("You need hero to sacrifice creature!");
  4974. int expSum = 0;
  4975. auto finish = [this, &hero, &expSum]()
  4976. {
  4977. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  4978. };
  4979. for(int i = 0; i < slot.size(); ++i)
  4980. {
  4981. int oldCount = hero->getStackCount(slot[i]);
  4982. if(oldCount < (int)count[i])
  4983. {
  4984. finish();
  4985. COMPLAIN_RET("Not enough creatures to sacrifice!")
  4986. }
  4987. else if(oldCount == count[i] && hero->stacksCount() == 1 && hero->needsLastStack())
  4988. {
  4989. finish();
  4990. COMPLAIN_RET("Cannot sacrifice last creature!");
  4991. }
  4992. int crid = hero->getStack(slot[i]).type->getId();
  4993. changeStackCount(StackLocation(hero, slot[i]), -(TQuantity)count[i]);
  4994. int dump, exp;
  4995. market->getOffer(crid, 0, dump, exp, EMarketMode::CREATURE_EXP);
  4996. exp *= count[i];
  4997. expSum += exp;
  4998. }
  4999. finish();
  5000. return true;
  5001. }
  5002. bool CGameHandler::sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactPosition> & slot)
  5003. {
  5004. if (!hero)
  5005. COMPLAIN_RET("You need hero to sacrifice artifact!");
  5006. int expSum = 0;
  5007. auto finish = [this, &hero, &expSum]()
  5008. {
  5009. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  5010. };
  5011. for(int i = 0; i < slot.size(); ++i)
  5012. {
  5013. ArtifactLocation al(hero, slot[i]);
  5014. const CArtifactInstance * a = al.getArt();
  5015. if(!a)
  5016. {
  5017. finish();
  5018. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  5019. }
  5020. const CArtifactInstance * art = hero->getArt(slot[i]);
  5021. if(!art)
  5022. {
  5023. finish();
  5024. COMPLAIN_RET("No artifact at position to sacrifice!");
  5025. }
  5026. si32 typId = art->artType->getId();
  5027. int dmp, expToGive;
  5028. m->getOffer(typId, 0, dmp, expToGive, EMarketMode::ARTIFACT_EXP);
  5029. expSum += expToGive;
  5030. removeArtifact(al);
  5031. }
  5032. finish();
  5033. return true;
  5034. }
  5035. void CGameHandler::makeStackDoNothing(const CStack * next)
  5036. {
  5037. BattleAction doNothing;
  5038. doNothing.actionType = EActionType::NO_ACTION;
  5039. doNothing.side = next->unitSide();
  5040. doNothing.stackNumber = next->unitId();
  5041. makeAutomaticAction(next, doNothing);
  5042. }
  5043. bool CGameHandler::insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count)
  5044. {
  5045. if (sl.army->hasStackAtSlot(sl.slot))
  5046. COMPLAIN_RET("Slot is already taken!");
  5047. if (!sl.slot.validSlot())
  5048. COMPLAIN_RET("Cannot insert stack to that slot!");
  5049. InsertNewStack ins;
  5050. ins.army = sl.army->id;
  5051. ins.slot = sl.slot;
  5052. ins.type = c->getId();
  5053. ins.count = count;
  5054. sendAndApply(&ins);
  5055. return true;
  5056. }
  5057. bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval)
  5058. {
  5059. if (!sl.army->hasStackAtSlot(sl.slot))
  5060. COMPLAIN_RET("Cannot find a stack to erase");
  5061. if (sl.army->stacksCount() == 1 //from the last stack
  5062. && sl.army->needsLastStack() //that must be left
  5063. && !forceRemoval) //ignore above conditions if we are forcing removal
  5064. {
  5065. COMPLAIN_RET("Cannot erase the last stack!");
  5066. }
  5067. EraseStack es;
  5068. es.army = sl.army->id;
  5069. es.slot = sl.slot;
  5070. sendAndApply(&es);
  5071. return true;
  5072. }
  5073. bool CGameHandler::changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue)
  5074. {
  5075. TQuantity currentCount = sl.army->getStackCount(sl.slot);
  5076. if ((absoluteValue && count < 0)
  5077. || (!absoluteValue && -count > currentCount))
  5078. {
  5079. COMPLAIN_RET("Cannot take more stacks than present!");
  5080. }
  5081. if ((currentCount == -count && !absoluteValue)
  5082. || (!count && absoluteValue))
  5083. {
  5084. eraseStack(sl);
  5085. }
  5086. else
  5087. {
  5088. ChangeStackCount csc;
  5089. csc.army = sl.army->id;
  5090. csc.slot = sl.slot;
  5091. csc.count = count;
  5092. csc.absoluteValue = absoluteValue;
  5093. sendAndApply(&csc);
  5094. }
  5095. return true;
  5096. }
  5097. bool CGameHandler::addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count)
  5098. {
  5099. const CCreature *slotC = sl.army->getCreature(sl.slot);
  5100. if (!slotC) //slot is empty
  5101. insertNewStack(sl, c, count);
  5102. else if (c == slotC)
  5103. changeStackCount(sl, count);
  5104. else
  5105. {
  5106. COMPLAIN_RET("Cannot add " + c->getNamePluralTranslated() + " to slot " + boost::lexical_cast<std::string>(sl.slot) + "!");
  5107. }
  5108. return true;
  5109. }
  5110. void CGameHandler::tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging)
  5111. {
  5112. if (removeObjWhenFinished)
  5113. removeAfterVisit(src);
  5114. if (!src->canBeMergedWith(*dst, allowMerging))
  5115. {
  5116. if (allowMerging) //do that, add all matching creatures.
  5117. {
  5118. bool cont = true;
  5119. while (cont)
  5120. {
  5121. for (auto i = src->stacks.begin(); i != src->stacks.end(); i++)//while there are unmoved creatures
  5122. {
  5123. SlotID pos = dst->getSlotFor(i->second->type);
  5124. if (pos.validSlot())
  5125. {
  5126. moveStack(StackLocation(src, i->first), StackLocation(dst, pos));
  5127. cont = true;
  5128. break; //or iterator crashes
  5129. }
  5130. cont = false;
  5131. }
  5132. }
  5133. }
  5134. showGarrisonDialog(src->id, dst->id, true); //show garrison window and optionally remove ourselves from map when player ends
  5135. }
  5136. else //merge
  5137. {
  5138. moveArmy(src, dst, allowMerging);
  5139. }
  5140. }
  5141. bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count)
  5142. {
  5143. if (!src.army->hasStackAtSlot(src.slot))
  5144. COMPLAIN_RET("No stack to move!");
  5145. if (dst.army->hasStackAtSlot(dst.slot) && dst.army->getCreature(dst.slot) != src.army->getCreature(src.slot))
  5146. COMPLAIN_RET("Cannot move: stack of different type at destination pos!");
  5147. if (!dst.slot.validSlot())
  5148. COMPLAIN_RET("Cannot move stack to that slot!");
  5149. if (count == -1)
  5150. {
  5151. count = src.army->getStackCount(src.slot);
  5152. }
  5153. if (src.army != dst.army //moving away
  5154. && count == src.army->getStackCount(src.slot) //all creatures
  5155. && src.army->stacksCount() == 1 //from the last stack
  5156. && src.army->needsLastStack()) //that must be left
  5157. {
  5158. COMPLAIN_RET("Cannot move away the last creature!");
  5159. }
  5160. RebalanceStacks rs;
  5161. rs.srcArmy = src.army->id;
  5162. rs.dstArmy = dst.army->id;
  5163. rs.srcSlot = src.slot;
  5164. rs.dstSlot = dst.slot;
  5165. rs.count = count;
  5166. sendAndApply(&rs);
  5167. return true;
  5168. }
  5169. void CGameHandler::castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos)
  5170. {
  5171. const CSpell * s = spellID.toSpell();
  5172. if(!s)
  5173. return;
  5174. AdventureSpellCastParameters p;
  5175. p.caster = caster;
  5176. p.pos = pos;
  5177. s->adventureCast(spellEnv, p);
  5178. }
  5179. bool CGameHandler::swapStacks(const StackLocation & sl1, const StackLocation & sl2)
  5180. {
  5181. if(!sl1.army->hasStackAtSlot(sl1.slot))
  5182. {
  5183. return moveStack(sl2, sl1);
  5184. }
  5185. else if(!sl2.army->hasStackAtSlot(sl2.slot))
  5186. {
  5187. return moveStack(sl1, sl2);
  5188. }
  5189. else
  5190. {
  5191. SwapStacks ss;
  5192. ss.srcArmy = sl1.army->id;
  5193. ss.dstArmy = sl2.army->id;
  5194. ss.srcSlot = sl1.slot;
  5195. ss.dstSlot = sl2.slot;
  5196. sendAndApply(&ss);
  5197. return true;
  5198. }
  5199. }
  5200. void CGameHandler::runBattle()
  5201. {
  5202. boost::unique_lock lock(battleActionMutex);
  5203. setBattle(gs->curB);
  5204. assert(gs->curB);
  5205. //TODO: pre-tactic stuff, call scripts etc.
  5206. turnTimerHandler.onBattleStart(gs->players[gs->curB->getSidePlayer(BattleSide::ATTACKER)]);
  5207. turnTimerHandler.onBattleStart(gs->players[gs->curB->getSidePlayer(BattleSide::DEFENDER)]);
  5208. //Moat should be initialized here, because only here we can use spellcasting
  5209. if (gs->curB->town && gs->curB->town->fortLevel() >= CGTownInstance::CITADEL)
  5210. {
  5211. const auto * h = gs->curB->battleGetFightingHero(BattleSide::DEFENDER);
  5212. const auto * actualCaster = h ? static_cast<const spells::Caster*>(h) : nullptr;
  5213. auto moatCaster = spells::SilentCaster(gs->curB->getSidePlayer(BattleSide::DEFENDER), actualCaster);
  5214. auto cast = spells::BattleCast(gs->curB, &moatCaster, spells::Mode::PASSIVE, gs->curB->town->town->moatAbility.toSpell());
  5215. auto target = spells::Target();
  5216. cast.cast(spellEnv, target);
  5217. }
  5218. //tactic round
  5219. {
  5220. while ((lobby->state != EServerState::SHUTDOWN) && gs->curB->tacticDistance && !battleResult.get())
  5221. {
  5222. auto unlockGuard = vstd::makeUnlockGuard(battleActionMutex);
  5223. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  5224. }
  5225. }
  5226. //initial stacks appearance triggers, e.g. built-in bonus spells
  5227. auto initialStacks = gs->curB->stacks; //use temporary variable to outclude summoned stacks added to gs->curB->stacks from processing
  5228. for (CStack * stack : initialStacks)
  5229. {
  5230. if (stack->hasBonusOfType(BonusType::SUMMON_GUARDIANS))
  5231. {
  5232. std::shared_ptr<const Bonus> summonInfo = stack->getBonus(Selector::type()(BonusType::SUMMON_GUARDIANS));
  5233. auto accessibility = getAccesibility();
  5234. CreatureID creatureData = CreatureID(summonInfo->subtype);
  5235. std::vector<BattleHex> targetHexes;
  5236. const bool targetIsBig = stack->unitType()->isDoubleWide(); //target = creature to guard
  5237. const bool guardianIsBig = creatureData.toCreature()->isDoubleWide();
  5238. /*Chosen idea for two hex units was to cover all possible surrounding hexes of target unit with as small number of stacks as possible.
  5239. For one-hex targets there are four guardians - front, back and one per side (up + down).
  5240. Two-hex targets are wider and the difference is there are two guardians per side to cover 3 hexes + extra hex in the front
  5241. Additionally, there are special cases for starting positions etc., where guardians would be outside of battlefield if spawned normally*/
  5242. if (!guardianIsBig)
  5243. targetHexes = stack->getSurroundingHexes();
  5244. else
  5245. summonGuardiansHelper(targetHexes, stack->getPosition(), stack->unitSide(), targetIsBig);
  5246. for(auto hex : targetHexes)
  5247. {
  5248. if(accessibility.accessible(hex, guardianIsBig, stack->unitSide())) //without this multiple creatures can occupy one hex
  5249. {
  5250. battle::UnitInfo info;
  5251. info.id = gs->curB->battleNextUnitId();
  5252. info.count = std::max(1, (int)(stack->getCount() * 0.01 * summonInfo->val));
  5253. info.type = creatureData;
  5254. info.side = stack->unitSide();
  5255. info.position = hex;
  5256. info.summoned = true;
  5257. BattleUnitsChanged pack;
  5258. pack.changedStacks.emplace_back(info.id, UnitChanges::EOperation::ADD);
  5259. info.save(pack.changedStacks.back().data);
  5260. sendAndApply(&pack);
  5261. }
  5262. }
  5263. }
  5264. stackEnchantedTrigger(stack);
  5265. }
  5266. //spells opening battle
  5267. for (int i = 0; i < 2; ++i)
  5268. {
  5269. auto h = gs->curB->battleGetFightingHero(i);
  5270. if (h)
  5271. {
  5272. TConstBonusListPtr bl = h->getBonuses(Selector::type()(BonusType::OPENING_BATTLE_SPELL));
  5273. for (auto b : *bl)
  5274. {
  5275. spells::BonusCaster caster(h, b);
  5276. const CSpell * spell = SpellID(b->subtype).toSpell();
  5277. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  5278. parameters.setSpellLevel(3);
  5279. parameters.setEffectDuration(b->val);
  5280. parameters.massive = true;
  5281. parameters.castIfPossible(spellEnv, spells::Target());
  5282. }
  5283. }
  5284. }
  5285. // it is possible that due to opening spells one side was eliminated -> check for end of battle
  5286. checkBattleStateChanges();
  5287. bool firstRound = true;//FIXME: why first round is -1?
  5288. //main loop
  5289. while ((lobby->state != EServerState::SHUTDOWN) && !battleResult.get()) //till the end of the battle ;]
  5290. {
  5291. BattleNextRound bnr;
  5292. bnr.round = gs->curB->round + 1;
  5293. logGlobal->debug("Round %d", bnr.round);
  5294. sendAndApply(&bnr);
  5295. auto obstacles = gs->curB->obstacles; //we copy container, because we're going to modify it
  5296. for (auto &obstPtr : obstacles)
  5297. {
  5298. if (const SpellCreatedObstacle *sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get()))
  5299. if (sco->turnsRemaining == 0)
  5300. removeObstacle(*obstPtr);
  5301. }
  5302. const BattleInfo & curB = *gs->curB;
  5303. for(auto stack : curB.stacks)
  5304. {
  5305. if(stack->alive() && !firstRound)
  5306. stackEnchantedTrigger(stack);
  5307. }
  5308. //stack loop
  5309. auto getNextStack = [this]() -> const CStack *
  5310. {
  5311. if(battleResult.get())
  5312. return nullptr;
  5313. std::vector<battle::Units> q;
  5314. gs->curB->battleGetTurnOrder(q, 1, 0, -1); //todo: get rid of "turn -1"
  5315. if(!q.empty())
  5316. {
  5317. if(!q.front().empty())
  5318. {
  5319. auto next = q.front().front();
  5320. const auto stack = dynamic_cast<const CStack *>(next);
  5321. // regeneration takes place before everything else but only during first turn attempt in each round
  5322. // also works under blind and similar effects
  5323. if(stack && stack->alive() && !stack->waiting)
  5324. {
  5325. BattleTriggerEffect bte;
  5326. bte.stackID = stack->unitId();
  5327. bte.effect = vstd::to_underlying(BonusType::HP_REGENERATION);
  5328. const int32_t lostHealth = stack->getMaxHealth() - stack->getFirstHPleft();
  5329. if(stack->hasBonusOfType(BonusType::HP_REGENERATION))
  5330. bte.val = std::min(lostHealth, stack->valOfBonuses(BonusType::HP_REGENERATION));
  5331. if(bte.val) // anything to heal
  5332. sendAndApply(&bte);
  5333. }
  5334. if(next->willMove())
  5335. return stack;
  5336. }
  5337. }
  5338. return nullptr;
  5339. };
  5340. const CStack * next = nullptr;
  5341. while((lobby->state != EServerState::SHUTDOWN) && (next = getNextStack()))
  5342. {
  5343. turnTimerHandler.onBattleNextStack(gs->players[next->getOwner()]);
  5344. BattleUnitsChanged removeGhosts;
  5345. for(auto stack : curB.stacks)
  5346. {
  5347. if(stack->ghostPending)
  5348. removeGhosts.changedStacks.emplace_back(stack->unitId(), UnitChanges::EOperation::REMOVE);
  5349. }
  5350. if(!removeGhosts.changedStacks.empty())
  5351. sendAndApply(&removeGhosts);
  5352. // check for bad morale => freeze
  5353. int nextStackMorale = next->moraleVal();
  5354. if(!next->hadMorale && !next->waited() && nextStackMorale < 0)
  5355. {
  5356. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_MORALE_DICE);
  5357. size_t diceIndex = std::min<size_t>(diceSize.size()-1, -nextStackMorale);
  5358. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  5359. {
  5360. //unit loses its turn - empty freeze action
  5361. BattleAction ba;
  5362. ba.actionType = EActionType::BAD_MORALE;
  5363. ba.side = next->unitSide();
  5364. ba.stackNumber = next->unitId();
  5365. makeAutomaticAction(next, ba);
  5366. continue;
  5367. }
  5368. }
  5369. if (next->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE)) //while in berserk
  5370. {
  5371. logGlobal->trace("Handle Berserk effect");
  5372. std::pair<const battle::Unit *, BattleHex> attackInfo = curB.getNearestStack(next);
  5373. if (attackInfo.first != nullptr)
  5374. {
  5375. BattleAction attack;
  5376. attack.actionType = EActionType::WALK_AND_ATTACK;
  5377. attack.side = next->unitSide();
  5378. attack.stackNumber = next->unitId();
  5379. attack.aimToHex(attackInfo.second);
  5380. attack.aimToUnit(attackInfo.first);
  5381. makeAutomaticAction(next, attack);
  5382. logGlobal->trace("Attacked nearest target %s", attackInfo.first->getDescription());
  5383. }
  5384. else
  5385. {
  5386. makeStackDoNothing(next);
  5387. logGlobal->trace("No target found");
  5388. }
  5389. continue;
  5390. }
  5391. const CGHeroInstance * curOwner = battleGetOwnerHero(next);
  5392. const int stackCreatureId = next->unitType()->getId();
  5393. if ((stackCreatureId == CreatureID::ARROW_TOWERS || stackCreatureId == CreatureID::BALLISTA)
  5394. && (!curOwner || getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, stackCreatureId)))
  5395. {
  5396. BattleAction attack;
  5397. attack.actionType = EActionType::SHOOT;
  5398. attack.side = next->unitSide();
  5399. attack.stackNumber = next->unitId();
  5400. //TODO: select target by priority
  5401. const battle::Unit * target = nullptr;
  5402. for(auto & elem : gs->curB->stacks)
  5403. {
  5404. if(elem->unitType()->getId() != CreatureID::CATAPULT
  5405. && elem->unitOwner() != next->unitOwner()
  5406. && elem->isValidTarget()
  5407. && gs->curB->battleCanShoot(next, elem->getPosition()))
  5408. {
  5409. target = elem;
  5410. break;
  5411. }
  5412. }
  5413. if(target == nullptr)
  5414. {
  5415. makeStackDoNothing(next);
  5416. }
  5417. else
  5418. {
  5419. attack.aimToUnit(target);
  5420. makeAutomaticAction(next, attack);
  5421. }
  5422. continue;
  5423. }
  5424. if (next->unitType()->getId() == CreatureID::CATAPULT)
  5425. {
  5426. const auto & attackableBattleHexes = curB.getAttackableBattleHexes();
  5427. if (attackableBattleHexes.empty())
  5428. {
  5429. makeStackDoNothing(next);
  5430. continue;
  5431. }
  5432. if (!curOwner || getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::CATAPULT))
  5433. {
  5434. BattleAction attack;
  5435. attack.actionType = EActionType::CATAPULT;
  5436. attack.side = next->unitSide();
  5437. attack.stackNumber = next->unitId();
  5438. makeAutomaticAction(next, attack);
  5439. continue;
  5440. }
  5441. }
  5442. if (next->unitType()->getId() == CreatureID::FIRST_AID_TENT)
  5443. {
  5444. TStacks possibleStacks = battleGetStacksIf([=](const CStack * s)
  5445. {
  5446. return s->unitOwner() == next->unitOwner() && s->canBeHealed();
  5447. });
  5448. if (!possibleStacks.size())
  5449. {
  5450. makeStackDoNothing(next);
  5451. continue;
  5452. }
  5453. if (!curOwner || getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::FIRST_AID_TENT))
  5454. {
  5455. RandomGeneratorUtil::randomShuffle(possibleStacks, getRandomGenerator());
  5456. const CStack * toBeHealed = possibleStacks.front();
  5457. BattleAction heal;
  5458. heal.actionType = EActionType::STACK_HEAL;
  5459. heal.aimToUnit(toBeHealed);
  5460. heal.side = next->unitSide();
  5461. heal.stackNumber = next->unitId();
  5462. makeAutomaticAction(next, heal);
  5463. continue;
  5464. }
  5465. }
  5466. int numberOfAsks = 1;
  5467. bool breakOuter = false;
  5468. do
  5469. {//ask interface and wait for answer
  5470. if (!battleResult.get())
  5471. {
  5472. stackTurnTrigger(next); //various effects
  5473. if(next->fear)
  5474. {
  5475. makeStackDoNothing(next); //end immediately if stack was affected by fear
  5476. }
  5477. else
  5478. {
  5479. logGlobal->trace("Activating %s", next->nodeName());
  5480. auto nextId = next->unitId();
  5481. BattleSetActiveStack sas;
  5482. sas.stack = nextId;
  5483. sendAndApply(&sas);
  5484. auto actionWasMade = [&]() -> bool
  5485. {
  5486. if (battleMadeAction.data)//active stack has made its action
  5487. return true;
  5488. if (battleResult.get())// battle is finished
  5489. return true;
  5490. if (next == nullptr)//active stack was been removed
  5491. return true;
  5492. return !next->alive();//active stack is dead
  5493. };
  5494. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  5495. battleMadeAction.data = false;
  5496. while ((lobby->state != EServerState::SHUTDOWN) && !actionWasMade())
  5497. {
  5498. {
  5499. auto unlockGuard = vstd::makeUnlockGuard(battleActionMutex);
  5500. battleMadeAction.cond.wait(lock);
  5501. }
  5502. if (battleGetStackByID(nextId, false) != next)
  5503. next = nullptr; //it may be removed, while we wait
  5504. }
  5505. }
  5506. }
  5507. if (battleResult.get()) //don't touch it, battle could be finished while waiting got action
  5508. {
  5509. breakOuter = true;
  5510. break;
  5511. }
  5512. //we're after action, all results applied
  5513. checkBattleStateChanges(); //check if this action ended the battle
  5514. if(next != nullptr)
  5515. {
  5516. //check for good morale
  5517. nextStackMorale = next->moraleVal();
  5518. if( !battleResult.get()
  5519. && !next->hadMorale
  5520. && !next->defending
  5521. && !next->waited()
  5522. && !next->fear
  5523. && next->alive()
  5524. && nextStackMorale > 0)
  5525. {
  5526. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_MORALE_DICE);
  5527. size_t diceIndex = std::min<size_t>(diceSize.size()-1, nextStackMorale);
  5528. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  5529. {
  5530. BattleTriggerEffect bte;
  5531. bte.stackID = next->unitId();
  5532. bte.effect = vstd::to_underlying(BonusType::MORALE);
  5533. bte.val = 1;
  5534. bte.additionalInfo = 0;
  5535. sendAndApply(&bte); //play animation
  5536. ++numberOfAsks; //move this stack once more
  5537. }
  5538. }
  5539. }
  5540. --numberOfAsks;
  5541. } while (numberOfAsks > 0);
  5542. if (breakOuter)
  5543. {
  5544. break;
  5545. }
  5546. }
  5547. firstRound = false;
  5548. }
  5549. if (lobby->state != EServerState::SHUTDOWN)
  5550. endBattle(gs->curB->tile, gs->curB->battleGetFightingHero(0), gs->curB->battleGetFightingHero(1));
  5551. }
  5552. bool CGameHandler::makeAutomaticAction(const CStack *stack, BattleAction &ba)
  5553. {
  5554. boost::unique_lock lock(battleActionMutex);
  5555. BattleSetActiveStack bsa;
  5556. bsa.stack = stack->unitId();
  5557. bsa.askPlayerInterface = false;
  5558. sendAndApply(&bsa);
  5559. bool ret = makeBattleAction(ba);
  5560. checkBattleStateChanges();
  5561. return ret;
  5562. }
  5563. bool CGameHandler::giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos)
  5564. {
  5565. assert(a->artType);
  5566. ArtifactLocation al(h, ArtifactPosition::PRE_FIRST);
  5567. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  5568. {
  5569. al.slot = ArtifactUtils::getArtAnyPosition(h, a->getTypeId());
  5570. }
  5571. else if(ArtifactUtils::isSlotBackpack(pos))
  5572. {
  5573. al.slot = ArtifactUtils::getArtBackpackPosition(h, a->getTypeId());
  5574. }
  5575. else
  5576. {
  5577. al.slot = pos;
  5578. }
  5579. if(a->canBePutAt(al))
  5580. putArtifact(al, a);
  5581. else
  5582. return false;
  5583. return true;
  5584. }
  5585. void CGameHandler::putArtifact(const ArtifactLocation &al, const CArtifactInstance *a)
  5586. {
  5587. PutArtifact pa;
  5588. pa.art = a;
  5589. pa.al = al;
  5590. sendAndApply(&pa);
  5591. }
  5592. bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos)
  5593. {
  5594. assert(artType);
  5595. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  5596. {
  5597. if(!artType->canBePutAt(h, ArtifactUtils::getArtAnyPosition(h, artType->getId())))
  5598. COMPLAIN_RET("Cannot put artifact in that slot!");
  5599. }
  5600. else if(ArtifactUtils::isSlotBackpack(pos))
  5601. {
  5602. if(!artType->canBePutAt(h, ArtifactUtils::getArtBackpackPosition(h, artType->getId())))
  5603. COMPLAIN_RET("Cannot put artifact in that slot!");
  5604. }
  5605. else
  5606. {
  5607. COMPLAIN_RET_FALSE_IF(!artType->canBePutAt(h, pos, false), "Cannot put artifact in that slot!");
  5608. }
  5609. auto * newArtInst = new CArtifactInstance();
  5610. newArtInst->artType = artType; // *NOT* via settype -> all bonus-related stuff must be done by NewArtifact apply
  5611. NewArtifact na;
  5612. na.art = newArtInst;
  5613. sendAndApply(&na); // -> updates newArtInst!!!
  5614. if(giveHeroArtifact(h, newArtInst, pos))
  5615. return true;
  5616. else
  5617. return false;
  5618. }
  5619. void CGameHandler::setBattleResult(BattleResult::EResult resultType, int victoriusSide)
  5620. {
  5621. boost::unique_lock<boost::mutex> guard(battleResult.mx);
  5622. if (battleResult.data)
  5623. {
  5624. complain((boost::format("The battle result has been already set (to %d, asked to %d)")
  5625. % battleResult.data->result % resultType).str());
  5626. return;
  5627. }
  5628. auto br = new BattleResult();
  5629. br->result = resultType;
  5630. br->winner = victoriusSide; //surrendering side loses
  5631. gs->curB->calculateCasualties(br->casualties);
  5632. battleResult.data = br;
  5633. }
  5634. void CGameHandler::spawnWanderingMonsters(CreatureID creatureID)
  5635. {
  5636. std::vector<int3>::iterator tile;
  5637. std::vector<int3> tiles;
  5638. getFreeTiles(tiles);
  5639. ui32 amount = (ui32)tiles.size() / 200; //Chance is 0.5% for each tile
  5640. RandomGeneratorUtil::randomShuffle(tiles, getRandomGenerator());
  5641. logGlobal->trace("Spawning wandering monsters. Found %d free tiles. Creature type: %d", tiles.size(), creatureID.num);
  5642. const CCreature *cre = VLC->creh->objects.at(creatureID);
  5643. for (int i = 0; i < (int)amount; ++i)
  5644. {
  5645. tile = tiles.begin();
  5646. logGlobal->trace("\tSpawning monster at %s", tile->toString());
  5647. {
  5648. auto count = cre->getRandomAmount(std::rand);
  5649. createObject(*tile, Obj::MONSTER, creatureID);
  5650. auto monsterId = getTopObj(*tile)->id;
  5651. setObjProperty(monsterId, ObjProperty::MONSTER_COUNT, count);
  5652. setObjProperty(monsterId, ObjProperty::MONSTER_POWER, (si64)1000*count);
  5653. }
  5654. tiles.erase(tile); //not use it again
  5655. }
  5656. }
  5657. void CGameHandler::removeObstacle(const CObstacleInstance & obstacle)
  5658. {
  5659. BattleObstaclesChanged obsRem;
  5660. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  5661. sendAndApply(&obsRem);
  5662. }
  5663. void CGameHandler::synchronizeArtifactHandlerLists()
  5664. {
  5665. UpdateArtHandlerLists uahl;
  5666. uahl.treasures = VLC->arth->treasures;
  5667. uahl.minors = VLC->arth->minors;
  5668. uahl.majors = VLC->arth->majors;
  5669. uahl.relics = VLC->arth->relics;
  5670. sendAndApply(&uahl);
  5671. }
  5672. bool CGameHandler::isValidObject(const CGObjectInstance *obj) const
  5673. {
  5674. return vstd::contains(gs->map->objects, obj);
  5675. }
  5676. bool CGameHandler::isBlockedByQueries(const CPack *pack, PlayerColor player)
  5677. {
  5678. if (!strcmp(typeid(*pack).name(), typeid(PlayerMessage).name()))
  5679. return false;
  5680. auto query = queries.topQuery(player);
  5681. if (query && query->blocksPack(pack))
  5682. {
  5683. complain(boost::str(boost::format(
  5684. "\r\n| Player \"%s\" has to answer queries before attempting any further actions.\r\n| Top Query: \"%s\"\r\n")
  5685. % boost::to_upper_copy<std::string>(player.getStr())
  5686. % query->toString()
  5687. ));
  5688. return true;
  5689. }
  5690. return false;
  5691. }
  5692. void CGameHandler::removeAfterVisit(const CGObjectInstance *object)
  5693. {
  5694. //If the object is being visited, there must be a matching query
  5695. for (const auto &query : queries.allQueries())
  5696. {
  5697. if (auto someVistQuery = std::dynamic_pointer_cast<CObjectVisitQuery>(query))
  5698. {
  5699. if (someVistQuery->visitedObject == object)
  5700. {
  5701. someVistQuery->removeObjectAfterVisit = true;
  5702. return;
  5703. }
  5704. }
  5705. }
  5706. //If we haven't returned so far, there is no query and no visit, call was wrong
  5707. assert("This function needs to be called during the object visit!");
  5708. }
  5709. void CGameHandler::changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide)
  5710. {
  5711. std::unordered_set<int3> tiles;
  5712. getTilesInRange(tiles, center, radius, player, hide? -1 : 1);
  5713. if (hide)
  5714. {
  5715. std::unordered_set<int3> observedTiles; //do not hide tiles observed by heroes. May lead to disastrous AI problems
  5716. auto p = getPlayerState(player);
  5717. for (auto h : p->heroes)
  5718. {
  5719. getTilesInRange(observedTiles, h->getSightCenter(), h->getSightRadius(), h->tempOwner, -1);
  5720. }
  5721. for (auto t : p->towns)
  5722. {
  5723. getTilesInRange(observedTiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, -1);
  5724. }
  5725. for (auto tile : observedTiles)
  5726. vstd::erase_if_present (tiles, tile);
  5727. }
  5728. changeFogOfWar(tiles, player, hide);
  5729. }
  5730. void CGameHandler::changeFogOfWar(std::unordered_set<int3> &tiles, PlayerColor player, bool hide)
  5731. {
  5732. FoWChange fow;
  5733. fow.tiles = tiles;
  5734. fow.player = player;
  5735. fow.mode = hide? 0 : 1;
  5736. sendAndApply(&fow);
  5737. }
  5738. bool CGameHandler::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero)
  5739. {
  5740. if (auto topQuery = queries.topQuery(hero->getOwner()))
  5741. if (auto visit = std::dynamic_pointer_cast<const CObjectVisitQuery>(topQuery))
  5742. return !(visit->visitedObject == obj && visit->visitingHero == hero);
  5743. return true;
  5744. }
  5745. void CGameHandler::setObjProperty(ObjectInstanceID objid, int prop, si64 val)
  5746. {
  5747. SetObjectProperty sob;
  5748. sob.id = objid;
  5749. sob.what = prop;
  5750. sob.val = static_cast<ui32>(val);
  5751. sendAndApply(&sob);
  5752. }
  5753. void CGameHandler::showInfoDialog(InfoWindow * iw)
  5754. {
  5755. sendAndApply(iw);
  5756. }
  5757. void CGameHandler::showInfoDialog(const std::string & msg, PlayerColor player)
  5758. {
  5759. InfoWindow iw;
  5760. iw.player = player;
  5761. iw.text.appendRawString(msg);
  5762. showInfoDialog(&iw);
  5763. }
  5764. CasualtiesAfterBattle::CasualtiesAfterBattle(const SideInBattle & battleSide, const BattleInfo * bat):
  5765. army(battleSide.armyObject)
  5766. {
  5767. heroWithDeadCommander = ObjectInstanceID();
  5768. PlayerColor color = battleSide.color;
  5769. for(CStack * st : bat->stacks)
  5770. {
  5771. if(st->summoned) //don't take into account temporary summoned stacks
  5772. continue;
  5773. if(st->unitOwner() != color) //remove only our stacks
  5774. continue;
  5775. logGlobal->debug("Calculating casualties for %s", st->nodeName());
  5776. st->health.takeResurrected();
  5777. if(st->unitSlot() == SlotID::ARROW_TOWERS_SLOT)
  5778. {
  5779. logGlobal->debug("Ignored arrow towers stack.");
  5780. }
  5781. else if(st->unitSlot() == SlotID::WAR_MACHINES_SLOT)
  5782. {
  5783. auto warMachine = st->unitType()->warMachine;
  5784. if(warMachine == ArtifactID::NONE)
  5785. {
  5786. logGlobal->error("Invalid creature in war machine virtual slot. Stack: %s", st->nodeName());
  5787. }
  5788. //catapult artifact remain even if "creature" killed in siege
  5789. else if(warMachine != ArtifactID::CATAPULT && st->getCount() <= 0)
  5790. {
  5791. logGlobal->debug("War machine has been destroyed");
  5792. auto hero = dynamic_ptr_cast<CGHeroInstance> (army);
  5793. if (hero)
  5794. removedWarMachines.push_back (ArtifactLocation(hero, hero->getArtPos(warMachine, true)));
  5795. else
  5796. logGlobal->error("War machine in army without hero");
  5797. }
  5798. }
  5799. else if(st->unitSlot() == SlotID::SUMMONED_SLOT_PLACEHOLDER)
  5800. {
  5801. if(st->alive() && st->getCount() > 0)
  5802. {
  5803. logGlobal->debug("Permanently summoned %d units.", st->getCount());
  5804. const CreatureID summonedType = st->creatureId();
  5805. summoned[summonedType] += st->getCount();
  5806. }
  5807. }
  5808. else if(st->unitSlot() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  5809. {
  5810. if (nullptr == st->base)
  5811. {
  5812. logGlobal->error("Stack with no base in commander slot. Stack: %s", st->nodeName());
  5813. }
  5814. else
  5815. {
  5816. auto c = dynamic_cast <const CCommanderInstance *>(st->base);
  5817. if(c)
  5818. {
  5819. auto h = dynamic_cast <const CGHeroInstance *>(army);
  5820. if(h && h->commander == c && (st->getCount() == 0 || !st->alive()))
  5821. {
  5822. logGlobal->debug("Commander is dead.");
  5823. heroWithDeadCommander = army->id; //TODO: unify commander handling
  5824. }
  5825. }
  5826. else
  5827. logGlobal->error("Stack with invalid instance in commander slot. Stack: %s", st->nodeName());
  5828. }
  5829. }
  5830. else if(st->base && !army->slotEmpty(st->unitSlot()))
  5831. {
  5832. logGlobal->debug("Count: %d; base count: %d", st->getCount(), army->getStackCount(st->unitSlot()));
  5833. if(st->getCount() == 0 || !st->alive())
  5834. {
  5835. logGlobal->debug("Stack has been destroyed.");
  5836. StackLocation sl(army, st->unitSlot());
  5837. newStackCounts.push_back(TStackAndItsNewCount(sl, 0));
  5838. }
  5839. else if(st->getCount() < army->getStackCount(st->unitSlot()))
  5840. {
  5841. logGlobal->debug("Stack lost %d units.", army->getStackCount(st->unitSlot()) - st->getCount());
  5842. StackLocation sl(army, st->unitSlot());
  5843. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  5844. }
  5845. else if(st->getCount() > army->getStackCount(st->unitSlot()))
  5846. {
  5847. logGlobal->debug("Stack gained %d units.", st->getCount() - army->getStackCount(st->unitSlot()));
  5848. StackLocation sl(army, st->unitSlot());
  5849. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  5850. }
  5851. }
  5852. else
  5853. {
  5854. logGlobal->warn("Unable to process stack: %s", st->nodeName());
  5855. }
  5856. }
  5857. }
  5858. void CasualtiesAfterBattle::updateArmy(CGameHandler *gh)
  5859. {
  5860. for (TStackAndItsNewCount &ncount : newStackCounts)
  5861. {
  5862. if (ncount.second > 0)
  5863. gh->changeStackCount(ncount.first, ncount.second, true);
  5864. else
  5865. gh->eraseStack(ncount.first, true);
  5866. }
  5867. for (auto summoned_iter : summoned)
  5868. {
  5869. SlotID slot = army->getSlotFor(summoned_iter.first);
  5870. if (slot.validSlot())
  5871. {
  5872. StackLocation location(army, slot);
  5873. gh->addToSlot(location, summoned_iter.first.toCreature(), summoned_iter.second);
  5874. }
  5875. else
  5876. {
  5877. //even if it will be possible to summon anything permanently it should be checked for free slot
  5878. //necromancy is handled separately
  5879. gh->complain("No free slot to put summoned creature");
  5880. }
  5881. }
  5882. for (auto al : removedWarMachines)
  5883. {
  5884. gh->removeArtifact(al);
  5885. }
  5886. if (heroWithDeadCommander != ObjectInstanceID())
  5887. {
  5888. SetCommanderProperty scp;
  5889. scp.heroid = heroWithDeadCommander;
  5890. scp.which = SetCommanderProperty::ALIVE;
  5891. scp.amount = 0;
  5892. gh->sendAndApply(&scp);
  5893. }
  5894. }
  5895. CGameHandler::FinishingBattleHelper::FinishingBattleHelper(std::shared_ptr<const CBattleQuery> Query, int RemainingBattleQueriesCount)
  5896. {
  5897. assert(Query->result);
  5898. assert(Query->bi);
  5899. auto &result = *Query->result;
  5900. auto &info = *Query->bi;
  5901. winnerHero = result.winner != 0 ? info.sides[1].hero : info.sides[0].hero;
  5902. loserHero = result.winner != 0 ? info.sides[0].hero : info.sides[1].hero;
  5903. victor = info.sides[result.winner].color;
  5904. loser = info.sides[!result.winner].color;
  5905. winnerSide = result.winner;
  5906. remainingBattleQueriesCount = RemainingBattleQueriesCount;
  5907. }
  5908. CGameHandler::FinishingBattleHelper::FinishingBattleHelper()
  5909. {
  5910. winnerHero = loserHero = nullptr;
  5911. winnerSide = 0;
  5912. remainingBattleQueriesCount = 0;
  5913. }
  5914. CRandomGenerator & CGameHandler::getRandomGenerator()
  5915. {
  5916. return CRandomGenerator::getDefault();
  5917. }
  5918. #if SCRIPTING_ENABLED
  5919. scripting::Pool * CGameHandler::getGlobalContextPool() const
  5920. {
  5921. return serverScripts.get();
  5922. }
  5923. scripting::Pool * CGameHandler::getContextPool() const
  5924. {
  5925. return serverScripts.get();
  5926. }
  5927. #endif
  5928. void CGameHandler::createObject(const int3 & visitablePosition, Obj type, int32_t subtype)
  5929. {
  5930. NewObject no;
  5931. no.ID = type;
  5932. no.subID= subtype;
  5933. no.targetPos = visitablePosition;
  5934. sendAndApply(&no);
  5935. }
  5936. void CGameHandler::deserializationFix()
  5937. {
  5938. //FIXME: pointer to GameHandler itself can't be deserialized at the moment since GameHandler is top-level entity in serialization
  5939. // restore any places that requires such pointer manually
  5940. heroPool->gameHandler = this;
  5941. playerMessages->gameHandler = this;
  5942. }