CGameHandler.cpp 149 KB

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