CGameHandler.cpp 95 KB

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