CGameHandler.cpp 88 KB

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