CGameHandler.cpp 192 KB

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