CGameHandler.cpp 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393
  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. //end battle, remove all info, free memory
  445. giveExp(*battleResult.data);
  446. sendAndApply(battleResult.data);
  447. //if one hero has lost we will erase him
  448. if(battleResult.data->winner!=0 && hero1)
  449. {
  450. RemoveObject ro(hero1->id);
  451. sendAndApply(&ro);
  452. }
  453. if(battleResult.data->winner!=1 && hero2)
  454. {
  455. RemoveObject ro(hero2->id);
  456. sendAndApply(&ro);
  457. }
  458. //give exp
  459. if(battleResult.data->exp[0] && hero1)
  460. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  461. if(battleResult.data->exp[1] && hero2)
  462. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  463. if(battleEndCallback && *battleEndCallback)
  464. {
  465. (*battleEndCallback)(battleResult.data);
  466. delete battleEndCallback;
  467. battleEndCallback = 0;
  468. }
  469. sendAndApply(&resultsApplied);
  470. // Necromancy if applicable.
  471. const CGHeroInstance *winnerHero = battleResult.data->winner != 0 ? hero2 : hero1;
  472. if (winnerHero) {
  473. std::pair<ui32, si32> raisedStack = winnerHero->calculateNecromancy(*battleResult.data);
  474. // Give raised units to winner and show dialog, if any were raised.
  475. if (raisedStack.first != -1) {
  476. int slot = winnerHero->army.getSlotFor(raisedStack.first);
  477. if (slot != -1) {
  478. SetGarrisons sg;
  479. sg.garrs[winnerHero->id] = winnerHero->army;
  480. if (vstd::contains(winnerHero->army.slots, slot)) // Add to existing stack.
  481. sg.garrs[winnerHero->id].slots[slot].second += raisedStack.second;
  482. else // Create a new stack.
  483. sg.garrs[winnerHero->id].slots[slot] = raisedStack;
  484. winnerHero->showNecromancyDialog(raisedStack);
  485. sendAndApply(&sg);
  486. }
  487. }
  488. }
  489. delete battleResult.data;
  490. }
  491. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, const CStack *def)
  492. {
  493. bsa.killedAmount = bsa.damageAmount / def->MaxHealth();
  494. unsigned damageFirst = bsa.damageAmount % def->MaxHealth();
  495. if( def->firstHPleft <= damageFirst )
  496. {
  497. bsa.killedAmount++;
  498. bsa.newHP = def->firstHPleft + def->MaxHealth() - damageFirst;
  499. }
  500. else
  501. {
  502. bsa.newHP = def->firstHPleft - damageFirst;
  503. }
  504. if(def->amount <= bsa.killedAmount) //stack killed
  505. {
  506. bsa.newAmount = 0;
  507. bsa.flags |= 1;
  508. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  509. }
  510. else
  511. {
  512. bsa.newAmount = def->amount - bsa.killedAmount;
  513. }
  514. }
  515. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance)
  516. {
  517. bat.bsa.clear();
  518. bat.stackAttacking = att->ID;
  519. std::set<BattleStackAttacked>::iterator i = bat.bsa.insert(BattleStackAttacked()).first;
  520. #ifdef __GNUC__
  521. BattleStackAttacked *bsa = (BattleStackAttacked *)&*i;
  522. #else
  523. BattleStackAttacked *bsa = &*i;
  524. #endif
  525. bsa->stackAttacked = def->ID;
  526. bsa->attackerID = att->ID;
  527. bsa->damageAmount = BattleInfo::calculateDmg(att, def, gs->battleGetOwner(att->ID), gs->battleGetOwner(def->ID), bat.shot(), distance);//counting dealt damage
  528. if(att->Luck() > 0 && rand()%24 < att->Luck())
  529. {
  530. bsa->damageAmount *= 2;
  531. bat.flags |= 4;
  532. }
  533. prepareAttacked(*bsa, def);
  534. }
  535. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  536. {
  537. srand(time(NULL));
  538. CPack *pack = NULL;
  539. try
  540. {
  541. while(!end2)
  542. {
  543. {
  544. boost::unique_lock<boost::mutex> lock(*c.rmx);
  545. c >> pack; //get the package
  546. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  547. }
  548. int packType = typeList.getTypeID(pack); //get the id of type
  549. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  550. if(apply)
  551. {
  552. bool result = apply->applyOnGH(this,&c,pack);
  553. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  554. //send confirmation that we've applied the package
  555. if(pack->type != 6000) //WORKAROUND - not confirm query replies TODO: reconsider
  556. {
  557. PackageApplied applied;
  558. applied.result = result;
  559. applied.packType = packType;
  560. {
  561. boost::unique_lock<boost::mutex> lock(*c.wmx);
  562. c << &applied;
  563. }
  564. }
  565. }
  566. else
  567. {
  568. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  569. }
  570. delete pack;
  571. pack = NULL;
  572. }
  573. }
  574. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  575. {
  576. tlog1 << e.what() << std::endl;
  577. end2 = true;
  578. }
  579. HANDLE_EXCEPTION(end2 = true);
  580. handleConEnd:
  581. tlog1 << "Ended handling connection\n";
  582. }
  583. int CGameHandler::moveStack(int stack, int dest)
  584. {
  585. int ret = 0;
  586. CStack *curStack = gs->curB->getStack(stack),
  587. *stackAtEnd = gs->curB->getStackT(dest);
  588. assert(curStack);
  589. assert(dest < BFIELD_SIZE);
  590. //initing necessary tables
  591. bool accessibility[BFIELD_SIZE];
  592. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  593. for(int b=0; b<BFIELD_SIZE; ++b)
  594. {
  595. accessibility[b] = false;
  596. }
  597. for(int g=0; g<accessible.size(); ++g)
  598. {
  599. accessibility[accessible[g]] = true;
  600. }
  601. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  602. if(!stackAtEnd && curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !accessibility[dest])
  603. {
  604. if(curStack->attackerOwned)
  605. {
  606. if(accessibility[dest+1])
  607. dest+=1;
  608. }
  609. else
  610. {
  611. if(accessibility[dest-1])
  612. dest-=1;
  613. }
  614. }
  615. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  616. return 0;
  617. bool accessibilityWithOccupyable[BFIELD_SIZE];
  618. std::vector<int> accOc = gs->curB->getAccessibility(curStack->ID, true);
  619. for(int b=0; b<BFIELD_SIZE; ++b)
  620. {
  621. accessibilityWithOccupyable[b] = false;
  622. }
  623. for(int g=0; g<accOc.size(); ++g)
  624. {
  625. accessibilityWithOccupyable[accOc[g]] = true;
  626. }
  627. //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
  628. // return false;
  629. 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);
  630. ret = path.second;
  631. if(curStack->hasFeatureOfType(StackFeature::FLYING))
  632. {
  633. if(path.second <= curStack->Speed() && path.first.size() > 0)
  634. {
  635. //inform clients about move
  636. BattleStackMoved sm;
  637. sm.stack = curStack->ID;
  638. sm.tile = path.first[0];
  639. sm.distance = path.second;
  640. sm.ending = true;
  641. sendAndApply(&sm);
  642. }
  643. }
  644. else //for non-flying creatures
  645. {
  646. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  647. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  648. {
  649. //inform clients about move
  650. BattleStackMoved sm;
  651. sm.stack = curStack->ID;
  652. sm.tile = path.first[v];
  653. sm.distance = path.second;
  654. sm.ending = v==tilesToMove;
  655. sendAndApply(&sm);
  656. }
  657. }
  658. return ret;
  659. }
  660. CGameHandler::CGameHandler(void)
  661. {
  662. QID = 1;
  663. gs = NULL;
  664. IObjectInterface::cb = this;
  665. applier = new CGHApplier;
  666. }
  667. CGameHandler::~CGameHandler(void)
  668. {
  669. delete applier;
  670. applier = NULL;
  671. delete gs;
  672. }
  673. void CGameHandler::init(StartInfo *si, int Seed)
  674. {
  675. Mapa *map = new Mapa(si->mapname);
  676. tlog0 << "Map loaded!" << std::endl;
  677. gs = new CGameState();
  678. tlog0 << "Gamestate created!" << std::endl;
  679. gs->init(si,map,Seed);
  680. tlog0 << "Gamestate initialized!" << std::endl;
  681. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  682. states.addPlayer(i->first);
  683. }
  684. static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  685. {
  686. return *a < *b;
  687. }
  688. void CGameHandler::newTurn()
  689. {
  690. tlog5 << "Turn " << gs->day+1 << std::endl;
  691. NewTurn n;
  692. n.day = gs->day + 1;
  693. n.resetBuilded = true;
  694. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  695. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  696. {
  697. if(i->first == 255) continue;
  698. else if(i->first > PLAYER_LIMIT) assert(0); //illegal player number!
  699. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  700. {
  701. SetAvailableHeroes sah;
  702. sah.player = i->first;
  703. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  704. if(h)
  705. sah.hid1 = h->subID;
  706. else
  707. sah.hid1 = -1;
  708. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  709. if(h)
  710. sah.hid2 = h->subID;
  711. else
  712. sah.hid2 = -1;
  713. sendAndApply(&sah);
  714. }
  715. if(i->first>=PLAYER_LIMIT) continue;
  716. n.res[i->first] = i->second.resources;
  717. // SetResources r;
  718. // r.player = i->first;
  719. // for(int j=0;j<RESOURCE_QUANTITY;j++)
  720. // r.res[j] = i->second.resources[j];
  721. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  722. {
  723. if(h->visitedTown)
  724. giveSpells(h->visitedTown, h);
  725. NewTurn::Hero hth;
  726. hth.id = h->id;
  727. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != TerrainTile::water);
  728. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  729. hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
  730. else
  731. hth.mana = std::max(si32(0), std::max(h->mana, std::min(h->mana + h->manaRegain(), h->manaLimit())) );
  732. n.heroes.insert(hth);
  733. if(gs->day) //not first day
  734. {
  735. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  736. {
  737. case 1: //basic
  738. n.res[i->first][6] += 125;
  739. break;
  740. case 2: //advanced
  741. n.res[i->first][6] += 250;
  742. break;
  743. case 3: //expert
  744. n.res[i->first][6] += 500;
  745. break;
  746. }
  747. for(std::list<HeroBonus>::iterator j = h->bonuses.begin(); j != h->bonuses.end(); j++)
  748. if(j->type == HeroBonus::GENERATE_RESOURCE)
  749. n.res[i->first][j->subtype] += j->val;
  750. }
  751. }
  752. //n.res.push_back(r);
  753. }
  754. for(std::vector<CGTownInstance *>::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  755. {
  756. ui8 player = (*j)->tempOwner;
  757. if(gs->getDate(1)==7) //first day of week
  758. {
  759. SetAvailableCreatures sac;
  760. sac.tid = (**j).id;
  761. sac.creatures = (**j).creatures;
  762. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  763. {
  764. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  765. {
  766. sac.creatures[k].first += (**j).creatureGrowth(k);
  767. if(!gs->getDate(0)) //first day of game: use only basic growths
  768. amin(sac.creatures[k].first, VLC->creh->creatures[(*j)->town->basicCreatures[k]].growth);
  769. }
  770. }
  771. n.cres.push_back(sac);
  772. }
  773. if(gs->day && player < PLAYER_LIMIT)//not the first day and town not neutral
  774. {
  775. ////SetResources r;
  776. //r.player = (**j).tempOwner;
  777. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  778. {
  779. if((**j).town->primaryRes == 127) //we'll give wood and ore
  780. {
  781. n.res[player][0] += 1;
  782. n.res[player][2] += 1;
  783. }
  784. else
  785. {
  786. n.res[player][(**j).town->primaryRes] += 1;
  787. }
  788. }
  789. n.res[player][6] += (**j).dailyIncome();
  790. }
  791. }
  792. sendAndApply(&n);
  793. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  794. handleTimeEvents();
  795. //call objects
  796. for(size_t i = 0; i<gs->map->objects.size(); i++)
  797. if(gs->map->objects[i])
  798. gs->map->objects[i]->newTurn();
  799. }
  800. void CGameHandler::run(bool resume)
  801. {
  802. BOOST_FOREACH(CConnection *cc, conns)
  803. {//init conn.
  804. ui8 quantity, pom;
  805. //ui32 seed;
  806. if(!resume)
  807. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  808. (*cc) >> quantity; //how many players will be handled at that client
  809. for(int i=0;i<quantity;i++)
  810. {
  811. (*cc) >> pom; //read player color
  812. {
  813. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  814. connections[pom] = cc;
  815. }
  816. }
  817. }
  818. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  819. {
  820. std::set<int> pom;
  821. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  822. if(j->second == *i)
  823. pom.insert(j->first);
  824. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  825. }
  826. while (!end2)
  827. {
  828. if(!resume)
  829. newTurn();
  830. else
  831. resume = false;
  832. std::map<ui8,PlayerState>::iterator i;
  833. if(!resume)
  834. i = gs->players.begin();
  835. else
  836. i = gs->players.find(gs->currentPlayer);
  837. for(; i != gs->players.end(); i++)
  838. {
  839. if((i->second.towns.size()==0 && i->second.heroes.size()==0) || i->second.color<0 || i->first>=PLAYER_LIMIT ) continue; //players has not towns/castle - loser
  840. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  841. gs->currentPlayer = i->first;
  842. {
  843. YourTurn yt;
  844. yt.player = i->first;
  845. boost::unique_lock<boost::mutex> lock(*connections[i->first]->wmx);
  846. *connections[i->first] << &yt;
  847. }
  848. //wait till turn is done
  849. boost::unique_lock<boost::mutex> lock(states.mx);
  850. while(states.players[i->first].makingTurn && !end2)
  851. {
  852. boost::posix_time::time_duration p;
  853. p = boost::posix_time::milliseconds(200);
  854. states.cv.timed_wait(lock,p);
  855. }
  856. }
  857. }
  858. }
  859. namespace CGH
  860. {
  861. using namespace std;
  862. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  863. {
  864. for(int j=0; j<7; ++j)
  865. {
  866. std::vector<int> pom;
  867. for(int g=0; g<j+1; ++g)
  868. {
  869. int hlp; input>>hlp;
  870. pom.push_back(hlp);
  871. }
  872. dest.push_back(pom);
  873. }
  874. }
  875. }
  876. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, const CCreatureSet &army1, const CCreatureSet &army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank, const CGTownInstance *town)
  877. {
  878. battleResult.set(NULL);
  879. std::vector<CStack*> & stacks = (curB->stacks);
  880. curB->tile = tile;
  881. curB->army1=army1;
  882. curB->army2=army2;
  883. curB->heroes[0] = const_cast<CGHeroInstance*>(hero1);
  884. curB->heroes[1] = const_cast<CGHeroInstance*>(hero2);
  885. curB->round = -2;
  886. curB->activeStack = -1;
  887. if(town)
  888. {
  889. curB->tid = town->id;
  890. curB->siege = town->fortLevel();
  891. }
  892. else
  893. {
  894. curB->tid = -1;
  895. curB->siege = 0;
  896. }
  897. //reading battleStartpos
  898. std::ifstream positions;
  899. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  900. if(!positions.is_open())
  901. {
  902. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  903. }
  904. std::string dump;
  905. positions>>dump; positions>>dump;
  906. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  907. CGH::readItTo(positions, attackerLoose);
  908. positions>>dump;
  909. CGH::readItTo(positions, defenderLoose);
  910. positions>>dump;
  911. positions>>dump;
  912. CGH::readItTo(positions, attackerTight);
  913. positions>>dump;
  914. CGH::readItTo(positions, defenderTight);
  915. positions>>dump;
  916. positions>>dump;
  917. CGH::readItTo(positions, attackerCreBank);
  918. positions>>dump;
  919. CGH::readItTo(positions, defenderCreBank);
  920. positions.close();
  921. //battleStartpos read
  922. int k = 0; //stack serial
  923. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army1.slots.begin(); i!=army1.slots.end(); i++, k++)
  924. {
  925. int pos;
  926. if(creatureBank)
  927. pos = attackerCreBank[army1.slots.size()-1][k];
  928. else if(army1.formation)
  929. pos = attackerTight[army1.slots.size()-1][k];
  930. else
  931. pos = attackerLoose[army1.slots.size()-1][k];
  932. 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);
  933. stacks.push_back(stack);
  934. }
  935. k = 0;
  936. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army2.slots.begin(); i!=army2.slots.end(); i++, k++)
  937. {
  938. int pos;
  939. if(creatureBank)
  940. pos = defenderCreBank[army2.slots.size()-1][k];
  941. else if(army2.formation)
  942. pos = defenderTight[army2.slots.size()-1][k];
  943. else
  944. pos = defenderLoose[army2.slots.size()-1][k];
  945. 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);
  946. stacks.push_back(stack);
  947. }
  948. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  949. {
  950. if((stacks[g]->position%17)==1 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned)
  951. {
  952. stacks[g]->position += 1;
  953. }
  954. else if((stacks[g]->position%17)==15 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned)
  955. {
  956. stacks[g]->position -= 1;
  957. }
  958. }
  959. //adding war machines
  960. if(hero1)
  961. {
  962. if(hero1->getArt(13)) //ballista
  963. {
  964. CStack * stack = curB->generateNewStack(hero1, 146, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 52);
  965. stacks.push_back(stack);
  966. }
  967. if(hero1->getArt(14)) //ammo cart
  968. {
  969. CStack * stack = curB->generateNewStack(hero1, 148, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 18);
  970. stacks.push_back(stack);
  971. }
  972. if(hero1->getArt(15)) //first aid tent
  973. {
  974. CStack * stack = curB->generateNewStack(hero1, 147, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 154);
  975. stacks.push_back(stack);
  976. }
  977. }
  978. if(hero2)
  979. {
  980. if(hero2->getArt(13)) //ballista
  981. {
  982. CStack * stack = curB->generateNewStack(hero2, 146, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 66);
  983. stacks.push_back(stack);
  984. }
  985. if(hero2->getArt(14)) //ammo cart
  986. {
  987. CStack * stack = curB->generateNewStack(hero2, 148, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 32);
  988. stacks.push_back(stack);
  989. }
  990. if(hero2->getArt(15)) //first aid tent
  991. {
  992. CStack * stack = curB->generateNewStack(hero2, 147, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 168);
  993. stacks.push_back(stack);
  994. }
  995. }
  996. if(town && hero1 && town->hasFort()) //catapult
  997. {
  998. CStack * stack = curB->generateNewStack(hero1, 145, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 120);
  999. stacks.push_back(stack);
  1000. }
  1001. //war machines added
  1002. switch(curB->siege) //adding towers
  1003. {
  1004. case 3: //castle
  1005. {//lower tower / upper tower
  1006. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -4);
  1007. stacks.push_back(stack);
  1008. stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -3);
  1009. stacks.push_back(stack);
  1010. }
  1011. case 2: //citadel
  1012. {//main tower
  1013. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -2);
  1014. stacks.push_back(stack);
  1015. }
  1016. }
  1017. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1018. //seting up siege
  1019. if(town && town->hasFort())
  1020. {
  1021. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1022. {
  1023. curB->si.wallState[b] = 1;
  1024. }
  1025. }
  1026. int terType = gs->battleGetBattlefieldType(tile);
  1027. //randomize obstacles
  1028. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1029. {
  1030. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1031. std::vector<int> possibleObstacles;
  1032. for(int i=0; i<BFIELD_SIZE; ++i)
  1033. {
  1034. if(i%17 < 4 || i%17 > 12)
  1035. {
  1036. obAv[i] = false;
  1037. }
  1038. else
  1039. {
  1040. obAv[i] = true;
  1041. }
  1042. }
  1043. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1044. {
  1045. 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
  1046. {
  1047. possibleObstacles.push_back(g->first);
  1048. }
  1049. }
  1050. srand(time(NULL));
  1051. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1052. {
  1053. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1054. while(toBlock>0)
  1055. {
  1056. CObstacleInstance coi;
  1057. coi.uniqueID = curB->obstacles.size();
  1058. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1059. coi.pos = rand()%BFIELD_SIZE;
  1060. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1061. bool badObstacle = false;
  1062. for(int b=0; b<block.size(); ++b)
  1063. {
  1064. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1065. {
  1066. badObstacle = true;
  1067. break;
  1068. }
  1069. }
  1070. if(badObstacle) continue;
  1071. //obstacle can be placed
  1072. curB->obstacles.push_back(coi);
  1073. for(int b=0; b<block.size(); ++b)
  1074. {
  1075. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1076. obAv[block[b]] = false;
  1077. }
  1078. toBlock -= block.size();
  1079. }
  1080. }
  1081. }
  1082. //giving terrain premies for heroes & stacks
  1083. int bonusSubtype = -1;
  1084. switch(terType)
  1085. {
  1086. case 9: //magic plains
  1087. {
  1088. bonusSubtype = 0;
  1089. }
  1090. case 14: //fiery fields
  1091. {
  1092. if(bonusSubtype == -1) bonusSubtype = 1;
  1093. }
  1094. case 15: //rock lands
  1095. {
  1096. if(bonusSubtype == -1) bonusSubtype = 8;
  1097. }
  1098. case 16: //magic clouds
  1099. {
  1100. if(bonusSubtype == -1) bonusSubtype = 2;
  1101. }
  1102. case 17: //lucid pools
  1103. {
  1104. if(bonusSubtype == -1) bonusSubtype = 4;
  1105. }
  1106. { //common part for cases 9, 14, 15, 16, 17
  1107. const CGHeroInstance * cHero = NULL;
  1108. for(int i=0; i<2; ++i)
  1109. {
  1110. if(i == 0) cHero = hero1;
  1111. else cHero = hero2;
  1112. if(cHero == NULL) continue;
  1113. GiveBonus gs;
  1114. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::MAGIC_SCHOOL_SKILL, HeroBonus::OBJECT, 3, -1, "", bonusSubtype);
  1115. gs.hid = cHero->id;
  1116. sendAndApply(&gs);
  1117. }
  1118. break;
  1119. }
  1120. case 18: //holy ground
  1121. {
  1122. for(int g=0; g<stacks.size(); ++g) //+1 morale bonus for good creatures, -1 morale bonus for evil creatures
  1123. {
  1124. if (stacks[g]->creature->isGood())
  1125. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1126. else if (stacks[g]->creature->isEvil())
  1127. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1128. }
  1129. break;
  1130. }
  1131. case 19: //clover field
  1132. {
  1133. for(int g=0; g<stacks.size(); ++g)
  1134. {
  1135. if(stacks[g]->creature->faction == -1) //+2 luck bonus for neutral creatures
  1136. {
  1137. stacks[g]->features.push_back(makeFeature(StackFeature::LUCK_BONUS, StackFeature::WHOLE_BATTLE, 0, 2, StackFeature::OTHER_SOURCE));
  1138. }
  1139. }
  1140. break;
  1141. }
  1142. case 20: //evil fog
  1143. {
  1144. for(int g=0; g<stacks.size(); ++g) //-1 morale bonus for good creatures, +1 morale bonus for evil creatures
  1145. {
  1146. if (stacks[g]->creature->isGood())
  1147. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1148. else if (stacks[g]->creature->isEvil())
  1149. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1150. }
  1151. break;
  1152. }
  1153. case 22: //cursed ground
  1154. {
  1155. for(int g=0; g<stacks.size(); ++g) //no luck nor morale
  1156. {
  1157. stacks[g]->features.push_back(makeFeature(StackFeature::NO_MORALE, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1158. stacks[g]->features.push_back(makeFeature(StackFeature::NO_LUCK, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1159. }
  1160. const CGHeroInstance * cHero = NULL;
  1161. for(int i=0; i<2; ++i) //blocking spells above level 1
  1162. {
  1163. if(i == 0) cHero = hero1;
  1164. else cHero = hero2;
  1165. if(cHero == NULL) continue;
  1166. GiveBonus gs;
  1167. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL, HeroBonus::OBJECT, 1, -1, "", bonusSubtype);
  1168. gs.hid = cHero->id;
  1169. sendAndApply(&gs);
  1170. }
  1171. break;
  1172. }
  1173. }
  1174. //premies given
  1175. //send info about battles
  1176. BattleStart bs;
  1177. bs.info = curB;
  1178. sendAndApply(&bs);
  1179. }
  1180. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1181. {
  1182. //checking winning condition
  1183. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1184. hasStack[0] = hasStack[1] = false;
  1185. for(int b = 0; b<stacks.size(); ++b)
  1186. {
  1187. if(stacks[b]->alive() && !stacks[b]->hasFeatureOfType(StackFeature::SIEGE_WEAPON))
  1188. {
  1189. hasStack[1-stacks[b]->attackerOwned] = true;
  1190. }
  1191. }
  1192. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1193. {
  1194. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1195. br->result = 0;
  1196. br->winner = hasStack[1]; //fleeing side loses
  1197. gs->curB->calculateCasualties(br->casualties);
  1198. battleResult.set(br);
  1199. }
  1200. }
  1201. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1202. {
  1203. if(!vstd::contains(h->artifWorn,17))
  1204. return; //hero hasn't spellbok
  1205. ChangeSpells cs;
  1206. cs.hid = h->id;
  1207. cs.learn = true;
  1208. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  1209. {
  1210. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1211. {
  1212. if(!vstd::contains(h->spells,t->spells[i][j]))
  1213. cs.spells.insert(t->spells[i][j]);
  1214. }
  1215. }
  1216. if(cs.spells.size())
  1217. sendAndApply(&cs);
  1218. }
  1219. void CGameHandler::setBlockVis(int objid, bool bv)
  1220. {
  1221. SetObjectProperty sop(objid,2,bv);
  1222. sendAndApply(&sop);
  1223. }
  1224. bool CGameHandler::removeObject( int objid )
  1225. {
  1226. if(!getObj(objid))
  1227. {
  1228. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1229. return false;
  1230. }
  1231. RemoveObject ro;
  1232. ro.id = objid;
  1233. sendAndApply(&ro);
  1234. return true;
  1235. }
  1236. void CGameHandler::setAmount(int objid, ui32 val)
  1237. {
  1238. SetObjectProperty sop(objid,3,val);
  1239. sendAndApply(&sop);
  1240. }
  1241. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1242. {
  1243. bool blockvis = false;
  1244. const CGHeroInstance *h = getHero(hid);
  1245. 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)
  1246. )
  1247. {
  1248. tlog1 << "Illegal call to move hero!\n";
  1249. return false;
  1250. }
  1251. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1252. int3 hmpos = dst + int3(-1,0,0);
  1253. if(!gs->map->isInTheMap(hmpos))
  1254. {
  1255. tlog1 << "Destination tile os out of the map!\n";
  1256. return false;
  1257. }
  1258. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1259. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1260. //result structure for start - movement failed, no move points used
  1261. TryMoveHero tmh;
  1262. tmh.id = hid;
  1263. tmh.start = h->pos;
  1264. tmh.end = dst;
  1265. tmh.result = TryMoveHero::FAILED;
  1266. tmh.movePoints = h->movement;
  1267. //check if destination tile is available
  1268. //it's a rock or blocked and not visitable tile
  1269. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1270. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable))
  1271. && complain("Cannot move hero, destination tile is blocked!")
  1272. || (!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)
  1273. && complain("Cannot move hero, destination tile is on water!")
  1274. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1275. && complain("Cannot disembark hero, tile is blocked!")
  1276. || (h->movement < cost && dst != h->pos)
  1277. && complain("Hero don't have any movement points left!")
  1278. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1279. && complain("Cannot move hero during the battle"))
  1280. {
  1281. //send info about movement failure
  1282. sendAndApply(&tmh);
  1283. return false;
  1284. }
  1285. //hero enters the boat
  1286. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1287. {
  1288. tmh.result = TryMoveHero::EMBARK;
  1289. tmh.movePoints = 0; //embarking takes all move points
  1290. //TODO: check for bonus that removes that penalty
  1291. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1292. sendAndApply(&tmh);
  1293. return true;
  1294. }
  1295. //hero leaves the boat
  1296. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1297. {
  1298. tmh.result = TryMoveHero::DISEMBARK;
  1299. tmh.movePoints = 0; //disembarking takes all move points
  1300. //TODO: check for bonus that removes that penalty
  1301. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1302. sendAndApply(&tmh);
  1303. return true;
  1304. }
  1305. //checks for standard movement
  1306. if(!instant)
  1307. {
  1308. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighbouring!")
  1309. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1310. {
  1311. sendAndApply(&tmh);
  1312. return false;
  1313. }
  1314. //check if there is blocking visitable object
  1315. blockvis = false;
  1316. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1317. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1318. {
  1319. if(obj != h && obj->blockVisit && !(obj->getPassableness() & 1<<h->tempOwner))
  1320. {
  1321. blockvis = true;
  1322. break;
  1323. }
  1324. }
  1325. //we start moving
  1326. if(blockvis)//interaction with blocking object (like resources)
  1327. {
  1328. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1329. sendAndApply(&tmh);
  1330. //failed to move to that tile but we visit object
  1331. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1332. {
  1333. if (obj->blockVisit)
  1334. {
  1335. objectVisited(obj, h);
  1336. }
  1337. }
  1338. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1339. return true;
  1340. }
  1341. else //normal move
  1342. {
  1343. tmh.result = TryMoveHero::SUCCESS;
  1344. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1345. {
  1346. obj->onHeroLeave(h);
  1347. }
  1348. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1349. sendAndApply(&tmh);
  1350. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1351. //call objects if they are visited
  1352. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1353. {
  1354. objectVisited(obj, h);
  1355. }
  1356. }
  1357. tlog5 << "Movement end!\n";
  1358. return true;
  1359. }
  1360. else //instant move - teleportation
  1361. {
  1362. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1363. {
  1364. if(obj->ID==HEROI_TYPE)
  1365. {
  1366. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1367. if(obj->tempOwner==h->tempOwner)
  1368. {
  1369. heroExchange(dh->id, h->id);
  1370. return true;
  1371. }
  1372. //TODO: check for ally
  1373. startBattleI(h, dh);
  1374. return true;
  1375. }
  1376. }
  1377. tmh.result = TryMoveHero::TELEPORTATION;
  1378. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1379. sendAndApply(&tmh);
  1380. return true;
  1381. }
  1382. }
  1383. void CGameHandler::setOwner(int objid, ui8 owner)
  1384. {
  1385. SetObjectProperty sop(objid,1,owner);
  1386. sendAndApply(&sop);
  1387. }
  1388. void CGameHandler::setHoverName(int objid, MetaString* name)
  1389. {
  1390. SetHoverName shn(objid, *name);
  1391. sendAndApply(&shn);
  1392. }
  1393. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1394. {
  1395. sendToAllClients(iw);
  1396. }
  1397. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1398. {
  1399. ask(iw,iw->player,callback);
  1400. }
  1401. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1402. {
  1403. //TODO
  1404. //gsm.lock();
  1405. //int query = QID++;
  1406. //states.addQuery(player,query);
  1407. //sendToAllClients(iw);
  1408. //gsm.unlock();
  1409. //ui32 ret = getQueryResult(iw->player, query);
  1410. //gsm.lock();
  1411. //states.removeQuery(player, query);
  1412. //gsm.unlock();
  1413. return 0;
  1414. }
  1415. int CGameHandler::getCurrentPlayer()
  1416. {
  1417. return gs->currentPlayer;
  1418. }
  1419. void CGameHandler::giveResource(int player, int which, int val)
  1420. {
  1421. if(!val) return; //don't waste time on empty call
  1422. SetResource sr;
  1423. sr.player = player;
  1424. sr.resid = which;
  1425. sr.val = gs->players.find(player)->second.resources[which]+val;
  1426. sendAndApply(&sr);
  1427. }
  1428. void CGameHandler::giveCreatures (int objid, const CGHeroInstance * h, CCreatureSet creatures)
  1429. {
  1430. if (creatures.slots.size() <= 0)
  1431. return;
  1432. CCreatureSet heroArmy = h->army;
  1433. while (creatures.slots.size() > 0)
  1434. {
  1435. int slot = heroArmy.getSlotFor (creatures.slots.begin()->second.first);
  1436. if (slot < 0)
  1437. break;
  1438. heroArmy.slots[slot].first = creatures.slots.begin()->second.first;
  1439. heroArmy.slots[slot].second += creatures.slots.begin()->second.second;
  1440. creatures.slots.erase (creatures.slots.begin());
  1441. }
  1442. if (creatures.slots.size() == 0) //all creatures can be moved to hero army - do that
  1443. {
  1444. SetGarrisons sg;
  1445. sg.garrs[h->id] = heroArmy;
  1446. sendAndApply(&sg);
  1447. }
  1448. else //show garrison window and let player pick creatures
  1449. {
  1450. SetGarrisons sg;
  1451. sg.garrs[objid] = creatures;
  1452. sendAndApply (&sg);
  1453. showGarrisonDialog (objid, h->id, true, 0);
  1454. return;
  1455. }
  1456. }
  1457. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1458. {
  1459. sendToAllClients(comp);
  1460. }
  1461. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1462. {
  1463. HeroVisitCastle vc;
  1464. vc.hid = heroID;
  1465. vc.tid = obj;
  1466. vc.flags |= 1;
  1467. sendAndApply(&vc);
  1468. vistiCastleObjects (getTown(obj), getHero(heroID));
  1469. giveSpells (getTown(obj), getHero(heroID));
  1470. }
  1471. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1472. {
  1473. std::vector<CGTownBuilding*>::const_iterator i;
  1474. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1475. (*i)->onHeroVisit (h);
  1476. }
  1477. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1478. {
  1479. HeroVisitCastle vc;
  1480. vc.hid = heroID;
  1481. vc.tid = obj;
  1482. sendAndApply(&vc);
  1483. }
  1484. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1485. {
  1486. const CGHeroInstance* h = getHero(hid);
  1487. const CArtifact &art = VLC->arth->artifacts[artid];
  1488. SetHeroArtifacts sha;
  1489. sha.hid = hid;
  1490. sha.artifacts = h->artifacts;
  1491. sha.artifWorn = h->artifWorn;
  1492. if(position<0)
  1493. {
  1494. if(position == -2)
  1495. {
  1496. int i;
  1497. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1498. {
  1499. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1500. {
  1501. //we've found a free suitable slot
  1502. sha.artifWorn[art.possibleSlots[i]] = artid;
  1503. break;
  1504. }
  1505. }
  1506. if(i == art.possibleSlots.size()) //if haven't find proper slot, use backpack
  1507. sha.artifacts.push_back(artid);
  1508. }
  1509. else //should be -1 => put artifact into backpack
  1510. {
  1511. sha.artifacts.push_back(artid);
  1512. }
  1513. }
  1514. else
  1515. {
  1516. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1517. {
  1518. sha.artifWorn[position] = artid;
  1519. }
  1520. else
  1521. {
  1522. sha.artifacts.push_back(artid);
  1523. }
  1524. }
  1525. sendAndApply(&sha);
  1526. }
  1527. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town) //use hero=NULL for no hero
  1528. {
  1529. engageIntoBattle(army1->tempOwner);
  1530. engageIntoBattle(army2->tempOwner);
  1531. //block engaged players
  1532. if(army2->tempOwner < PLAYER_LIMIT)
  1533. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1534. boost::thread(boost::bind(&CGameHandler::startBattle, this, army1, army2, tile, hero1, hero2, creatureBank, cb, town));
  1535. }
  1536. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  1537. {
  1538. startBattleI(army1, army2, tile,
  1539. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  1540. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  1541. creatureBank, cb);
  1542. }
  1543. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  1544. {
  1545. startBattleI(army1, army2, army2->pos - army2->getVisitableOffset(), cb, creatureBank);
  1546. }
  1547. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1548. //{
  1549. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1550. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  1551. // //battle(&h->army,army,tile,h,NULL);
  1552. //}
  1553. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1554. {
  1555. ChangeSpells cs;
  1556. cs.hid = hid;
  1557. cs.spells = spells;
  1558. cs.learn = give;
  1559. sendAndApply(&cs);
  1560. }
  1561. int CGameHandler::getSelectedHero()
  1562. {
  1563. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1564. }
  1565. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  1566. {
  1567. SetObjectProperty sob;
  1568. sob.id = objid;
  1569. sob.what = prop;
  1570. sob.val = val;
  1571. sendAndApply(&sob);
  1572. }
  1573. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1574. {
  1575. SystemMessage sm;
  1576. sm.text = message;
  1577. c << &sm;
  1578. }
  1579. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1580. {
  1581. sendAndApply(bonus);
  1582. }
  1583. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1584. {
  1585. sendAndApply(smp);
  1586. }
  1587. void CGameHandler::setManaPoints( int hid, int val )
  1588. {
  1589. SetMana sm;
  1590. sm.hid = hid;
  1591. sm.val = val;
  1592. sendAndApply(&sm);
  1593. }
  1594. void CGameHandler::giveHero( int id, int player )
  1595. {
  1596. GiveHero gh;
  1597. gh.id = id;
  1598. gh.player = player;
  1599. sendAndApply(&gh);
  1600. }
  1601. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1602. {
  1603. ChangeObjPos cop;
  1604. cop.objid = objid;
  1605. cop.nPos = newPos;
  1606. cop.flags = flags;
  1607. sendAndApply(&cop);
  1608. }
  1609. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  1610. {
  1611. ui8 player1 = getHero(hero1)->tempOwner;
  1612. ui8 player2 = getHero(hero2)->tempOwner;
  1613. if(player1 == player2)
  1614. {
  1615. OpenWindow hex;
  1616. hex.window = OpenWindow::EXCHANGE_WINDOW;
  1617. hex.id1 = hero1;
  1618. hex.id2 = hero2;
  1619. sendAndApply(&hex);
  1620. }
  1621. }
  1622. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1623. {
  1624. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1625. sel->id = QID;
  1626. callbacks[QID] = callback;
  1627. states.addQuery(player,QID);
  1628. QID++;
  1629. sendAndApply(sel);
  1630. }
  1631. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1632. {
  1633. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1634. sel->id = QID;
  1635. callbacks[QID] = callback;
  1636. states.addQuery(player,QID);
  1637. sendToAllClients(sel);
  1638. QID++;
  1639. }
  1640. void CGameHandler::sendToAllClients( CPackForClient * info )
  1641. {
  1642. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1643. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1644. {
  1645. (*i)->wmx->lock();
  1646. **i << info;
  1647. (*i)->wmx->unlock();
  1648. }
  1649. }
  1650. void CGameHandler::sendAndApply( CPackForClient * info )
  1651. {
  1652. gs->apply(info);
  1653. sendToAllClients(info);
  1654. }
  1655. void CGameHandler::save( const std::string &fname )
  1656. {
  1657. {
  1658. tlog0 << "Ordering clients to serialize...\n";
  1659. SaveGame sg(fname);
  1660. sendToAllClients(&sg);
  1661. }
  1662. {
  1663. tlog0 << "Serializing game info...\n";
  1664. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vlgm1");
  1665. char hlp[8] = "VCMISVG";
  1666. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  1667. }
  1668. {
  1669. tlog0 << "Serializing server info...\n";
  1670. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vsgm1");
  1671. save << *this;
  1672. }
  1673. tlog0 << "Game has been successfully saved!\n";
  1674. }
  1675. void CGameHandler::close()
  1676. {
  1677. tlog0 << "We have been requested to close.\n";
  1678. //BOOST_FOREACH(CConnection *cc, conns)
  1679. // if(cc && cc->socket && cc->socket->is_open())
  1680. // cc->socket->close();
  1681. //exit(0);
  1682. }
  1683. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val )
  1684. {
  1685. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  1686. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  1687. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  1688. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  1689. if(!isAllowedExchange(id1,id2))
  1690. {
  1691. complain("Cannot exchange stacks between these two objects!\n");
  1692. return false;
  1693. }
  1694. if(what==1) //swap
  1695. {
  1696. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  1697. //if one of them is empty, remove entry
  1698. if(!S1.slots[p1].second)
  1699. S1.slots.erase(p1);
  1700. if(!S2.slots[p2].second)
  1701. S2.slots.erase(p2);
  1702. }
  1703. else if(what==2)//merge
  1704. {
  1705. if(S1.slots[p1].first != S2.slots[p2].first) //not same creature
  1706. {
  1707. complain("Cannot merge different creatures stacks!");
  1708. return false;
  1709. }
  1710. S2.slots[p2].second += S1.slots[p1].second;
  1711. S1.slots.erase(p1);
  1712. }
  1713. else if(what==3) //split
  1714. {
  1715. //general conditions checking
  1716. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1717. || (val<1 && complain("no creatures to split")) )
  1718. {
  1719. return false;
  1720. }
  1721. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1722. {
  1723. int total = S1.slots[p1].second + S2.slots[p2].second;
  1724. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1725. || (S2.slots[p2].first != S1.slots[p1].first && complain("Cannot rebalance different creatures stacks!"))
  1726. )
  1727. {
  1728. return false;
  1729. }
  1730. S2.slots[p2].second = val;
  1731. S1.slots[p1].second = total - val;
  1732. }
  1733. else //split one stack to the two
  1734. {
  1735. if(S1.slots[p1].second < val)//not enough creatures
  1736. {
  1737. complain("Cannot split that stack, not enough creatures!");
  1738. return false;
  1739. }
  1740. S2.slots[p2].first = S1.slots[p1].first;
  1741. S2.slots[p2].second = val;
  1742. S1.slots[p1].second -= val;
  1743. }
  1744. if(!S1.slots[p1].second) //if we've moved all creatures
  1745. S1.slots.erase(p1);
  1746. }
  1747. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  1748. || (s2->needsLastStack() && !S2.slots.size())
  1749. )
  1750. {
  1751. complain("Cannot take the last stack!");
  1752. return false; //leave without applying changes to garrison
  1753. }
  1754. //apply changes
  1755. SetGarrisons sg;
  1756. sg.garrs[id1] = S1;
  1757. if(s1 != s2)
  1758. sg.garrs[id2] = S2;
  1759. sendAndApply(&sg);
  1760. return true;
  1761. }
  1762. int CGameHandler::getPlayerAt( CConnection *c ) const
  1763. {
  1764. std::set<int> all;
  1765. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1766. if(i->second == c)
  1767. all.insert(i->first);
  1768. switch(all.size())
  1769. {
  1770. case 0:
  1771. return 255;
  1772. case 1:
  1773. return *all.begin();
  1774. default:
  1775. {
  1776. //if we have more than one player at this connection, try to pick active one
  1777. if(vstd::contains(all,int(gs->currentPlayer)))
  1778. return gs->currentPlayer;
  1779. else
  1780. return 253; //cannot say which player is it
  1781. }
  1782. }
  1783. }
  1784. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  1785. {
  1786. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  1787. if(!vstd::contains(s1->army.slots,pos))
  1788. {
  1789. complain("Illegal call to disbandCreature - no such stack in army!");
  1790. return false;
  1791. }
  1792. s1->army.slots.erase(pos);
  1793. SetGarrisons sg;
  1794. sg.garrs[id] = s1->army;
  1795. sendAndApply(&sg);
  1796. return true;
  1797. }
  1798. bool CGameHandler::buildStructure( si32 tid, si32 bid )
  1799. {
  1800. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1801. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  1802. if(gs->canBuildStructure(t,bid) != 7)
  1803. {
  1804. complain("Cannot raze that building!");
  1805. return false;
  1806. }
  1807. NewStructures ns;
  1808. ns.tid = tid;
  1809. if(bid>36) //upg dwelling
  1810. {
  1811. if(t->getHordeLevel(0) == (bid-37))
  1812. ns.bid.insert(19);
  1813. else if(t->getHordeLevel(1) == (bid-37))
  1814. ns.bid.insert(25);
  1815. SetAvailableCreatures ssi;
  1816. ssi.tid = tid;
  1817. ssi.creatures = t->creatures;
  1818. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  1819. sendAndApply(&ssi);
  1820. }
  1821. else if(bid >= 30) //bas. dwelling
  1822. {
  1823. int crid = t->town->basicCreatures[bid-30];
  1824. SetAvailableCreatures ssi;
  1825. ssi.tid = tid;
  1826. ssi.creatures = t->creatures;
  1827. ssi.creatures[bid-30].first = VLC->creh->creatures[crid].growth;
  1828. ssi.creatures[bid-30].second.push_back(crid);
  1829. sendAndApply(&ssi);
  1830. }
  1831. ns.bid.insert(bid);
  1832. ns.builded = t->builded + 1;
  1833. sendAndApply(&ns);
  1834. //reveal ground for lookout tower
  1835. FoWChange fw;
  1836. fw.player = t->tempOwner;
  1837. fw.mode = 1;
  1838. getTilesInRange(fw.tiles,t->pos,t->getSightRadious(),t->tempOwner,1);
  1839. sendAndApply(&fw);
  1840. SetResources sr;
  1841. sr.player = t->tempOwner;
  1842. sr.res = gs->getPlayer(t->tempOwner)->resources;
  1843. for(int i=0;i<b->resources.size();i++)
  1844. sr.res[i]-=b->resources[i];
  1845. sendAndApply(&sr);
  1846. if(bid<5) //it's mage guild
  1847. {
  1848. if(t->visitingHero)
  1849. giveSpells(t,t->visitingHero);
  1850. if(t->garrisonHero)
  1851. giveSpells(t,t->garrisonHero);
  1852. }
  1853. if(t->visitingHero)
  1854. vistiCastleObjects (t, t->visitingHero);
  1855. if(t->garrisonHero)
  1856. vistiCastleObjects (t, t->garrisonHero);
  1857. return true;
  1858. }
  1859. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  1860. {
  1861. ///incomplete, simply erases target building
  1862. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1863. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  1864. return false;
  1865. RazeStructures rs;
  1866. rs.tid = tid;
  1867. rs.bid.insert(bid);
  1868. rs.destroyed = t->destroyed + 1;
  1869. sendAndApply(&rs);
  1870. return true;
  1871. }
  1872. void CGameHandler::sendMessageToAll( const std::string &message )
  1873. {
  1874. SystemMessage sm;
  1875. sm.text = message;
  1876. sendToAllClients(&sm);
  1877. }
  1878. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  1879. {
  1880. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid]);
  1881. const CArmedInstance *dst = NULL;
  1882. if(dw->ID == TOWNI_TYPE)
  1883. dst = dw;
  1884. else if(dw->ID == 17 || dw->ID == 20) //advmap dwelling
  1885. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  1886. assert(dw && dst);
  1887. //verify
  1888. bool found = false;
  1889. int level = -1;
  1890. typedef std::pair<const int,int> Parka;
  1891. for(level = 0; level < dw->creatures.size(); level++) //iterate through all levels
  1892. {
  1893. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  1894. int i = 0;
  1895. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  1896. if(cur.second[i] == crid)
  1897. break;
  1898. if(i < cur.second.size())
  1899. {
  1900. found = true;
  1901. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  1902. break;
  1903. }
  1904. }
  1905. int slot = dst->army.getSlotFor(crid);
  1906. if(!found && complain("Cannot recruit: no such creatures!")
  1907. || cram > VLC->creh->creatures[crid].maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  1908. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  1909. || slot<0 && complain("Cannot recruit: no available slot!"))
  1910. {
  1911. return false;
  1912. }
  1913. //recruit
  1914. SetResources sr;
  1915. sr.player = dst->tempOwner;
  1916. for(int i=0;i<RESOURCE_QUANTITY;i++)
  1917. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  1918. SetAvailableCreatures sac;
  1919. sac.tid = objid;
  1920. sac.creatures = dw->creatures;
  1921. sac.creatures[level].first -= cram;
  1922. SetGarrisons sg;
  1923. sg.garrs[dst->id] = dst->army;
  1924. if(sg.garrs[dst->id].slots.find(slot) == sg.garrs[dst->id].slots.end()) //take a free slot
  1925. {
  1926. sg.garrs[dst->id].slots[slot] = std::make_pair(crid,cram);
  1927. }
  1928. else //add creatures to a already existing stack
  1929. {
  1930. sg.garrs[dst->id].slots[slot].second += cram;
  1931. }
  1932. sendAndApply(&sr);
  1933. sendAndApply(&sac);
  1934. sendAndApply(&sg);
  1935. return true;
  1936. }
  1937. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  1938. {
  1939. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  1940. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  1941. int player = obj->tempOwner;
  1942. int crQuantity = obj->army.slots[pos].second;
  1943. //check if upgrade is possible
  1944. if((ui.oldID<0 || !vstd::contains(ui.newID,upgID)) && complain("That upgrade is not possible!"))
  1945. {
  1946. return false;
  1947. }
  1948. //check if player has enough resources
  1949. for(int i=0;i<ui.cost.size();i++)
  1950. {
  1951. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1952. {
  1953. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  1954. {
  1955. complain("Cannot upgrade, not enough resources!");
  1956. return false;
  1957. }
  1958. }
  1959. }
  1960. //take resources
  1961. for(int i=0;i<ui.cost.size();i++)
  1962. {
  1963. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1964. {
  1965. SetResource sr;
  1966. sr.player = player;
  1967. sr.resid = j->first;
  1968. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  1969. sendAndApply(&sr);
  1970. }
  1971. }
  1972. //upgrade creature
  1973. SetGarrisons sg;
  1974. sg.garrs[objid] = obj->army;
  1975. sg.garrs[objid].slots[pos].first = upgID;
  1976. sendAndApply(&sg);
  1977. return true;
  1978. }
  1979. bool CGameHandler::garrisonSwap( si32 tid )
  1980. {
  1981. CGTownInstance *town = gs->getTown(tid);
  1982. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  1983. {
  1984. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  1985. while(!cso.slots.empty())//while there are unmoved creatures
  1986. {
  1987. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  1988. if(pos<0)
  1989. {
  1990. //try to merge two other stacks to make place
  1991. std::pair<TSlot, TSlot> toMerge;
  1992. if(csn.mergableStacks(toMerge, cso.slots.begin()->first))
  1993. {
  1994. //merge
  1995. csn.slots[toMerge.second].second += csn.slots[toMerge.first].second;
  1996. csn.slots[toMerge.first] = cso.slots.begin()->second;
  1997. }
  1998. else
  1999. {
  2000. complain("Cannot make garrison swap, not enough free slots!");
  2001. return false;
  2002. }
  2003. }
  2004. else if(csn.slots.find(pos) != csn.slots.end()) //add creatures to the existing stack
  2005. {
  2006. csn.slots[pos].second += cso.slots.begin()->second.second;
  2007. }
  2008. else //move stack on the free pos
  2009. {
  2010. csn.slots[pos].first = cso.slots.begin()->second.first;
  2011. csn.slots[pos].second = cso.slots.begin()->second.second;
  2012. }
  2013. cso.slots.erase(cso.slots.begin());
  2014. }
  2015. SetGarrisons sg;
  2016. sg.garrs[town->visitingHero->id] = csn;
  2017. sg.garrs[town->id] = csn;
  2018. sendAndApply(&sg);
  2019. SetHeroesInTown intown;
  2020. intown.tid = tid;
  2021. intown.visiting = -1;
  2022. intown.garrison = town->visitingHero->id;
  2023. sendAndApply(&intown);
  2024. return true;
  2025. }
  2026. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2027. {
  2028. //check if moving hero out of town will break 8 wandering heroes limit
  2029. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2030. {
  2031. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2032. return false;
  2033. }
  2034. SetHeroesInTown intown;
  2035. intown.tid = tid;
  2036. intown.garrison = -1;
  2037. intown.visiting = town->garrisonHero->id;
  2038. sendAndApply(&intown);
  2039. //town will be empty
  2040. SetGarrisons sg;
  2041. sg.garrs[tid] = CCreatureSet();
  2042. sendAndApply(&sg);
  2043. return true;
  2044. }
  2045. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2046. {
  2047. SetGarrisons sg;
  2048. sg.garrs[town->id] = town->visitingHero->army;
  2049. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  2050. SetHeroesInTown intown;
  2051. intown.tid = tid;
  2052. intown.garrison = town->visitingHero->id;
  2053. intown.visiting = town->garrisonHero->id;
  2054. sendAndApply(&intown);
  2055. sendAndApply(&sg);
  2056. return true;
  2057. }
  2058. else
  2059. {
  2060. complain("Cannot swap garrison hero!");
  2061. return false;
  2062. }
  2063. }
  2064. bool CGameHandler::swapArtifacts(si32 srcHeroID, si32 destHeroID, ui16 srcSlot, ui16 destSlot)
  2065. {
  2066. CGHeroInstance *srcHero = gs->getHero(srcHeroID);
  2067. CGHeroInstance *destHero = gs->getHero(destHeroID);
  2068. // Make sure exchange is even possible between the two heroes.
  2069. if ((distance(srcHero->pos,destHero->pos) > 1.5 )|| (srcHero->tempOwner != destHero->tempOwner))
  2070. return false;
  2071. const CArtifact *srcArtifact = srcHero->getArt(srcSlot);
  2072. const CArtifact *destArtifact = destHero->getArt(destSlot);
  2073. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2074. // Moving to the backpack is always allowed.
  2075. if ((!srcArtifact || destSlot < 19)
  2076. && (((srcArtifact && !vstd::contains(srcArtifact->possibleSlots, destSlot))
  2077. || (destArtifact && srcSlot < 19 && !vstd::contains(destArtifact->possibleSlots, srcSlot)))))
  2078. {
  2079. complain("Cannot swap artifacts!");
  2080. return false;
  2081. }
  2082. // TODO: This relates to bug #112, fix later.
  2083. // Make sure the artifacts are not war machines.
  2084. if ((srcSlot>=13 && srcSlot<=16) || (destSlot>=13 && destSlot<=16)) {
  2085. complain("Cannot move war machine!");
  2086. return false;
  2087. }
  2088. // Perform the exchange.
  2089. SetHeroArtifacts sha;
  2090. sha.hid = srcHeroID;
  2091. sha.artifacts = srcHero->artifacts;
  2092. sha.artifWorn = srcHero->artifWorn;
  2093. sha.setArtAtPos(srcSlot, -1);
  2094. if (destSlot < 19 && (destArtifact || srcSlot < 19))
  2095. sha.setArtAtPos(srcSlot, destHero->getArtAtPos(destSlot));
  2096. // Internal hero artifact arrangement.
  2097. if(srcHero == destHero) {
  2098. // Correction for destination from removing source artifact in backpack.
  2099. if (srcSlot >= 19 && destSlot >= 19 && srcSlot < destSlot)
  2100. destSlot--;
  2101. sha.setArtAtPos(destSlot, srcHero->getArtAtPos(srcSlot));
  2102. }
  2103. sendAndApply(&sha);
  2104. if (srcHeroID != destHeroID) {
  2105. // Exchange between two different heroes.
  2106. sha.hid = destHeroID;
  2107. sha.artifacts = destHero->artifacts;
  2108. sha.artifWorn = destHero->artifWorn;
  2109. sha.setArtAtPos(destSlot, srcArtifact ? srcArtifact->id : -1);
  2110. sendAndApply(&sha);
  2111. }
  2112. return true;
  2113. }
  2114. /**
  2115. * Sets a hero artifact slot to contain a specific artifact.
  2116. *
  2117. * @param artID ID of an artifact or -1 for no artifact.
  2118. */
  2119. bool CGameHandler::setArtifact(si32 heroID, ui16 slot, int artID)
  2120. {
  2121. CGHeroInstance *hero = gs->getHero(heroID);
  2122. // TODO: Deal with war machine placement.
  2123. // Perform the exchange.
  2124. SetHeroArtifacts sha;
  2125. sha.hid = heroID;
  2126. sha.artifacts = hero->artifacts;
  2127. sha.artifWorn = hero->artifWorn;
  2128. sha.setArtAtPos(slot, artID);
  2129. sendAndApply(&sha);
  2130. return true;
  2131. }
  2132. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2133. {
  2134. CGHeroInstance *hero = gs->getHero(hid);
  2135. CGTownInstance *town = hero->visitedTown;
  2136. if(aid==0) //spellbook
  2137. {
  2138. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2139. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  2140. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  2141. )
  2142. return false;
  2143. giveResource(hero->getOwner(),6,-500);
  2144. giveHeroArtifact(0,hid,17);
  2145. giveSpells(town,hero);
  2146. return true;
  2147. }
  2148. else if(aid < 7 && aid > 3) //war machine
  2149. {
  2150. int price = VLC->arth->artifacts[aid].price;
  2151. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2152. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2153. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  2154. || town->town->warMachine!= aid && complain("This machine is unavailable here!") ) //TODO: ballista yard in Stronghold
  2155. {
  2156. return false;
  2157. }
  2158. giveResource(hero->getOwner(),6,-price);
  2159. giveHeroArtifact(aid,hid,9+aid);
  2160. return true;
  2161. }
  2162. return false;
  2163. }
  2164. bool CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  2165. {
  2166. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  2167. double yield = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  2168. yield /= gs->resVals[id2];
  2169. SetResource sr;
  2170. sr.player = player;
  2171. sr.resid = id1;
  2172. sr.val = gs->getPlayer(player)->resources[id1] - val;
  2173. sendAndApply(&sr);
  2174. sr.resid = id2;
  2175. sr.val = gs->getPlayer(player)->resources[id2] + (int)yield;
  2176. sendAndApply(&sr);
  2177. return true;
  2178. }
  2179. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  2180. {
  2181. gs->getHero(hid)->army.formation = formation;
  2182. return true;
  2183. }
  2184. bool CGameHandler::hireHero( ui32 tid, ui8 hid )
  2185. {
  2186. CGTownInstance *t = gs->getTown(tid);
  2187. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  2188. || gs->getPlayer(t->tempOwner)->resources[6]<2500 && complain("Not enough gold for buying hero!")
  2189. || t->visitingHero && complain("There is visiting hero - no place!")
  2190. || getHeroCount(t->tempOwner,false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!")
  2191. )
  2192. return false;
  2193. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  2194. assert(nh);
  2195. HeroRecruited hr;
  2196. hr.tid = tid;
  2197. hr.hid = nh->subID;
  2198. hr.player = t->tempOwner;
  2199. hr.tile = t->pos - int3(1,0,0);
  2200. sendAndApply(&hr);
  2201. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  2202. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  2203. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2204. if(*j)
  2205. pool.erase((**j).subID);
  2206. SetAvailableHeroes sah;
  2207. CGHeroInstance *h1 = gs->hpool.pickHeroFor(false,t->tempOwner,t->town, pool),
  2208. *h2 = gs->getPlayer(t->tempOwner)->availableHeroes[!hid];
  2209. (hid ? sah.hid2 : sah.hid1) = h1 ? h1->subID : -1;
  2210. (hid ? sah.hid1 : sah.hid2) = h2 ? h2->subID : -1;
  2211. sah.player = t->tempOwner;
  2212. sah.flags = hid+1;
  2213. sendAndApply(&sah);
  2214. SetResource sr;
  2215. sr.player = t->tempOwner;
  2216. sr.resid = 6;
  2217. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  2218. sendAndApply(&sr);
  2219. vistiCastleObjects (t, nh);
  2220. giveSpells (t,nh);
  2221. return true;
  2222. }
  2223. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  2224. {
  2225. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2226. if(vstd::contains(callbacks,qid))
  2227. {
  2228. CFunctionList<void(ui32)> callb = callbacks[qid];
  2229. callbacks.erase(qid);
  2230. if(callb)
  2231. callb(answer);
  2232. }
  2233. else if(vstd::contains(garrisonCallbacks,qid))
  2234. {
  2235. if(garrisonCallbacks[qid])
  2236. garrisonCallbacks[qid]();
  2237. garrisonCallbacks.erase(qid);
  2238. allowedExchanges.erase(qid);
  2239. }
  2240. else
  2241. {
  2242. tlog1 << "Unknown query reply...\n";
  2243. return false;
  2244. }
  2245. return true;
  2246. }
  2247. bool CGameHandler::makeBattleAction( BattleAction &ba )
  2248. {
  2249. tlog1 << "\tMaking action of type " << ba.actionType << std::endl;
  2250. bool ok = true;
  2251. switch(ba.actionType)
  2252. {
  2253. case 2: //walk
  2254. {
  2255. sendAndApply(&StartAction(ba)); //start movement
  2256. moveStack(ba.stackNumber,ba.destinationTile); //move
  2257. sendAndApply(&EndAction());
  2258. break;
  2259. }
  2260. case 3: //defend
  2261. case 8: //wait
  2262. {
  2263. sendAndApply(&StartAction(ba));
  2264. sendAndApply(&EndAction());
  2265. break;
  2266. }
  2267. case 4: //retreat/flee
  2268. {
  2269. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  2270. break;
  2271. //TODO: remove retreating hero from map and place it in recruitment list
  2272. BattleResult *br = new BattleResult;
  2273. br->result = 1;
  2274. br->winner = !ba.side; //fleeing side loses
  2275. gs->curB->calculateCasualties(br->casualties);
  2276. giveExp(*br);
  2277. battleResult.set(br);
  2278. break;
  2279. }
  2280. case 6: //walk or attack
  2281. {
  2282. sendAndApply(&StartAction(ba)); //start movement and attack
  2283. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  2284. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  2285. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2286. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  2287. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  2288. && !(curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  2289. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  2290. ) //nor occupy specified hex
  2291. )
  2292. {
  2293. std::string problem = "We cannot move this stack to its destination " + curStack->creature->namePl;
  2294. tlog3 << problem << std::endl;
  2295. complain(problem);
  2296. ok = false;
  2297. sendAndApply(&EndAction());
  2298. break;
  2299. }
  2300. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  2301. {
  2302. stackAtEnd = NULL;
  2303. }
  2304. if(!stackAtEnd)
  2305. {
  2306. std::ostringstream problem;
  2307. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  2308. std::string probl = problem.str();
  2309. tlog3 << probl << std::endl;
  2310. complain(probl);
  2311. ok = false;
  2312. sendAndApply(&EndAction());
  2313. break;
  2314. }
  2315. ui16 curpos = curStack->position,
  2316. enemypos = stackAtEnd->position;
  2317. if( !(
  2318. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  2319. || (curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //back <=> front
  2320. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  2321. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //front <=> back
  2322. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2323. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)//back <=> back
  2324. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2325. )
  2326. )
  2327. {
  2328. tlog3 << "Attack cannot be performed!";
  2329. sendAndApply(&EndAction());
  2330. ok = false;
  2331. }
  2332. //attack
  2333. BattleAttack bat;
  2334. prepareAttack(bat, curStack, stackAtEnd, distance);
  2335. sendAndApply(&bat);
  2336. //counterattack
  2337. if(!curStack->hasFeatureOfType(StackFeature::BLOCKS_RETALIATION)
  2338. && stackAtEnd->alive()
  2339. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasFeatureOfType(StackFeature::UNLIMITED_RETALIATIONS) )
  2340. && !stackAtEnd->hasFeatureOfType(StackFeature::SIEGE_WEAPON)
  2341. && !stackAtEnd->hasFeatureOfType(StackFeature::HYPNOTIZED))
  2342. {
  2343. prepareAttack(bat, stackAtEnd, curStack, 0);
  2344. bat.flags |= 2;
  2345. sendAndApply(&bat);
  2346. }
  2347. //second attack
  2348. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0
  2349. && !curStack->hasFeatureOfType(StackFeature::SHOOTER)
  2350. && curStack->alive()
  2351. && stackAtEnd->alive() )
  2352. {
  2353. bat.flags = 0;
  2354. prepareAttack(bat, curStack, stackAtEnd, 0);
  2355. sendAndApply(&bat);
  2356. }
  2357. //return
  2358. if(curStack->hasFeatureOfType(StackFeature::RETURN_AFTER_STRIKE) && startingPos != curStack->position)
  2359. {
  2360. moveStack(ba.stackNumber, startingPos);
  2361. }
  2362. sendAndApply(&EndAction());
  2363. break;
  2364. }
  2365. case 7: //shoot
  2366. {
  2367. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2368. *destStack= gs->curB->getStackT(ba.destinationTile);
  2369. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  2370. break;
  2371. sendAndApply(&StartAction(ba)); //start shooting
  2372. BattleAttack bat;
  2373. prepareAttack(bat, curStack, destStack, 0);
  2374. bat.flags |= 1;
  2375. sendAndApply(&bat);
  2376. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  2377. && curStack->alive()
  2378. && destStack->alive()
  2379. && curStack->shots
  2380. )
  2381. {
  2382. prepareAttack(bat, curStack, destStack, 0);
  2383. sendAndApply(&bat);
  2384. }
  2385. sendAndApply(&EndAction());
  2386. break;
  2387. }
  2388. case 9: //catapult
  2389. {
  2390. sendAndApply(&StartAction(ba));
  2391. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  2392. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(20)]; //artillery
  2393. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  2394. if(attackedPart == -1)
  2395. {
  2396. complain("catapult tried to attack non-catapultable hex!");
  2397. break;
  2398. }
  2399. for(int g=0; g<sbi.shots; ++g)
  2400. {
  2401. if(gs->curB->si.wallState[attackedPart] == 3) //it's not destroyed
  2402. continue;
  2403. CatapultAttack ca; //package for clients
  2404. std::pair< std::pair< ui8, si16 >, ui8> attack;
  2405. attack.first.first = attackedPart;
  2406. attack.first.second = ba.destinationTile;
  2407. attack.second = 0;
  2408. int chanceForHit = 0;
  2409. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  2410. switch(attackedPart)
  2411. {
  2412. case 0: //keep
  2413. chanceForHit = sbi.keep;
  2414. break;
  2415. case 1: //bottom tower
  2416. case 6: //upper tower
  2417. chanceForHit = sbi.tower;
  2418. break;
  2419. case 2: //bottom wall
  2420. case 3: //below gate
  2421. case 4: //over gate
  2422. case 5: //upper wall
  2423. chanceForHit = sbi.wall;
  2424. break;
  2425. case 7: //gate
  2426. chanceForHit = sbi.gate;
  2427. break;
  2428. }
  2429. if(rand()%100 <= chanceForHit) //hit is successful
  2430. {
  2431. int dmgRand = rand()%100;
  2432. //accumulating dmgChance
  2433. dmgChance[1] += dmgChance[0];
  2434. dmgChance[2] += dmgChance[1];
  2435. //calculating dealt damage
  2436. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  2437. {
  2438. if(dmgRand <= dmgChance[v])
  2439. {
  2440. attack.second = v;
  2441. break;
  2442. }
  2443. }
  2444. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  2445. {
  2446. int posRemove = -1;
  2447. switch(attackedPart)
  2448. {
  2449. case 0: //keep
  2450. posRemove = -2;
  2451. break;
  2452. case 1: //bottom tower
  2453. posRemove = -3;
  2454. break;
  2455. case 6: //upper tower
  2456. posRemove = -4;
  2457. break;
  2458. }
  2459. BattleStacksRemoved bsr;
  2460. for(int g=0; g<gs->curB->stacks.size(); ++g)
  2461. {
  2462. if(gs->curB->stacks[g]->position == posRemove)
  2463. {
  2464. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  2465. break;
  2466. }
  2467. }
  2468. sendAndApply(&bsr);
  2469. }
  2470. }
  2471. ca.attacker = ba.stackNumber;
  2472. ca.attackedParts.insert(attack);
  2473. sendAndApply(&ca);
  2474. }
  2475. sendAndApply(&EndAction());
  2476. break;
  2477. }
  2478. }
  2479. battleMadeAction.setn(true);
  2480. return ok;
  2481. }
  2482. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  2483. {
  2484. bool cheated=true;
  2485. sendAndApply(&PlayerMessage(player,message));
  2486. if(message == "vcmiistari") //give all spells and 999 mana
  2487. {
  2488. SetMana sm;
  2489. ChangeSpells cs;
  2490. SetHeroArtifacts sha;
  2491. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  2492. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  2493. sm.hid = cs.hid = h->id;
  2494. //give all spells
  2495. cs.learn = 1;
  2496. for(int i=0;i<VLC->spellh->spells.size();i++)
  2497. {
  2498. if(!VLC->spellh->spells[i].creatureAbility)
  2499. cs.spells.insert(i);
  2500. }
  2501. //give mana
  2502. sm.val = 999;
  2503. if(!h->getArt(17)) //hero doesn't have spellbook
  2504. {
  2505. //give spellbook
  2506. sha.hid = h->id;
  2507. sha.artifacts = h->artifacts;
  2508. sha.artifWorn = h->artifWorn;
  2509. sha.artifWorn[17] = 0;
  2510. sendAndApply(&sha);
  2511. }
  2512. sendAndApply(&cs);
  2513. sendAndApply(&sm);
  2514. }
  2515. else if(message == "vcmiainur") //gives 5 archangels into each slot
  2516. {
  2517. SetGarrisons sg;
  2518. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2519. if(!hero) return;
  2520. sg.garrs[hero->id] = hero->army;
  2521. for(int i=0;i<7;i++)
  2522. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2523. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  2524. sendAndApply(&sg);
  2525. }
  2526. else if(message == "vcmiangband") //gives 10 black knight into each slot
  2527. {
  2528. SetGarrisons sg;
  2529. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2530. if(!hero) return;
  2531. sg.garrs[hero->id] = hero->army;
  2532. for(int i=0;i<7;i++)
  2533. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2534. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  2535. sendAndApply(&sg);
  2536. }
  2537. else if(message == "vcminoldor") //all war machines
  2538. {
  2539. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2540. if(!hero) return;
  2541. SetHeroArtifacts sha;
  2542. sha.hid = hero->id;
  2543. sha.artifacts = hero->artifacts;
  2544. sha.artifWorn = hero->artifWorn;
  2545. sha.artifWorn[13] = 4;
  2546. sha.artifWorn[14] = 5;
  2547. sha.artifWorn[15] = 6;
  2548. sendAndApply(&sha);
  2549. }
  2550. else if(message == "vcminahar") //1000000 movement points
  2551. {
  2552. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2553. if(!hero) return;
  2554. SetMovePoints smp;
  2555. smp.hid = hero->id;
  2556. smp.val = 1000000;
  2557. sendAndApply(&smp);
  2558. }
  2559. else if(message == "vcmiformenos") //give resources
  2560. {
  2561. SetResources sr;
  2562. sr.player = player;
  2563. sr.res = gs->getPlayer(player)->resources;
  2564. for(int i=0;i<7;i++)
  2565. sr.res[i] += 100;
  2566. sr.res[6] += 19900;
  2567. sendAndApply(&sr);
  2568. }
  2569. else if(message == "vcmieagles") //reveal FoW
  2570. {
  2571. FoWChange fc;
  2572. fc.mode = 1;
  2573. fc.player = player;
  2574. for(int i=0;i<gs->map->width;i++)
  2575. for(int j=0;j<gs->map->height;j++)
  2576. for(int k=0;k<gs->map->twoLevel+1;k++)
  2577. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  2578. fc.tiles.insert(int3(i,j,k));
  2579. sendAndApply(&fc);
  2580. }
  2581. else if(message == "vcmiglorfindel")
  2582. {
  2583. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2584. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  2585. }
  2586. else
  2587. cheated = false;
  2588. if(cheated)
  2589. {
  2590. sendAndApply(&SystemMessage("CHEATER!!!"));
  2591. }
  2592. }
  2593. static ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack)
  2594. {
  2595. switch(spell->id)
  2596. {
  2597. case 37: //cure
  2598. {
  2599. int healedHealth = caster->getPrimSkillLevel(2) * 5 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2600. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft);
  2601. break;
  2602. }
  2603. case 38: //resurrection
  2604. {
  2605. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2606. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2607. break;
  2608. }
  2609. case 39: //animate dead
  2610. {
  2611. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2612. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2613. break;
  2614. }
  2615. }
  2616. //we shouldn't be here
  2617. tlog1 << "calculateHealedHP called for non-healing spell: " << spell->name << std::endl;
  2618. return 0;
  2619. }
  2620. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  2621. {
  2622. std::vector<ui32> ret;
  2623. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2624. {
  2625. if ((*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2626. || ((*it)->valOfFeatures(StackFeature::LEVEL_SPELL_IMMUNITY) >= sp->level))
  2627. {
  2628. ret.push_back((*it)->ID);
  2629. continue;
  2630. }
  2631. //non-negative spells on friendly stacks should always succeed, unless immune
  2632. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  2633. continue;
  2634. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  2635. if((*it)->owner == caster->tempOwner)
  2636. bonusHero = caster;
  2637. else
  2638. bonusHero = hero2;
  2639. int prob = (*it)->valOfFeatures(StackFeature::MAGIC_RESISTANCE); //probability of resistance in %
  2640. if(bonusHero)
  2641. {
  2642. //bonusHero's resistance support (secondary skils and artifacts)
  2643. prob += bonusHero->valOfBonuses(HeroBonus::MAGIC_RESISTANCE);
  2644. switch(bonusHero->getSecSkillLevel(26)) //resistance
  2645. {
  2646. case 1: //basic
  2647. prob += 5;
  2648. break;
  2649. case 2: //advanced
  2650. prob += 10;
  2651. break;
  2652. case 3: //expert
  2653. prob += 20;
  2654. break;
  2655. }
  2656. }
  2657. if(prob > 100) prob = 100;
  2658. if(rand()%100 < prob) //immunity from resistance
  2659. ret.push_back((*it)->ID);
  2660. }
  2661. if(sp->id == 60) //hypnotize
  2662. {
  2663. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2664. {
  2665. if( (*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2666. || ( (*it)->amount - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  2667. >
  2668. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  2669. )
  2670. {
  2671. ret.push_back((*it)->ID);
  2672. }
  2673. }
  2674. }
  2675. return ret;
  2676. }
  2677. bool CGameHandler::makeCustomAction( BattleAction &ba )
  2678. {
  2679. switch(ba.actionType)
  2680. {
  2681. case 1: //hero casts spell
  2682. {
  2683. const CGHeroInstance *h = gs->curB->heroes[ba.side];
  2684. const CGHeroInstance *secondHero = gs->curB->heroes[!ba.side];
  2685. if(!h)
  2686. {
  2687. tlog2 << "Wrong caster!\n";
  2688. return false;
  2689. }
  2690. if(ba.additionalInfo >= VLC->spellh->spells.size())
  2691. {
  2692. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  2693. return false;
  2694. }
  2695. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  2696. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  2697. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  2698. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  2699. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  2700. || (gs->curB->castSpells[ba.side]) //spell has been cast
  2701. || (secondHero->hasBonusOfType(HeroBonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  2702. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  2703. )
  2704. {
  2705. tlog2 << "Spell cannot be cast!\n";
  2706. return false;
  2707. }
  2708. sendAndApply(&StartAction(ba)); //start spell casting
  2709. SpellCast sc;
  2710. sc.side = ba.side;
  2711. sc.id = ba.additionalInfo;
  2712. sc.skill = skill;
  2713. sc.tile = ba.destinationTile;
  2714. sc.dmgToDisplay = 0;
  2715. //calculating affected creatures for all spells
  2716. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(s, h, ba.destinationTile);
  2717. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2718. {
  2719. sc.affectedCres.insert((*it)->ID);
  2720. }
  2721. //checking if creatures resist
  2722. sc.resisted = calculateResistedStacks(s, h, secondHero, attackedCres);
  2723. //calculating dmg to display
  2724. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2725. {
  2726. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2727. continue;
  2728. sc.dmgToDisplay += gs->curB->calculateSpellDmg(s, h, *it);
  2729. }
  2730. sendAndApply(&sc);
  2731. //applying effects
  2732. switch(ba.additionalInfo) //spell id
  2733. {
  2734. case 15: //magic arrow
  2735. case 16: //ice bolt
  2736. case 17: //lightning bolt
  2737. case 18: //implosion
  2738. case 20: //frost ring
  2739. case 21: //fireball
  2740. case 22: //inferno
  2741. case 23: //meteor shower
  2742. case 24: //death ripple
  2743. case 25: //destroy undead
  2744. case 26: //armageddon
  2745. {
  2746. StacksInjured si;
  2747. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2748. {
  2749. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2750. continue;
  2751. BattleStackAttacked bsa;
  2752. bsa.flags |= 2;
  2753. bsa.effect = VLC->spellh->spells[ba.additionalInfo].mainEffectAnim;
  2754. bsa.damageAmount = gs->curB->calculateSpellDmg(s, h, *it);
  2755. bsa.stackAttacked = (*it)->ID;
  2756. bsa.attackerID = -1;
  2757. prepareAttacked(bsa,*it);
  2758. si.stacks.insert(bsa);
  2759. }
  2760. if(!si.stacks.empty())
  2761. sendAndApply(&si);
  2762. break;
  2763. }
  2764. case 27: //shield
  2765. case 28: //air shield
  2766. case 30: //protection from air
  2767. case 31: //protection from fire
  2768. case 32: //protection from water
  2769. case 33: //protection from earth
  2770. case 34: //anti-magic
  2771. case 41: //bless
  2772. case 42: //curse
  2773. case 43: //bloodlust
  2774. case 44: //precision
  2775. case 45: //weakness
  2776. case 46: //stone skin
  2777. case 47: //disrupting ray
  2778. case 48: //prayer
  2779. case 49: //mirth
  2780. case 50: //sorrow
  2781. case 51: //fortune
  2782. case 52: //misfortune
  2783. case 53: //haste
  2784. case 54: //slow
  2785. case 55: //slayer
  2786. case 56: //frenzy
  2787. case 58: //counterstrike
  2788. case 59: //berserk
  2789. case 60: //hypnotize
  2790. case 61: //forgetfulness
  2791. case 62: //blind
  2792. {
  2793. SetStackEffect sse;
  2794. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2795. {
  2796. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2797. continue;
  2798. sse.stacks.insert((*it)->ID);
  2799. }
  2800. sse.effect.id = ba.additionalInfo;
  2801. sse.effect.level = h->getSpellSchoolLevel(s);
  2802. sse.effect.turnsRemain = BattleInfo::calculateSpellDuration(s, h);
  2803. if(!sse.stacks.empty())
  2804. sendAndApply(&sse);
  2805. break;
  2806. }
  2807. case 37: //cure
  2808. case 38: //resurrection
  2809. case 39: //animate dead
  2810. {
  2811. StacksHealedOrResurrected shr;
  2812. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2813. {
  2814. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  2815. || (s->id == 39 && !(*it)->hasFeatureOfType(StackFeature::UNDEAD)) //we try to cast animate dead on living stack
  2816. )
  2817. continue;
  2818. StacksHealedOrResurrected::HealInfo hi;
  2819. hi.stackID = (*it)->ID;
  2820. hi.healedHP = calculateHealedHP(h, s, *it);
  2821. shr.healedStacks.push_back(hi);
  2822. }
  2823. if(!shr.healedStacks.empty())
  2824. sendAndApply(&shr);
  2825. break;
  2826. }
  2827. case 64: //remove obstacle
  2828. {
  2829. ObstaclesRemoved obr;
  2830. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  2831. {
  2832. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  2833. if(vstd::contains(blockedHexes, ba.destinationTile)) //this obstacle covers given hex
  2834. {
  2835. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  2836. }
  2837. }
  2838. if(!obr.obstacles.empty())
  2839. sendAndApply(&obr);
  2840. break;
  2841. }
  2842. }
  2843. sendAndApply(&EndAction());
  2844. if( !gs->curB->getStack(gs->curB->activeStack, false)->alive() )
  2845. {
  2846. battleMadeAction.setn(true);
  2847. }
  2848. checkForBattleEnd(gs->curB->stacks);
  2849. if(battleResult.get())
  2850. {
  2851. endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  2852. }
  2853. return true;
  2854. }
  2855. }
  2856. return false;
  2857. }
  2858. void CGameHandler::handleTimeEvents()
  2859. {
  2860. gs->map->events.sort(evntCmp);
  2861. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  2862. {
  2863. CMapEvent *ev = gs->map->events.front();
  2864. for(int player = 0; player < PLAYER_LIMIT; player++)
  2865. {
  2866. PlayerState *pinfo = gs->getPlayer(player);
  2867. if( pinfo //player exists
  2868. && (ev->players & 1<<player) //event is enabled to this player
  2869. && ((ev->computerAffected && !pinfo->human)
  2870. || (ev->humanAffected && pinfo->human)
  2871. )
  2872. )
  2873. {
  2874. //give resources
  2875. SetResources sr;
  2876. sr.player = player;
  2877. sr.res = pinfo->resources;
  2878. //prepare dialog
  2879. InfoWindow iw;
  2880. iw.player = player;
  2881. iw.text << ev->message;
  2882. for (int i=0; i<ev->resources.size(); i++)
  2883. {
  2884. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  2885. {
  2886. // If removing too much resources, adjust the
  2887. // amount so the total doesn't become negative.
  2888. if (sr.res[i] + ev->resources[i] < 0)
  2889. ev->resources[i] = -sr.res[i];
  2890. if(ev->resources[i]) //if non-zero res change
  2891. {
  2892. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  2893. sr.res[i] += ev->resources[i];
  2894. }
  2895. }
  2896. }
  2897. if (iw.components.size())
  2898. {
  2899. sendAndApply(&sr); //update player resources if changed
  2900. }
  2901. sendAndApply(&iw); //show dialog
  2902. }
  2903. } //PLAYERS LOOP
  2904. if(ev->nextOccurence)
  2905. {
  2906. ev->firstOccurence += ev->nextOccurence;
  2907. gs->map->events.sort(evntCmp);
  2908. }
  2909. else
  2910. {
  2911. delete ev;
  2912. gs->map->events.pop_front();
  2913. }
  2914. }
  2915. }
  2916. bool CGameHandler::complain( const std::string &problem )
  2917. {
  2918. sendMessageToAll("Server encountered a problem: " + problem);
  2919. tlog1 << problem << std::endl;
  2920. return true;
  2921. }
  2922. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  2923. {
  2924. //TODO: write
  2925. return 0;
  2926. }
  2927. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  2928. {
  2929. ui8 player = getOwner(hid);
  2930. GarrisonDialog gd;
  2931. gd.hid = hid;
  2932. gd.objid = upobj;
  2933. {
  2934. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2935. gd.id = QID;
  2936. garrisonCallbacks[QID] = cb;
  2937. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  2938. states.addQuery(player,QID);
  2939. QID++;
  2940. gd.removableUnits = removableUnits;
  2941. sendAndApply(&gd);
  2942. }
  2943. }
  2944. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  2945. {
  2946. if(id1 == id2)
  2947. return true;
  2948. {
  2949. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2950. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  2951. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  2952. return true;
  2953. }
  2954. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  2955. if(o1->ID == TOWNI_TYPE)
  2956. {
  2957. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  2958. if(t->visitingHero == o2 || t->garrisonHero == o2)
  2959. return true;
  2960. }
  2961. if(o2->ID == TOWNI_TYPE)
  2962. {
  2963. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  2964. if(t->visitingHero == o1 || t->garrisonHero == o1)
  2965. return true;
  2966. }
  2967. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  2968. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  2969. {
  2970. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  2971. //(to block moving stacks for free [without visiting] beteen heroes)
  2972. return true;
  2973. }
  2974. return false;
  2975. }
  2976. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  2977. {
  2978. obj->onHeroVisit(h);
  2979. }
  2980. bool CGameHandler::buildBoat( ui32 objid )
  2981. {
  2982. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  2983. int boatType = 1;
  2984. if(obj->state())
  2985. {
  2986. complain("Cannot build boat in this shipyard!");
  2987. return false;
  2988. }
  2989. else if(obj->o->ID == TOWNI_TYPE
  2990. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  2991. {
  2992. complain("Cannot build boat in the town - no shipyard!");
  2993. return false;
  2994. }
  2995. //TODO use "real" cost via obj->getBoatCost
  2996. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  2997. {
  2998. complain("Not enough resources to build a boat!");
  2999. return false;
  3000. }
  3001. int3 tile = obj->bestLocation();
  3002. if(!gs->map->isInTheMap(tile))
  3003. {
  3004. complain("Cannot find appropriate tile for a boat!");
  3005. return false;
  3006. }
  3007. //take boat cost
  3008. SetResources sr;
  3009. sr.player = obj->o->tempOwner;
  3010. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  3011. sr.res[0] -= 10;
  3012. sr.res[6] -= 1000;
  3013. sendAndApply(&sr);
  3014. //create boat
  3015. NewObject no;
  3016. no.ID = 8;
  3017. if (obj->o->ID == TOWNI_TYPE)
  3018. {
  3019. switch ((static_cast<const CGTownInstance*>(obj))->alignment)
  3020. {
  3021. case 1: //good - standard
  3022. boatType = 1;
  3023. break;
  3024. case -1: //evil
  3025. boatType = 0;
  3026. break;
  3027. case 0: //neutral
  3028. boatType = 2;
  3029. break;
  3030. }
  3031. }
  3032. no.subID = boatType;
  3033. no.pos = tile + int3(1,0,0);
  3034. sendAndApply(&no);
  3035. return true;
  3036. }
  3037. void CGameHandler::engageIntoBattle( ui8 player )
  3038. {
  3039. if(vstd::contains(states.players, player))
  3040. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  3041. //notify interfaces
  3042. PlayerBlocked pb;
  3043. pb.player = player;
  3044. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  3045. sendAndApply(&pb);
  3046. }