CGameHandler.cpp 156 KB

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