CGameHandler.cpp 95 KB

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