CGameHandler.cpp 146 KB

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