CGameHandler.cpp 127 KB

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