CGameHandler.cpp 109 KB

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