CGameHandler.cpp 165 KB

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