CGameHandler.cpp 148 KB

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