CGameHandler.cpp 178 KB

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