CGameHandler.cpp 207 KB

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