CGameHandler.cpp 202 KB

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