CGameHandler.cpp 88 KB

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