CGameHandler.cpp 187 KB

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