CGameHandler.cpp 221 KB

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