CGameHandler.cpp 188 KB

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