CGameHandler.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370
  1. #include "../StartInfo.h"
  2. #include "../hch/CArtHandler.h"
  3. #include "../hch/CBuildingHandler.h"
  4. #include "../hch/CDefObjInfoHandler.h"
  5. #include "../hch/CGeneralTextHandler.h"
  6. #include "../hch/CHeroHandler.h"
  7. #include "../hch/CObjectHandler.h"
  8. #include "../hch/CSpellHandler.h"
  9. #include "../hch/CTownHandler.h"
  10. #include "../CGameState.h"
  11. #include "../lib/CondSh.h"
  12. #include "../lib/NetPacks.h"
  13. #include "../lib/Connection.h"
  14. #include "../lib/VCMI_Lib.h"
  15. #include "../map.h"
  16. #include "CGameHandler.h"
  17. #include <boost/bind.hpp>
  18. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  19. #include <boost/foreach.hpp>
  20. #include <boost/thread.hpp>
  21. #include <boost/thread/shared_mutex.hpp>
  22. #include <fstream>
  23. #undef DLL_EXPORT
  24. #define DLL_EXPORT
  25. #include "../lib/RegisterTypes.cpp"
  26. #ifndef _MSC_VER
  27. #include <boost/thread/xtime.hpp>
  28. #endif
  29. extern bool end2;
  30. #ifdef min
  31. #undef min
  32. #endif
  33. #ifdef max
  34. #undef max
  35. #endif
  36. #define NEW_ROUND BattleNextRound bnr;\
  37. bnr.round = gs->curB->round + 1;\
  38. sendAndApply(&bnr);
  39. boost::mutex gsm;
  40. ui32 CGameHandler::QID = 1;
  41. CondSh<bool> battleMadeAction;
  42. CondSh<BattleResult *> battleResult(NULL);
  43. std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback function - for selection dialogs
  44. class CBaseForGHApply
  45. {
  46. public:
  47. virtual void applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  48. };
  49. template <typename T> class CApplyOnGH : public CBaseForGHApply
  50. {
  51. public:
  52. void applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  53. {
  54. T *ptr = static_cast<T*>(pack);
  55. ptr->c = c;
  56. ptr->applyGh(gh);
  57. }
  58. };
  59. class CGHApplier
  60. {
  61. public:
  62. std::map<ui16,CBaseForGHApply*> apps;
  63. CGHApplier()
  64. {
  65. registerTypes3(*this);
  66. }
  67. template<typename T> void registerType(const T * t=NULL)
  68. {
  69. ui16 ID = typeList.registerType(t);
  70. apps[ID] = new CApplyOnGH<T>;
  71. }
  72. } *applier = NULL;
  73. class CMP_stack
  74. {
  75. public:
  76. inline bool operator ()(const CStack* a, const CStack* b)
  77. {
  78. return (a->speed())>(b->speed());
  79. }
  80. } cmpst ;
  81. double distance(int3 a, int3 b)
  82. {
  83. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  84. }
  85. int getSchoolLevel(const CGHeroInstance *h, const CSpell *s)
  86. {
  87. ui8 ret = 0;
  88. if(s->fire)
  89. ret = std::max(ret,h->getSecSkillLevel(14));
  90. if(s->air)
  91. ret = std::max(ret,h->getSecSkillLevel(15));
  92. if(s->water)
  93. ret = std::max(ret,h->getSecSkillLevel(16));
  94. if(s->earth)
  95. ret = std::max(ret,h->getSecSkillLevel(17));
  96. return ret;
  97. }
  98. void giveExp(BattleResult &r)
  99. {
  100. r.exp[0] = 0;
  101. r.exp[1] = 0;
  102. for(std::set<std::pair<ui32,si32> >::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  103. {
  104. r.exp[r.winner] += VLC->creh->creatures[i->first].hitPoints * i->second;
  105. }
  106. }
  107. PlayerStatus PlayerStatuses::operator[](ui8 player)
  108. {
  109. boost::unique_lock<boost::mutex> l(mx);
  110. if(players.find(player) != players.end())
  111. {
  112. return players[player];
  113. }
  114. else
  115. {
  116. throw std::string("No such player!");
  117. }
  118. }
  119. void PlayerStatuses::addPlayer(ui8 player)
  120. {
  121. boost::unique_lock<boost::mutex> l(mx);
  122. players[player];
  123. }
  124. bool PlayerStatuses::hasQueries(ui8 player)
  125. {
  126. boost::unique_lock<boost::mutex> l(mx);
  127. if(players.find(player) != players.end())
  128. {
  129. return players[player].queries.size();
  130. }
  131. else
  132. {
  133. throw std::string("No such player!");
  134. }
  135. }
  136. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  137. {
  138. boost::unique_lock<boost::mutex> l(mx);
  139. if(players.find(player) != players.end())
  140. {
  141. return players[player].*flag;
  142. }
  143. else
  144. {
  145. throw std::string("No such player!");
  146. }
  147. }
  148. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  149. {
  150. boost::unique_lock<boost::mutex> l(mx);
  151. if(players.find(player) != players.end())
  152. {
  153. players[player].*flag = val;
  154. }
  155. else
  156. {
  157. throw std::string("No such player!");
  158. }
  159. cv.notify_all();
  160. }
  161. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  162. {
  163. boost::unique_lock<boost::mutex> l(mx);
  164. if(players.find(player) != players.end())
  165. {
  166. players[player].queries.insert(id);
  167. }
  168. else
  169. {
  170. throw std::string("No such player!");
  171. }
  172. cv.notify_all();
  173. }
  174. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  175. {
  176. boost::unique_lock<boost::mutex> l(mx);
  177. if(players.find(player) != players.end())
  178. {
  179. players[player].queries.erase(id);
  180. }
  181. else
  182. {
  183. throw std::string("No such player!");
  184. }
  185. cv.notify_all();
  186. }
  187. template <typename T>
  188. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  189. {
  190. fun(args[which]);
  191. }
  192. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  193. {
  194. SetSecSkill sss;
  195. sss.id = ID;
  196. sss.which = which;
  197. sss.val = val;
  198. sss.abs = abs;
  199. sendAndApply(&sss);
  200. }
  201. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  202. {
  203. SetPrimSkill sps;
  204. sps.id = ID;
  205. sps.which = which;
  206. sps.abs = abs;
  207. sps.val = val;
  208. sendAndApply(&sps);
  209. if(which==4) //only for exp - hero may level up
  210. {
  211. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  212. if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  213. {
  214. //give prim skill
  215. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  216. int r = rand()%100, pom=0, x=0;
  217. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  218. for(;x<PRIMARY_SKILLS;x++)
  219. {
  220. pom += hero->type->heroClass->primChance[x].*g;
  221. if(r<pom)
  222. break;
  223. }
  224. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  225. SetPrimSkill sps;
  226. sps.id = ID;
  227. sps.which = x;
  228. sps.abs = false;
  229. sps.val = 1;
  230. sendAndApply(&sps);
  231. HeroLevelUp hlu;
  232. hlu.heroid = ID;
  233. hlu.primskill = x;
  234. hlu.level = hero->level+1;
  235. //picking sec. skills for choice
  236. std::set<int> basicAndAdv, expert, none;
  237. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  238. for(unsigned i=0;i<hero->secSkills.size();i++)
  239. {
  240. if(hero->secSkills[i].second < 3)
  241. basicAndAdv.insert(hero->secSkills[i].first);
  242. else
  243. expert.insert(hero->secSkills[i].first);
  244. none.erase(hero->secSkills[i].first);
  245. }
  246. //first offered skill
  247. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  248. {
  249. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  250. none.erase(hlu.skills.back());
  251. }
  252. else if(basicAndAdv.size())
  253. {
  254. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  255. hlu.skills.push_back(s);
  256. basicAndAdv.erase(s);
  257. }
  258. //second offered skill
  259. if(basicAndAdv.size())
  260. {
  261. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  262. }
  263. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  264. {
  265. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  266. }
  267. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  268. {
  269. 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));
  270. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  271. }
  272. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  273. {
  274. changeSecSkill(ID,hlu.skills.back(),1,false);
  275. sendAndApply(&hlu);
  276. }
  277. else //apply and send info
  278. {
  279. sendAndApply(&hlu);
  280. }
  281. }
  282. }
  283. }
  284. CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  285. {
  286. CCreatureSet ret(set);
  287. for(int i=0; i<bat->stacks.size();i++)
  288. {
  289. CStack *st = bat->stacks[i];
  290. if(st->owner==color && vstd::contains(set.slots,st->slot) && st->amount < set.slots.find(st->slot)->second.second)
  291. {
  292. if(st->alive())
  293. ret.slots[st->slot].second = st->amount;
  294. else
  295. ret.slots.erase(st->slot);
  296. }
  297. }
  298. return ret;
  299. }
  300. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb)
  301. {
  302. BattleInfo *curB = new BattleInfo;
  303. setupBattle(curB, tile, army1, army2, hero1, hero2); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  304. NEW_ROUND;
  305. //TODO: pre-tactic stuff, call scripts etc.
  306. //tactic round
  307. {
  308. NEW_ROUND;
  309. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  310. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  311. {
  312. //TODO: tactic round (round -1)
  313. }
  314. }
  315. //main loop
  316. while(!battleResult.get()) //till the end of the battle ;]
  317. {
  318. NEW_ROUND;
  319. std::vector<CStack*> & stacks = (gs->curB->stacks);
  320. const BattleInfo & curB = *gs->curB;
  321. //stack loop
  322. CStack *next;
  323. while(!battleResult.get() && (next=gs->curB->getNextStack()))
  324. {
  325. next->state -= WAITING; //if stack was waiting it'll now make move, so it won't be "waiting" anymore
  326. //check for bad morale => freeze
  327. if(next->Morale() < 0)
  328. {
  329. if( rand()%24 < (-next->Morale())*2 )
  330. {
  331. //unit loses its turn - empty freeze action
  332. BattleAction ba;
  333. ba.actionType = 11;
  334. ba.additionalInfo = 1;
  335. ba.side = !next->attackerOwned;
  336. ba.stackNumber = next->ID;
  337. sendAndApply(&StartAction(ba));
  338. sendAndApply(&EndAction());
  339. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  340. continue;
  341. }
  342. }
  343. askInterfaceForMove:
  344. //ask interface and wait for answer
  345. if(!battleResult.get())
  346. {
  347. BattleSetActiveStack sas;
  348. sas.stack = next->ID;
  349. sendAndApply(&sas);
  350. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  351. while(!battleMadeAction.data && !battleResult.get()) //active stack hasn't made its action and battle is still going
  352. battleMadeAction.cond.wait(lock);
  353. battleMadeAction.data = false;
  354. }
  355. else
  356. {
  357. break;
  358. }
  359. //we're after action, all results applied
  360. checkForBattleEnd(stacks); //check if this action ended the battle
  361. //check for good morale
  362. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  363. && !vstd::contains(next->state,DEFENDING)
  364. && !vstd::contains(next->state,WAITING)
  365. && next->alive()
  366. && next->Morale() > 0
  367. )
  368. if(rand()%24 < next->Morale()) //this stack hasn't got morale this turn
  369. goto askInterfaceForMove; //move this stack once more
  370. }
  371. }
  372. //unblock engaged players
  373. if(hero1->tempOwner<PLAYER_LIMIT)
  374. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  375. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  376. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  377. //casualties among heroes armies
  378. SetGarrisons sg;
  379. if(hero1)
  380. sg.garrs[hero1->id] = takeCasualties(hero1->tempOwner,hero1->army,gs->curB);
  381. if(hero2)
  382. sg.garrs[hero2->id] = takeCasualties(hero2->tempOwner,hero2->army,gs->curB);
  383. sendAndApply(&sg);
  384. //end battle, remove all info, free memory
  385. giveExp(*battleResult.data);
  386. sendAndApply(battleResult.data);
  387. if(cb)
  388. cb(battleResult.data);
  389. //if one hero has lost we will erase him
  390. if(battleResult.data->winner!=0 && hero1)
  391. {
  392. RemoveObject ro(hero1->id);
  393. sendAndApply(&ro);
  394. }
  395. if(battleResult.data->winner!=1 && hero2)
  396. {
  397. RemoveObject ro(hero2->id);
  398. sendAndApply(&ro);
  399. }
  400. //give exp
  401. if(battleResult.data->exp[0] && hero1)
  402. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  403. if(battleResult.data->exp[1] && hero2)
  404. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  405. delete battleResult.data;
  406. }
  407. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, CStack *def)
  408. {
  409. bsa.killedAmount = bsa.damageAmount / def->creature->hitPoints;
  410. unsigned damageFirst = bsa.damageAmount % def->creature->hitPoints;
  411. if( def->firstHPleft <= damageFirst )
  412. {
  413. bsa.killedAmount++;
  414. bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  415. }
  416. else
  417. {
  418. bsa.newHP = def->firstHPleft - damageFirst;
  419. }
  420. if(def->amount <= bsa.killedAmount) //stack killed
  421. {
  422. bsa.newAmount = 0;
  423. bsa.flags |= 1;
  424. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  425. }
  426. else
  427. {
  428. bsa.newAmount = def->amount - bsa.killedAmount;
  429. }
  430. }
  431. void CGameHandler::prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  432. {
  433. bat.bsa.clear();
  434. bat.stackAttacking = att->ID;
  435. std::set<BattleStackAttacked>::iterator i = bat.bsa.insert(BattleStackAttacked()).first;
  436. BattleStackAttacked *bsa = (BattleStackAttacked *) &*i;
  437. bsa->stackAttacked = def->ID;
  438. 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());//counting dealt damage
  439. if(att->Luck() > 0 && rand()%24 < att->Luck())
  440. {
  441. bsa->damageAmount *= 2;
  442. bsa->flags |= 4;
  443. }
  444. prepareAttacked(*bsa,def);
  445. }
  446. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  447. {
  448. CPack *pack = NULL;
  449. try
  450. {
  451. while(!end2)
  452. {
  453. c >> pack;
  454. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  455. CBaseForGHApply *apply = applier->apps[typeList.getTypeID(pack)];
  456. if(apply)
  457. {
  458. apply->applyOnGH(this,&c,pack);
  459. tlog5 << "Message successfully applied!\n";
  460. }
  461. else
  462. {
  463. tlog5 << "Message cannot be applied, cannot find applier!\n";
  464. }
  465. delete pack;
  466. pack = NULL;
  467. }
  468. }
  469. HANDLE_EXCEPTION(end2 = true);
  470. handleConEnd:
  471. tlog1 << "Ended handling connection\n";
  472. #undef SPELL_CAST_TEMPLATE_1
  473. }
  474. void CGameHandler::moveStack(int stack, int dest)
  475. {
  476. CStack *curStack = gs->curB->getStack(stack),
  477. *stackAtEnd = gs->curB->getStackT(dest);
  478. //initing necessary tables
  479. bool accessibility[BFIELD_SIZE];
  480. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  481. for(int b=0; b<BFIELD_SIZE; ++b)
  482. {
  483. accessibility[b] = false;
  484. }
  485. for(int g=0; g<accessible.size(); ++g)
  486. {
  487. accessibility[accessible[g]] = true;
  488. }
  489. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  490. if(!stackAtEnd && curStack->creature->isDoubleWide() && !accessibility[dest])
  491. {
  492. if(curStack->attackerOwned)
  493. {
  494. if(accessibility[dest+1])
  495. dest+=1;
  496. }
  497. else
  498. {
  499. if(accessibility[dest-1])
  500. dest-=1;
  501. }
  502. }
  503. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  504. return;
  505. //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
  506. // return false;
  507. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibility, curStack->creature->isFlying());
  508. if(curStack->creature->isFlying())
  509. {
  510. if(path.second <= curStack->speed() && path.first.size() > 0)
  511. {
  512. //inform clients about move
  513. BattleStackMoved sm;
  514. sm.stack = curStack->ID;
  515. sm.tile = path.first[0];
  516. sm.distance = path.second;
  517. sm.ending = true;
  518. sendAndApply(&sm);
  519. }
  520. }
  521. else //for non-flying creatures
  522. {
  523. int tilesToMove = std::max((int)(path.first.size() - curStack->speed()), 0);
  524. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  525. {
  526. //inform clients about move
  527. BattleStackMoved sm;
  528. sm.stack = curStack->ID;
  529. sm.tile = path.first[v];
  530. sm.distance = path.second;
  531. sm.ending = v==tilesToMove;
  532. sendAndApply(&sm);
  533. }
  534. }
  535. }
  536. CGameHandler::CGameHandler(void)
  537. {
  538. gs = NULL;
  539. IObjectInterface::cb = this;
  540. applier = new CGHApplier;
  541. }
  542. CGameHandler::~CGameHandler(void)
  543. {
  544. delete applier;
  545. applier = NULL;
  546. delete gs;
  547. }
  548. void CGameHandler::init(StartInfo *si, int Seed)
  549. {
  550. Mapa *map = new Mapa(si->mapname);
  551. tlog0 << "Map loaded!" << std::endl;
  552. gs = new CGameState();
  553. tlog0 << "Gamestate created!" << std::endl;
  554. gs->init(si,map,Seed);
  555. tlog0 << "Gamestate initialized!" << std::endl;
  556. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  557. states.addPlayer(i->first);
  558. }
  559. bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  560. {
  561. return *a < *b;
  562. }
  563. void CGameHandler::newTurn()
  564. {
  565. tlog5 << "Turn " << gs->day+1 << std::endl;
  566. NewTurn n;
  567. n.day = gs->day + 1;
  568. n.resetBuilded = true;
  569. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  570. {
  571. if(i->first == 255) continue;
  572. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  573. {
  574. SetAvailableHeroes sah;
  575. sah.player = i->first;
  576. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle]);
  577. if(h)
  578. sah.hid1 = h->subID;
  579. else
  580. sah.hid1 = -1;
  581. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle],sah.hid1);
  582. if(h)
  583. sah.hid2 = h->subID;
  584. else
  585. sah.hid2 = -1;
  586. sendAndApply(&sah);
  587. }
  588. if(i->first>=PLAYER_LIMIT) continue;
  589. SetResources r;
  590. r.player = i->first;
  591. for(int j=0;j<RESOURCE_QUANTITY;j++)
  592. r.res[j] = i->second.resources[j];
  593. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  594. {
  595. NewTurn::Hero hth;
  596. hth.id = h->id;
  597. hth.move = h->maxMovePoints(true); //TODO: check if hero is really on the land
  598. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  599. hth.mana = h->manaLimit(); //restore all mana
  600. else
  601. hth.mana = std::max(si32(0), std::min(h->mana + h->manaRegain(), h->manaLimit()) );
  602. n.heroes.insert(hth);
  603. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  604. {
  605. case 1: //basic
  606. r.res[6] += 125;
  607. break;
  608. case 2: //advanced
  609. r.res[6] += 250;
  610. break;
  611. case 3: //expert
  612. r.res[6] += 500;
  613. break;
  614. }
  615. }
  616. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  617. {
  618. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  619. {
  620. if((**j).town->primaryRes == 127) //we'll give wood and ore
  621. {
  622. r.res[0] += 1;
  623. r.res[2] += 1;
  624. }
  625. else
  626. {
  627. r.res[(**j).town->primaryRes] += 1;
  628. }
  629. }
  630. if(gs->getDate(1)==7) //first day of week
  631. {
  632. SetAvailableCreatures sac;
  633. sac.tid = (**j).id;
  634. sac.creatures = (**j).strInfo.creatures;
  635. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  636. {
  637. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  638. sac.creatures[k] += (**j).creatureGrowth(k);
  639. }
  640. n.cres.push_back(sac);
  641. }
  642. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  643. r.res[6] += (**j).dailyIncome();
  644. }
  645. n.res.push_back(r);
  646. }
  647. sendAndApply(&n);
  648. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  649. handleTimeEvents();
  650. //call objects
  651. for(size_t i = 0; i<gs->map->objects.size(); i++)
  652. if(gs->map->objects[i])
  653. gs->map->objects[i]->newTurn();
  654. }
  655. void CGameHandler::run(bool resume)
  656. {
  657. BOOST_FOREACH(CConnection *cc, conns)
  658. {//init conn.
  659. ui8 quantity, pom;
  660. //ui32 seed;
  661. if(!resume)
  662. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  663. (*cc) >> quantity; //how many players will be handled at that client
  664. for(int i=0;i<quantity;i++)
  665. {
  666. (*cc) >> pom; //read player color
  667. gsm.lock();
  668. connections[pom] = cc;
  669. gsm.unlock();
  670. }
  671. }
  672. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  673. {
  674. std::set<int> pom;
  675. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  676. if(j->second == *i)
  677. pom.insert(j->first);
  678. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  679. }
  680. while (!end2)
  681. {
  682. if(!resume)
  683. newTurn();
  684. else
  685. resume = false;
  686. std::map<ui8,PlayerState>::iterator i;
  687. if(!resume)
  688. i = gs->players.begin();
  689. else
  690. i = gs->players.find(gs->currentPlayer);
  691. for(; i != gs->players.end(); i++)
  692. {
  693. 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
  694. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  695. gs->currentPlayer = i->first;
  696. {
  697. YourTurn yt;
  698. yt.player = i->first;
  699. *connections[i->first] << &yt;
  700. }
  701. //wait till turn is done
  702. boost::unique_lock<boost::mutex> lock(states.mx);
  703. while(states.players[i->first].makingTurn && !end2)
  704. {
  705. boost::posix_time::time_duration p;
  706. p = boost::posix_time::milliseconds(200);
  707. states.cv.timed_wait(lock,p);
  708. }
  709. }
  710. }
  711. }
  712. namespace CGH
  713. {
  714. using namespace std;
  715. void readItTo(ifstream & input, vector< vector<int> > & dest)
  716. {
  717. for(int j=0; j<7; ++j)
  718. {
  719. std::vector<int> pom;
  720. for(int g=0; g<j+1; ++g)
  721. {
  722. int hlp; input>>hlp;
  723. pom.push_back(hlp);
  724. }
  725. dest.push_back(pom);
  726. }
  727. }
  728. }
  729. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  730. {
  731. battleResult.set(NULL);
  732. std::vector<CStack*> & stacks = (curB->stacks);
  733. curB->tile = tile;
  734. curB->siege = 0; //TODO: add sieges
  735. curB->army1=army1;
  736. curB->army2=army2;
  737. curB->hero1=(hero1)?(hero1->id):(-1);
  738. curB->hero2=(hero2)?(hero2->id):(-1);
  739. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  740. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  741. curB->round = -2;
  742. curB->activeStack = -1;
  743. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  744. {
  745. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  746. //base luck/morale calculations
  747. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  748. if(hero1)
  749. {
  750. stacks.back()->morale = hero1->getCurrentMorale(i->first,false);
  751. stacks.back()->luck = hero1->getCurrentLuck(i->first,false);
  752. }
  753. else
  754. {
  755. stacks.back()->morale = 0;
  756. stacks.back()->luck = 0;
  757. }
  758. stacks[stacks.size()-1]->ID = stacks.size()-1;
  759. }
  760. //initialization of positions
  761. std::ifstream positions;
  762. positions.open("config" PATHSEPARATOR "battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  763. if(!positions.is_open())
  764. {
  765. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  766. }
  767. std::string dump;
  768. positions>>dump; positions>>dump;
  769. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight;
  770. CGH::readItTo(positions, attackerLoose);
  771. positions>>dump;
  772. CGH::readItTo(positions, defenderLoose);
  773. positions>>dump;
  774. positions>>dump;
  775. CGH::readItTo(positions, attackerTight);
  776. positions>>dump;
  777. CGH::readItTo(positions, defenderTight);
  778. positions.close();
  779. if(army1.formation)
  780. for(int b=0; b<army1.slots.size(); ++b) //tight
  781. {
  782. stacks[b]->position = attackerTight[army1.slots.size()-1][b];
  783. }
  784. else
  785. for(int b=0; b<army1.slots.size(); ++b) //loose
  786. {
  787. stacks[b]->position = attackerLoose[army1.slots.size()-1][b];
  788. }
  789. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  790. {
  791. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  792. //base luck/morale calculations
  793. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  794. if(hero2)
  795. {
  796. stacks.back()->morale = hero2->getCurrentMorale(i->first,false);
  797. stacks.back()->luck = hero2->getCurrentLuck(i->first,false);
  798. }
  799. else
  800. {
  801. stacks.back()->morale = 0;
  802. stacks.back()->luck = 0;
  803. }
  804. }
  805. if(army2.formation)
  806. for(int b=0; b<army2.slots.size(); ++b) //tight
  807. {
  808. stacks[b+army1.slots.size()]->position = defenderTight[army2.slots.size()-1][b];
  809. }
  810. else
  811. for(int b=0; b<army2.slots.size(); ++b) //loose
  812. {
  813. stacks[b+army1.slots.size()]->position = defenderLoose[army2.slots.size()-1][b];
  814. }
  815. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  816. {
  817. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  818. {
  819. stacks[g]->position += 1;
  820. }
  821. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  822. {
  823. stacks[g]->position -= 1;
  824. }
  825. }
  826. //adding war machines
  827. if(hero1)
  828. {
  829. if(hero1->getArt(13)) //ballista
  830. {
  831. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero1->tempOwner, stacks.size(), true, 255));
  832. stacks[stacks.size()-1]->position = 52;
  833. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  834. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  835. }
  836. if(hero1->getArt(14)) //ammo cart
  837. {
  838. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero1->tempOwner, stacks.size(), true, 255));
  839. stacks[stacks.size()-1]->position = 18;
  840. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  841. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  842. }
  843. if(hero1->getArt(15)) //first aid tent
  844. {
  845. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero1->tempOwner, stacks.size(), true, 255));
  846. stacks[stacks.size()-1]->position = 154;
  847. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  848. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  849. }
  850. }
  851. if(hero2)
  852. {
  853. if(hero2->getArt(13)) //ballista
  854. {
  855. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero2->tempOwner, stacks.size(), false, 255));
  856. stacks[stacks.size()-1]->position = 66;
  857. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  858. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  859. }
  860. if(hero2->getArt(14)) //ammo cart
  861. {
  862. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero2->tempOwner, stacks.size(), false, 255));
  863. stacks[stacks.size()-1]->position = 32;
  864. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  865. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  866. }
  867. if(hero2->getArt(15)) //first aid tent
  868. {
  869. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero2->tempOwner, stacks.size(), false, 255));
  870. stacks[stacks.size()-1]->position = 168;
  871. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  872. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  873. }
  874. }
  875. //war machiens added
  876. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  877. //randomize obstacles
  878. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  879. std::vector<int> possibleObstacles;
  880. for(int i=0; i<BFIELD_SIZE; ++i)
  881. {
  882. if(i%17 < 4 || i%17 > 12)
  883. {
  884. obAv[i] = false;
  885. }
  886. else
  887. {
  888. obAv[i] = true;
  889. }
  890. }
  891. int terType = gs->battleGetBattlefieldType(tile);
  892. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  893. {
  894. if(g->second.allowedTerrains[terType] == '1')
  895. {
  896. possibleObstacles.push_back(g->first);
  897. }
  898. }
  899. srand(time(NULL));
  900. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  901. {
  902. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  903. while(toBlock>0)
  904. {
  905. CObstacleInstance coi;
  906. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  907. coi.pos = rand()%BFIELD_SIZE;
  908. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  909. bool badObstacle = false;
  910. for(int b=0; b<block.size(); ++b)
  911. {
  912. if(!obAv[block[b]])
  913. {
  914. badObstacle = true;
  915. break;
  916. }
  917. }
  918. if(badObstacle) continue;
  919. //obstacle can be placed
  920. curB->obstacles.push_back(coi);
  921. for(int b=0; b<block.size(); ++b)
  922. {
  923. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  924. obAv[block[b]] = false;
  925. }
  926. toBlock -= block.size();
  927. }
  928. }
  929. //block engaged players
  930. if(hero1->tempOwner<PLAYER_LIMIT)
  931. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  932. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  933. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  934. //send info about battles
  935. BattleStart bs;
  936. bs.info = curB;
  937. sendAndApply(&bs);
  938. }
  939. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  940. {
  941. //checking winning condition
  942. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  943. hasStack[0] = hasStack[1] = false;
  944. for(int b = 0; b<stacks.size(); ++b)
  945. {
  946. if(stacks[b]->alive() && !vstd::contains(stacks[b]->abilities,SIEGE_WEAPON))
  947. {
  948. hasStack[1-stacks[b]->attackerOwned] = true;
  949. }
  950. }
  951. if(!hasStack[0] || !hasStack[1]) //somebody has won
  952. {
  953. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  954. br->result = 0;
  955. br->winner = hasStack[1]; //fleeing side loses
  956. gs->curB->calculateCasualties(br->casualties);
  957. battleResult.set(br);
  958. }
  959. }
  960. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  961. {
  962. if(!vstd::contains(h->artifWorn,17))
  963. return; //hero hasn't spellbok
  964. ChangeSpells cs;
  965. cs.hid = h->id;
  966. cs.learn = true;
  967. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  968. {
  969. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  970. {
  971. if(!vstd::contains(h->spells,t->spells[i][j]))
  972. cs.spells.insert(t->spells[i][j]);
  973. }
  974. }
  975. if(cs.spells.size())
  976. sendAndApply(&cs);
  977. }
  978. void CGameHandler::setBlockVis(int objid, bool bv)
  979. {
  980. SetObjectProperty sop(objid,2,bv);
  981. sendAndApply(&sop);
  982. }
  983. void CGameHandler::removeObject(int objid)
  984. {
  985. RemoveObject ro;
  986. ro.id = objid;
  987. sendAndApply(&ro);
  988. }
  989. void CGameHandler::setAmount(int objid, ui32 val)
  990. {
  991. SetObjectProperty sop(objid,3,val);
  992. sendAndApply(&sop);
  993. }
  994. void CGameHandler::moveHero(si32 hid, int3 dst, ui8 instant, ui8 asker)
  995. {
  996. bool blockvis = false;
  997. const CGHeroInstance *h = getHero(hid);
  998. 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)
  999. )
  1000. {
  1001. tlog1 << "Illegal call to move hero!\n";
  1002. return;
  1003. }
  1004. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1005. int3 hmpos = dst + int3(-1,0,0);
  1006. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1007. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1008. //result structure for start - movement failed, no move points used
  1009. TryMoveHero tmh;
  1010. tmh.id = hid;
  1011. tmh.start = h->pos;
  1012. tmh.end = dst;
  1013. tmh.result = 0;
  1014. tmh.movePoints = h->movement;
  1015. //check if destination tile is available
  1016. if( t.tertype == rock
  1017. || (!h->canWalkOnSea() && t.tertype == water)
  1018. || (t.blocked && !t.visitable) //tile is blocked andnot visitable
  1019. )
  1020. {
  1021. tlog2 << "Cannot move hero, destination tile is blocked!\n";
  1022. sendAndApply(&tmh);
  1023. return;
  1024. }
  1025. //checks for standard movement
  1026. if(!instant)
  1027. {
  1028. if( (distance(h->pos,dst)>=1.5) //tiles are not neighouring
  1029. || (h->movement < cost && h->movement < 100) //lack of movement points
  1030. )
  1031. {
  1032. tlog2 << "Cannot move hero, not enough move points or tiles are not neighbouring!\n";
  1033. sendAndApply(&tmh);
  1034. return;
  1035. }
  1036. //check if there is blocking visitable object
  1037. blockvis = false;
  1038. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1039. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1040. {
  1041. if(obj != h && obj->blockVisit)
  1042. {
  1043. blockvis = true;
  1044. break;
  1045. }
  1046. }
  1047. //we start moving
  1048. if(blockvis)//interaction with blocking object (like resources)
  1049. {
  1050. sendAndApply(&tmh);
  1051. //failed to move to that tile but we visit object
  1052. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1053. {
  1054. if (obj->blockVisit)
  1055. {
  1056. obj->onHeroVisit(h);
  1057. }
  1058. }
  1059. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1060. return;
  1061. }
  1062. else //normal move
  1063. {
  1064. tmh.result = 1;
  1065. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1066. {
  1067. obj->onHeroLeave(h);
  1068. }
  1069. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1070. sendAndApply(&tmh);
  1071. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1072. //call objects if they are visited
  1073. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1074. {
  1075. obj->onHeroVisit(h);
  1076. }
  1077. }
  1078. tlog5 << "Movement end!\n";
  1079. }
  1080. else //instant move - teleportation
  1081. {
  1082. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1083. {
  1084. if(obj->ID==HEROI_TYPE)
  1085. {
  1086. if(obj->tempOwner==h->tempOwner)
  1087. return;//TODO: exchange
  1088. //TODO: check for ally
  1089. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1090. startBattleI(&h->army,&dh->army,dst,h,dh,0);
  1091. return;
  1092. }
  1093. }
  1094. tmh.result = instant+1;
  1095. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1096. sendAndApply(&tmh);
  1097. }
  1098. }
  1099. void CGameHandler::setOwner(int objid, ui8 owner)
  1100. {
  1101. SetObjectProperty sop(objid,1,owner);
  1102. sendAndApply(&sop);
  1103. }
  1104. void CGameHandler::setHoverName(int objid, MetaString* name)
  1105. {
  1106. SetHoverName shn(objid, *name);
  1107. sendAndApply(&shn);
  1108. }
  1109. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1110. {
  1111. sendToAllClients(iw);
  1112. }
  1113. void CGameHandler::showYesNoDialog( YesNoDialog *iw, const CFunctionList<void(ui32)> &callback )
  1114. {
  1115. ask(iw,iw->player,callback);
  1116. }
  1117. void CGameHandler::showSelectionDialog(SelectionDialog *iw, const CFunctionList<void(ui32)> &callback)
  1118. {
  1119. ask(iw,iw->player,callback);
  1120. }
  1121. int CGameHandler::getCurrentPlayer()
  1122. {
  1123. return gs->currentPlayer;
  1124. }
  1125. void CGameHandler::giveResource(int player, int which, int val)
  1126. {
  1127. SetResource sr;
  1128. sr.player = player;
  1129. sr.resid = which;
  1130. sr.val = (gs->players.find(player)->second.resources[which]+val);
  1131. sendAndApply(&sr);
  1132. }
  1133. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1134. {
  1135. sendToAllClients(comp);
  1136. }
  1137. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1138. {
  1139. HeroVisitCastle vc;
  1140. vc.hid = heroID;
  1141. vc.tid = obj;
  1142. vc.flags |= 1;
  1143. sendAndApply(&vc);
  1144. giveSpells(getTown(obj),getHero(heroID));
  1145. }
  1146. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1147. {
  1148. HeroVisitCastle vc;
  1149. vc.hid = heroID;
  1150. vc.tid = obj;
  1151. sendAndApply(&vc);
  1152. }
  1153. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1154. {
  1155. const CGHeroInstance* h = getHero(hid);
  1156. const CArtifact &art = VLC->arth->artifacts[artid];
  1157. SetHeroArtifacts sha;
  1158. sha.hid = hid;
  1159. sha.artifacts = h->artifacts;
  1160. sha.artifWorn = h->artifWorn;
  1161. if(position<0)
  1162. {
  1163. if(position == -2)
  1164. {
  1165. int i;
  1166. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1167. {
  1168. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1169. {
  1170. //we've found a free suitable slot
  1171. sha.artifWorn[art.possibleSlots[i]] = artid;
  1172. break;
  1173. }
  1174. }
  1175. if(i == art.possibleSlots.size()) //if haven't find proper slot, use backpack
  1176. sha.artifacts.push_back(artid);
  1177. }
  1178. else //should be -1 => put artifact into backpack
  1179. {
  1180. sha.artifacts.push_back(artid);
  1181. }
  1182. }
  1183. else
  1184. {
  1185. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1186. {
  1187. sha.artifWorn[position] = artid;
  1188. }
  1189. else
  1190. {
  1191. sha.artifacts.push_back(artid);
  1192. }
  1193. }
  1194. sendAndApply(&sha);
  1195. }
  1196. void CGameHandler::startBattleI(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb) //use hero=NULL for no hero
  1197. {
  1198. boost::thread(boost::bind(&CGameHandler::startBattle,this,*(CCreatureSet *)army1,*(CCreatureSet *)army2,tile,(CGHeroInstance *)hero1,(CGHeroInstance *)hero2,cb));
  1199. }
  1200. void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1201. {
  1202. CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1203. startBattleI(&h->army,&army,tile,h,NULL,cb);
  1204. //battle(&h->army,army,tile,h,NULL);
  1205. }
  1206. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1207. {
  1208. ChangeSpells cs;
  1209. cs.hid = hid;
  1210. cs.spells = spells;
  1211. cs.learn = give;
  1212. sendAndApply(&cs);
  1213. }
  1214. int CGameHandler::getSelectedHero()
  1215. {
  1216. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1217. }
  1218. void CGameHandler::setObjProperty( int objid, int prop, int val )
  1219. {
  1220. SetObjectProperty sob;
  1221. sob.id = objid;
  1222. sob.what = prop;
  1223. sob.val = val;
  1224. sendAndApply(&sob);
  1225. }
  1226. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1227. {
  1228. SystemMessage sm;
  1229. sm.text = message;
  1230. c << &sm;
  1231. }
  1232. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1233. {
  1234. sendAndApply(bonus);
  1235. }
  1236. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1237. {
  1238. sendAndApply(smp);
  1239. }
  1240. void CGameHandler::setManaPoints( int hid, int val )
  1241. {
  1242. SetMana sm;
  1243. sm.hid = hid;
  1244. sm.val = val;
  1245. sendAndApply(&sm);
  1246. }
  1247. void CGameHandler::giveHero( int id, int player )
  1248. {
  1249. GiveHero gh;
  1250. gh.id = id;
  1251. gh.player = player;
  1252. sendAndApply(&gh);
  1253. }
  1254. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1255. {
  1256. ChangeObjPos cop;
  1257. cop.objid = objid;
  1258. cop.nPos = newPos;
  1259. cop.flags = flags;
  1260. sendAndApply(&cop);
  1261. }
  1262. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1263. {
  1264. gsm.lock();
  1265. sel->id = QID;
  1266. callbacks[QID] = callback;
  1267. states.addQuery(player,QID);
  1268. QID++;
  1269. sendAndApply(sel);
  1270. gsm.unlock();
  1271. }
  1272. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1273. {
  1274. gsm.lock();
  1275. sel->id = QID;
  1276. callbacks[QID] = callback;
  1277. states.addQuery(player,QID);
  1278. sendToAllClients(sel);
  1279. QID++;
  1280. gsm.unlock();
  1281. }
  1282. void CGameHandler::sendToAllClients( CPackForClient * info )
  1283. {
  1284. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1285. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1286. {
  1287. (*i)->wmx->lock();
  1288. **i << info;
  1289. (*i)->wmx->unlock();
  1290. }
  1291. }
  1292. void CGameHandler::sendAndApply( CPackForClient * info )
  1293. {
  1294. gs->apply(info);
  1295. sendToAllClients(info);
  1296. }
  1297. void CGameHandler::save( const std::string &fname )
  1298. {
  1299. {
  1300. tlog0 << "Ordering clients to serialize...\n";
  1301. SaveGame sg(fname);
  1302. //TODO: uncomment when client saving is ready
  1303. //sendToAllClients(&sg);
  1304. }
  1305. {
  1306. tlog0 << "Serializing game info...\n";
  1307. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vlgm1");
  1308. char hlp[8] = "VCMISVG";
  1309. save << hlp << version << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  1310. }
  1311. {
  1312. tlog0 << "Serializing server info...\n";
  1313. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vsgm1");
  1314. save << *this;
  1315. }
  1316. tlog0 << "Game has been succesfully saved!\n";
  1317. }
  1318. void CGameHandler::close()
  1319. {
  1320. tlog0 << "We have been requested to close.\n";
  1321. exit(0);
  1322. }
  1323. void CGameHandler::arrangeStacks(si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val)
  1324. {
  1325. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  1326. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  1327. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  1328. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  1329. if(what==1) //swap
  1330. {
  1331. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  1332. //if one of them is empty, remove entry
  1333. if(!S1.slots[p1].second)
  1334. S1.slots.erase(p1);
  1335. if(!S2.slots[p2].second)
  1336. S2.slots.erase(p2);
  1337. }
  1338. else if(what==2)//merge
  1339. {
  1340. if(S1.slots[p1].first != S2.slots[p2].first) //not same creature
  1341. {
  1342. complain("Cannot merge different creatures stacks!");
  1343. return;
  1344. }
  1345. S2.slots[p2].second += S1.slots[p1].second;
  1346. S1.slots.erase(p1);
  1347. }
  1348. else if(what==3) //split
  1349. {
  1350. //general conditions checking
  1351. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1352. || (val<1 && complain("no creatures to split")) )
  1353. {
  1354. return;
  1355. }
  1356. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1357. {
  1358. int total = S1.slots[p1].second + S2.slots[p2].second;
  1359. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1360. || (S2.slots[p2].first != S1.slots[p1].first && complain("Cannot rebalance different creatures stacks!"))
  1361. )
  1362. {
  1363. return;
  1364. }
  1365. S2.slots[p2].second = val;
  1366. S1.slots[p1].second = total - val;
  1367. }
  1368. else //split one stack to the two
  1369. {
  1370. if(S1.slots[p1].second < val)//not enough creatures
  1371. {
  1372. complain("Cannot split that stack, not enough creatures!");
  1373. return;
  1374. }
  1375. S2.slots[p2].first = S1.slots[p1].first;
  1376. S2.slots[p2].second = val;
  1377. S1.slots[p1].second -= val;
  1378. }
  1379. if(!S1.slots[p1].second) //if we've moved all creatures
  1380. S1.slots.erase(p1);
  1381. }
  1382. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  1383. || (s2->needsLastStack() && !S2.slots.size())
  1384. )
  1385. {
  1386. complain("Cannot take the last stack!");
  1387. return; //leave without applying changes to garrison
  1388. }
  1389. //apply changes
  1390. SetGarrisons sg;
  1391. sg.garrs[id1] = S1;
  1392. if(s1 != s2)
  1393. sg.garrs[id2] = S2;
  1394. sendAndApply(&sg);
  1395. }
  1396. int CGameHandler::getPlayerAt( CConnection *c ) const
  1397. {
  1398. std::set<int> all;
  1399. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1400. if(i->second == c)
  1401. all.insert(i->first);
  1402. switch(all.size())
  1403. {
  1404. case 0:
  1405. return 255;
  1406. case 1:
  1407. return *all.begin();
  1408. default:
  1409. {
  1410. //if we have more than one player at this connection, try to pick active one
  1411. if(vstd::contains(all,int(gs->currentPlayer)))
  1412. return gs->currentPlayer;
  1413. else
  1414. return 253; //cannot say which player is it
  1415. }
  1416. }
  1417. }
  1418. void CGameHandler::disbandCreature(si32 id, ui8 pos)
  1419. {
  1420. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  1421. if(!vstd::contains(s1->army.slots,pos))
  1422. {
  1423. complain("Illegal call to disbandCreature - no such stack in army!");
  1424. return;
  1425. }
  1426. s1->army.slots.erase(pos);
  1427. SetGarrisons sg;
  1428. sg.garrs[id] = s1->army;
  1429. sendAndApply(&sg);
  1430. }
  1431. void CGameHandler::buildStructure(si32 tid, si32 bid)
  1432. {
  1433. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1434. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  1435. if(gs->canBuildStructure(t,bid) != 7)
  1436. {
  1437. complain("Cannot build that building!");
  1438. return;
  1439. }
  1440. NewStructures ns;
  1441. ns.tid = tid;
  1442. if(bid>36) //upg dwelling
  1443. {
  1444. if(t->getHordeLevel(0) == (bid-37))
  1445. ns.bid.insert(19);
  1446. else if(t->getHordeLevel(1) == (bid-37))
  1447. ns.bid.insert(25);
  1448. }
  1449. else if(bid >= 30) //bas. dwelling
  1450. {
  1451. SetAvailableCreatures ssi;
  1452. ssi.tid = tid;
  1453. ssi.creatures = t->strInfo.creatures;
  1454. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  1455. sendAndApply(&ssi);
  1456. }
  1457. ns.bid.insert(bid);
  1458. ns.builded = t->builded + 1;
  1459. sendAndApply(&ns);
  1460. SetResources sr;
  1461. sr.player = t->tempOwner;
  1462. sr.res = gs->getPlayer(t->tempOwner)->resources;
  1463. for(int i=0;i<7;i++)
  1464. sr.res[i]-=b->resources[i];
  1465. sendAndApply(&sr);
  1466. if(bid<5) //it's mage guild
  1467. {
  1468. if(t->visitingHero)
  1469. giveSpells(t,t->visitingHero);
  1470. if(t->garrisonHero)
  1471. giveSpells(t,t->garrisonHero);
  1472. }
  1473. }
  1474. void CGameHandler::sendMessageToAll( const std::string &message )
  1475. {
  1476. SystemMessage sm;
  1477. sm.text = message;
  1478. sendToAllClients(&sm);
  1479. }
  1480. void CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  1481. {
  1482. si32 ser = -1;
  1483. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  1484. //verify
  1485. bool found = false;
  1486. typedef std::pair<const int,int> Parka;
  1487. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  1488. {
  1489. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  1490. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  1491. {
  1492. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  1493. ser = av->first;
  1494. break;
  1495. }
  1496. }
  1497. int slot = t->army.getSlotFor(crid);
  1498. if(!found || //no such creature
  1499. cram > VLC->creh->creatures[crid].maxAmount(gs->getPlayer(t->tempOwner)->resources) || //lack of resources
  1500. cram<=0 ||
  1501. slot<0 )
  1502. return;
  1503. //recruit
  1504. SetResources sr;
  1505. sr.player = t->tempOwner;
  1506. for(int i=0;i<RESOURCE_QUANTITY;i++)
  1507. sr.res[i] = gs->getPlayer(t->tempOwner)->resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  1508. SetAvailableCreatures sac;
  1509. sac.tid = objid;
  1510. sac.creatures = t->strInfo.creatures;
  1511. sac.creatures[ser] -= cram;
  1512. SetGarrisons sg;
  1513. sg.garrs[objid] = t->army;
  1514. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  1515. {
  1516. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  1517. }
  1518. else //add creatures to a already existing stack
  1519. {
  1520. sg.garrs[objid].slots[slot].second += cram;
  1521. }
  1522. sendAndApply(&sr);
  1523. sendAndApply(&sac);
  1524. sendAndApply(&sg);
  1525. }
  1526. void CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  1527. {
  1528. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  1529. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  1530. int player = obj->tempOwner;
  1531. int crQuantity = obj->army.slots[pos].second;
  1532. //check if upgrade is possible
  1533. if(ui.oldID<0 || !vstd::contains(ui.newID,upgID))
  1534. return;
  1535. //check if player has enough resources
  1536. for(int i=0;i<ui.cost.size();i++)
  1537. {
  1538. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1539. {
  1540. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  1541. return;
  1542. }
  1543. }
  1544. //take resources
  1545. for(int i=0;i<ui.cost.size();i++)
  1546. {
  1547. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1548. {
  1549. SetResource sr;
  1550. sr.player = player;
  1551. sr.resid = j->first;
  1552. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  1553. sendAndApply(&sr);
  1554. }
  1555. }
  1556. //upgrade creature
  1557. SetGarrisons sg;
  1558. sg.garrs[objid] = obj->army;
  1559. sg.garrs[objid].slots[pos].first = upgID;
  1560. sendAndApply(&sg);
  1561. }
  1562. void CGameHandler::garrisonSwap(si32 tid)
  1563. {
  1564. CGTownInstance *town = gs->getTown(tid);
  1565. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  1566. {
  1567. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  1568. while(!cso.slots.empty())//while there are unmoved creatures
  1569. {
  1570. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  1571. if(pos<0)
  1572. return;
  1573. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  1574. {
  1575. csn.slots[pos].second += cso.slots.begin()->second.second;
  1576. }
  1577. else //move stack on the free pos
  1578. {
  1579. csn.slots[pos].first = cso.slots.begin()->second.first;
  1580. csn.slots[pos].second = cso.slots.begin()->second.second;
  1581. }
  1582. cso.slots.erase(cso.slots.begin());
  1583. }
  1584. SetGarrisons sg;
  1585. sg.garrs[town->visitingHero->id] = csn;
  1586. sg.garrs[town->id] = csn;
  1587. sendAndApply(&sg);
  1588. SetHeroesInTown intown;
  1589. intown.tid = tid;
  1590. intown.visiting = -1;
  1591. intown.garrison = town->visitingHero->id;
  1592. sendAndApply(&intown);
  1593. }
  1594. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  1595. {
  1596. SetHeroesInTown intown;
  1597. intown.tid = tid;
  1598. intown.garrison = -1;
  1599. intown.visiting = town->garrisonHero->id;
  1600. sendAndApply(&intown);
  1601. //town will be empty
  1602. SetGarrisons sg;
  1603. sg.garrs[tid] = CCreatureSet();
  1604. sendAndApply(&sg);
  1605. }
  1606. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  1607. {
  1608. SetGarrisons sg;
  1609. sg.garrs[town->id] = town->visitingHero->army;
  1610. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  1611. SetHeroesInTown intown;
  1612. intown.tid = tid;
  1613. intown.garrison = town->visitingHero->id;
  1614. intown.visiting = town->garrisonHero->id;
  1615. sendAndApply(&intown);
  1616. sendAndApply(&sg);
  1617. }
  1618. else
  1619. {
  1620. complain("Cannot swap garrison hero!");
  1621. }
  1622. }
  1623. void CGameHandler::swapArtifacts( si32 hid1, si32 hid2, ui16 slot1, ui16 slot2 )
  1624. {
  1625. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  1626. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  1627. return;
  1628. const CArtifact *a1 = h1->getArt(slot1),
  1629. *a2=h2->getArt(slot2);
  1630. if(a1 && slot2<19 && !vstd::contains(a1->possibleSlots,slot2)
  1631. || a2 && slot1<19 && !vstd::contains(a2->possibleSlots,slot1)
  1632. )
  1633. {
  1634. //artifact doesn't fit dst slot
  1635. complain("Cannot swap artifacts!");
  1636. return;
  1637. }
  1638. SetHeroArtifacts sha;
  1639. sha.hid = hid1;
  1640. sha.artifacts = h1->artifacts;
  1641. sha.artifWorn = h1->artifWorn;
  1642. sha.setArtAtPos(slot1,h2->getArtAtPos(slot2));
  1643. if(h1 == h2) sha.setArtAtPos(slot2,h1->getArtAtPos(slot1));
  1644. sendAndApply(&sha);
  1645. if(hid1 != hid2)
  1646. {
  1647. sha.hid = hid2;
  1648. sha.artifacts = h2->artifacts;
  1649. sha.artifWorn = h2->artifWorn;
  1650. sha.setArtAtPos(slot2,h1->getArtAtPos(slot1));
  1651. sendAndApply(&sha);
  1652. }
  1653. }
  1654. void CGameHandler::buyArtifact( ui32 hid, si32 aid )
  1655. {
  1656. CGHeroInstance *hero = gs->getHero(hid);
  1657. CGTownInstance *town = hero->visitedTown;
  1658. if(aid==0) //spellbook
  1659. {
  1660. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  1661. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  1662. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  1663. )
  1664. return;
  1665. giveResource(hero->getOwner(),6,-500);
  1666. giveHeroArtifact(0,hid,17);
  1667. giveSpells(town,hero);
  1668. }
  1669. else if(aid < 7 && aid > 3) //war machine
  1670. {
  1671. int price = VLC->arth->artifacts[aid].price;
  1672. if(vstd::contains(hero->artifWorn,ui16(9+aid)) //hero already has this machine
  1673. || !vstd::contains(town->builtBuildings,si32(16)) //no blackismith
  1674. || gs->getPlayer(hero->getOwner())->resources[6] < price //no gold
  1675. || town->town->warMachine!= aid ) //this machine is not available here (//TODO: support ballista yard in stronghold)
  1676. {
  1677. return;
  1678. }
  1679. giveResource(hero->getOwner(),6,-price);
  1680. giveHeroArtifact(aid,hid,9+aid);
  1681. }
  1682. }
  1683. void CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  1684. {
  1685. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  1686. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  1687. uzysk /= gs->resVals[id2];
  1688. SetResource sr;
  1689. sr.player = player;
  1690. sr.resid = id1;
  1691. sr.val = gs->getPlayer(player)->resources[id1] - val;
  1692. sendAndApply(&sr);
  1693. sr.resid = id2;
  1694. sr.val = gs->getPlayer(player)->resources[id2] + (int)uzysk;
  1695. sendAndApply(&sr);
  1696. }
  1697. void CGameHandler::setFormation( si32 hid, ui8 formation )
  1698. {
  1699. gs->getHero(hid)->army.formation = formation;
  1700. }
  1701. void CGameHandler::hireHero( ui32 tid, ui8 hid )
  1702. {
  1703. CGTownInstance *t = gs->getTown(tid);
  1704. if(!vstd::contains(t->builtBuildings,5) //no tavern in the town
  1705. || gs->getPlayer(t->tempOwner)->resources[6]<2500 //not enough gold
  1706. || t->visitingHero //there is visiting hero - no place
  1707. || gs->getPlayer(t->tempOwner)->heroes.size()>7 //8 hero limit
  1708. )
  1709. return;
  1710. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  1711. HeroRecruited hr;
  1712. hr.tid = tid;
  1713. hr.hid = nh->subID;
  1714. hr.player = t->tempOwner;
  1715. hr.tile = t->pos - int3(1,0,0);
  1716. sendAndApply(&hr);
  1717. SetAvailableHeroes sah;
  1718. (hid ? sah.hid2 : sah.hid1) = gs->hpool.pickHeroFor(false,t->tempOwner,t->town)->subID;
  1719. (hid ? sah.hid1 : sah.hid2) = gs->getPlayer(t->tempOwner)->availableHeroes[!hid]->subID;
  1720. sah.player = t->tempOwner;
  1721. sah.flags = hid+1;
  1722. sendAndApply(&sah);
  1723. SetResource sr;
  1724. sr.player = t->tempOwner;
  1725. sr.resid = 6;
  1726. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  1727. sendAndApply(&sr);
  1728. giveSpells(t,nh);
  1729. }
  1730. void CGameHandler::queryReply( ui32 qid, ui32 answer )
  1731. {
  1732. gsm.lock();
  1733. CFunctionList<void(ui32)> callb = callbacks[qid];
  1734. callbacks.erase(qid);
  1735. gsm.unlock();
  1736. callb(answer);
  1737. }
  1738. void CGameHandler::makeBattleAction( BattleAction &ba )
  1739. {
  1740. switch(ba.actionType)
  1741. {
  1742. case 2: //walk
  1743. {
  1744. sendAndApply(&StartAction(ba)); //start movement
  1745. moveStack(ba.stackNumber,ba.destinationTile); //move
  1746. sendAndApply(&EndAction());
  1747. break;
  1748. }
  1749. case 3: //defend
  1750. case 8: //wait
  1751. {
  1752. sendAndApply(&StartAction(ba));
  1753. sendAndApply(&EndAction());
  1754. break;
  1755. }
  1756. case 4: //retreat/flee
  1757. {
  1758. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  1759. //TODO: calculate casualties
  1760. //TODO: remove retreating hero from map and place it in recruitment list
  1761. BattleResult *br = new BattleResult;
  1762. br->result = 1;
  1763. br->winner = !ba.side; //fleeing side loses
  1764. gs->curB->calculateCasualties(br->casualties);
  1765. giveExp(*br);
  1766. battleResult.set(br);
  1767. break;
  1768. }
  1769. case 6: //walk or attack
  1770. {
  1771. sendAndApply(&StartAction(ba)); //start movement and attack
  1772. moveStack(ba.stackNumber,ba.destinationTile);
  1773. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1774. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  1775. if(curStack->position != ba.destinationTile) //we wasn't able to reach destination tile
  1776. {
  1777. tlog3<<"We cannot move this stack to its destination "<<curStack->creature->namePl<<std::endl;
  1778. }
  1779. if(!stackAtEnd)
  1780. {
  1781. tlog3 << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  1782. break;
  1783. }
  1784. ui16 curpos = curStack->position,
  1785. enemypos = stackAtEnd->position;
  1786. if( !(
  1787. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  1788. || (curStack->creature->isDoubleWide() //back <=> front
  1789. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  1790. || (stackAtEnd->creature->isDoubleWide() //front <=> back
  1791. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1792. || (stackAtEnd->creature->isDoubleWide() && curStack->creature->isDoubleWide()//back <=> back
  1793. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1794. )
  1795. )
  1796. {
  1797. tlog3 << "Attack cannot be performed!";
  1798. sendAndApply(&EndAction());
  1799. break;
  1800. }
  1801. //attack
  1802. BattleAttack bat;
  1803. prepareAttack(bat,curStack,stackAtEnd);
  1804. sendAndApply(&bat);
  1805. //counterattack
  1806. if(!vstd::contains(curStack->abilities,NO_ENEMY_RETALIATION)
  1807. && stackAtEnd->alive()
  1808. && stackAtEnd->counterAttacks
  1809. && !vstd::contains(stackAtEnd->abilities, SIEGE_WEAPON)) //TODO: support for multiple retaliatons per turn
  1810. {
  1811. prepareAttack(bat,stackAtEnd,curStack);
  1812. bat.flags |= 2;
  1813. sendAndApply(&bat);
  1814. }
  1815. //second attack
  1816. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  1817. && curStack->alive()
  1818. && stackAtEnd->alive() )
  1819. {
  1820. bat.flags = 0;
  1821. prepareAttack(bat,curStack,stackAtEnd);
  1822. sendAndApply(&bat);
  1823. }
  1824. sendAndApply(&EndAction());
  1825. break;
  1826. }
  1827. case 7: //shoot
  1828. {
  1829. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1830. *destStack= gs->curB->getStackT(ba.destinationTile);
  1831. if(!curStack //our stack exists
  1832. || !destStack //there is a stack at destination tile
  1833. || !curStack->shots //stack has shots
  1834. || gs->curB->isStackBlocked(curStack->ID) //we are not blocked
  1835. || !vstd::contains(curStack->abilities,SHOOTER) //our stack is shooting unit
  1836. )
  1837. break;
  1838. for(int g=0; g<curStack->effects.size(); ++g)
  1839. {
  1840. if(61 == curStack->effects[g].id) //forgetfulness
  1841. break;
  1842. }
  1843. sendAndApply(&StartAction(ba)); //start shooting
  1844. BattleAttack bat;
  1845. prepareAttack(bat,curStack,destStack);
  1846. bat.flags |= 1;
  1847. sendAndApply(&bat);
  1848. if(vstd::contains(curStack->abilities,TWICE_ATTACK) //if unit shots twice let's make another shot
  1849. && curStack->alive()
  1850. && destStack->alive()
  1851. && curStack->shots
  1852. )
  1853. {
  1854. prepareAttack(bat,curStack,destStack);
  1855. sendAndApply(&bat);
  1856. }
  1857. sendAndApply(&EndAction());
  1858. break;
  1859. }
  1860. }
  1861. battleMadeAction.setn(true);
  1862. }
  1863. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  1864. {
  1865. bool cheated=true;
  1866. sendAndApply(&PlayerMessage(player,message));
  1867. if(message == "vcmiistari") //give all spells and 999 mana
  1868. {
  1869. SetMana sm;
  1870. ChangeSpells cs;
  1871. cs.learn = 1;
  1872. for(int i=0;i<VLC->spellh->spells.size();i++)
  1873. {
  1874. if(!VLC->spellh->spells[i].creatureAbility)
  1875. cs.spells.insert(i);
  1876. }
  1877. sm.hid = cs.hid = gs->players[player].currentSelection;
  1878. sm.val = 999;
  1879. if(gs->getHero(cs.hid))
  1880. {
  1881. sendAndApply(&cs);
  1882. sendAndApply(&sm);
  1883. }
  1884. }
  1885. else if(message == "vcmiainur") //gives 5 archangels into each slot
  1886. {
  1887. SetGarrisons sg;
  1888. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1889. if(!hero) return;
  1890. sg.garrs[hero->id] = hero->army;
  1891. for(int i=0;i<7;i++)
  1892. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  1893. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  1894. sendAndApply(&sg);
  1895. }
  1896. else if(message == "vcmiangband") //gives 10 black knightinto each slot
  1897. {
  1898. SetGarrisons sg;
  1899. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1900. if(!hero) return;
  1901. sg.garrs[hero->id] = hero->army;
  1902. for(int i=0;i<7;i++)
  1903. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  1904. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  1905. sendAndApply(&sg);
  1906. }
  1907. else if(message == "vcminoldor") //all war machines
  1908. {
  1909. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1910. if(!hero) return;
  1911. SetHeroArtifacts sha;
  1912. sha.hid = hero->id;
  1913. sha.artifacts = hero->artifacts;
  1914. sha.artifWorn = hero->artifWorn;
  1915. sha.artifWorn[13] = 4;
  1916. sha.artifWorn[14] = 5;
  1917. sha.artifWorn[15] = 6;
  1918. sendAndApply(&sha);
  1919. }
  1920. else if(message == "vcminahar") //1000000 movement points
  1921. {
  1922. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1923. if(!hero) return;
  1924. SetMovePoints smp;
  1925. smp.hid = hero->id;
  1926. smp.val = 1000000;
  1927. sendAndApply(&smp);
  1928. }
  1929. else if(message == "vcmiformenos") //give resources
  1930. {
  1931. SetResources sr;
  1932. sr.player = player;
  1933. sr.res = gs->getPlayer(player)->resources;
  1934. for(int i=0;i<7;i++)
  1935. sr.res[i] += 100;
  1936. sr.res[6] += 19900;
  1937. sendAndApply(&sr);
  1938. }
  1939. else if(message == "vcmieagles") //reveal FoW
  1940. {
  1941. FoWChange fc;
  1942. fc.player = player;
  1943. for(int i=0;i<gs->map->width;i++)
  1944. for(int j=0;j<gs->map->height;j++)
  1945. for(int k=0;k<gs->map->twoLevel+1;k++)
  1946. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  1947. fc.tiles.insert(int3(i,j,k));
  1948. sendAndApply(&fc);
  1949. }
  1950. else if(message == "vcmiglorfindel")
  1951. {
  1952. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1953. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  1954. }
  1955. else
  1956. cheated = false;
  1957. if(cheated)
  1958. {
  1959. sendAndApply(&SystemMessage("CHEATER!!!"));
  1960. }
  1961. }
  1962. void CGameHandler::makeCustomAction( BattleAction &ba )
  1963. {
  1964. switch(ba.actionType)
  1965. {
  1966. case 1: //hero casts spell
  1967. {
  1968. CGHeroInstance *h = (ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  1969. if(!h)
  1970. {
  1971. tlog2 << "Wrong caster!\n";
  1972. return;
  1973. }
  1974. if(ba.additionalInfo >= VLC->spellh->spells.size())
  1975. {
  1976. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  1977. return;
  1978. }
  1979. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  1980. ui8 skill = 0; //skill level
  1981. if(s->fire)
  1982. skill = std::max(skill,h->getSecSkillLevel(14));
  1983. if(s->air)
  1984. skill = std::max(skill,h->getSecSkillLevel(15));
  1985. if(s->water)
  1986. skill = std::max(skill,h->getSecSkillLevel(16));
  1987. if(s->earth)
  1988. skill = std::max(skill,h->getSecSkillLevel(17));
  1989. //TODO: skill level may be different on special terrain
  1990. if( !(vstd::contains(h->spells,ba.additionalInfo)) //hero doesn't know this spell
  1991. || (h->mana < s->costs[skill]) //not enough mana
  1992. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  1993. || (gs->curB->castedSpells[ba.side])
  1994. )
  1995. {
  1996. tlog2 << "Spell cannot be casted!\n";
  1997. return;
  1998. }
  1999. sendAndApply(&StartAction(ba)); //start spell casting
  2000. //TODO: check resistances
  2001. #define SPELL_CAST_TEMPLATE_1(NUMBER, DURATION) SetStackEffect sse; \
  2002. if(getSchoolLevel(h,s) < 3) /*not expert */ \
  2003. { \
  2004. sse.stacks.insert(gs->curB->getStackT(ba.destinationTile)->ID); \
  2005. sse.effect.id = (NUMBER); \
  2006. sse.effect.level = getSchoolLevel(h,s); \
  2007. sse.effect.turnsRemain = (DURATION); /*! - any duration */ \
  2008. sendAndApply(&sse); \
  2009. } \
  2010. else \
  2011. { \
  2012. for(int it=0; it<gs->curB->stacks.size(); ++it) \
  2013. { \
  2014. /*if it's non negative spell and our unit or non positive spell and hostile unit */ \
  2015. if((VLC->spellh->spells[ba.additionalInfo].positiveness >= 0 && gs->curB->stacks[it]->owner == h->tempOwner) \
  2016. ||(VLC->spellh->spells[ba.additionalInfo].positiveness <= 0 && gs->curB->stacks[it]->owner != h->tempOwner ) \
  2017. ) \
  2018. { \
  2019. sse.stacks.insert(gs->curB->stacks[it]->ID); \
  2020. } \
  2021. } \
  2022. sse.effect.id = (NUMBER); \
  2023. sse.effect.level = getSchoolLevel(h,s); \
  2024. sse.effect.turnsRemain = (DURATION); \
  2025. sendAndApply(&sse); \
  2026. }
  2027. SpellCasted sc;
  2028. sc.side = ba.side;
  2029. sc.id = ba.additionalInfo;
  2030. sc.skill = skill;
  2031. sc.tile = ba.destinationTile;
  2032. sendAndApply(&sc);
  2033. switch(ba.additionalInfo) //spell id
  2034. {
  2035. case 15: //magic arrow
  2036. {
  2037. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2038. if(!attacked) break;
  2039. BattleStackAttacked bsa;
  2040. bsa.flags |= 2;
  2041. bsa.effect = 64;
  2042. bsa.damageAmount = h->getPrimSkillLevel(2) * 10 + s->powers[getSchoolLevel(h,s)];
  2043. bsa.stackAttacked = attacked->ID;
  2044. prepareAttacked(bsa,attacked);
  2045. sendAndApply(&bsa);
  2046. break;
  2047. }
  2048. case 16: //ice bolt
  2049. {
  2050. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2051. if(!attacked) break;
  2052. BattleStackAttacked bsa;
  2053. bsa.flags |= 2;
  2054. bsa.effect = 46;
  2055. bsa.damageAmount = h->getPrimSkillLevel(2) * 20 + s->powers[getSchoolLevel(h,s)];
  2056. bsa.stackAttacked = attacked->ID;
  2057. prepareAttacked(bsa,attacked);
  2058. sendAndApply(&bsa);
  2059. break;
  2060. }
  2061. case 17: //lightning bolt
  2062. {
  2063. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2064. if(!attacked) break;
  2065. BattleStackAttacked bsa;
  2066. bsa.flags |= 2;
  2067. bsa.effect = 38;
  2068. bsa.damageAmount = h->getPrimSkillLevel(2) * 25 + s->powers[getSchoolLevel(h,s)];
  2069. bsa.stackAttacked = attacked->ID;
  2070. prepareAttacked(bsa,attacked);
  2071. sendAndApply(&bsa);
  2072. break;
  2073. }
  2074. case 18: //implosion
  2075. {
  2076. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2077. if(!attacked) break;
  2078. BattleStackAttacked bsa;
  2079. bsa.flags |= 2;
  2080. bsa.effect = 10;
  2081. bsa.damageAmount = h->getPrimSkillLevel(2) * 75 + s->powers[getSchoolLevel(h,s)];
  2082. bsa.stackAttacked = attacked->ID;
  2083. prepareAttacked(bsa,attacked);
  2084. sendAndApply(&bsa);
  2085. break;
  2086. }
  2087. case 27: //shield
  2088. case 28: //air shield
  2089. case 41: //bless
  2090. case 42: //curse
  2091. case 43: //bloodlust
  2092. case 45: //weakness
  2093. case 46: //stone skin
  2094. case 48: //prayer
  2095. case 49: //mirth
  2096. case 50: //sorrow
  2097. case 51: //fortune
  2098. case 52: //misfortune
  2099. case 53: //haste
  2100. case 54: //slow
  2101. {
  2102. SPELL_CAST_TEMPLATE_1(ba.additionalInfo, h->getPrimSkillLevel(2))
  2103. break;
  2104. }
  2105. case 56: //frenzy
  2106. {
  2107. SPELL_CAST_TEMPLATE_1(ba.additionalInfo, 1)
  2108. break;
  2109. }
  2110. case 61: //forgetfulness
  2111. {
  2112. SPELL_CAST_TEMPLATE_1(ba.additionalInfo, h->getPrimSkillLevel(2))
  2113. break;
  2114. }
  2115. }
  2116. sendAndApply(&EndAction());
  2117. }
  2118. }
  2119. }
  2120. void CGameHandler::handleTimeEvents()
  2121. {
  2122. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  2123. {
  2124. CMapEvent *ev = gs->map->events.front();
  2125. for(int player = 0; player < PLAYER_LIMIT; player++)
  2126. {
  2127. PlayerState *pinfo = gs->getPlayer(player);
  2128. if( pinfo //player exists
  2129. && (ev->players & 1<<player) //event is enabled to this player
  2130. && ((ev->computerAffected && !pinfo->human)
  2131. || (ev->humanAffected && pinfo->human)
  2132. )
  2133. )
  2134. {
  2135. //give resources
  2136. SetResources sr;
  2137. sr.player = player;
  2138. sr.res = pinfo->resources;
  2139. //prepare dialog
  2140. InfoWindow iw;
  2141. iw.player = player;
  2142. iw.text << ev->message;
  2143. for (int i=0; i<ev->resources.size(); i++)
  2144. {
  2145. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  2146. {
  2147. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  2148. sr.res[i] += ev->resources[i];
  2149. }
  2150. }
  2151. if (iw.components.size())
  2152. {
  2153. sendAndApply(&sr); //update player resources if changed
  2154. }
  2155. sendAndApply(&iw); //show dialog
  2156. }
  2157. } //PLAYERS LOOP
  2158. if(ev->nextOccurence)
  2159. {
  2160. ev->firstOccurence += ev->nextOccurence;
  2161. gs->map->events.sort(evntCmp);
  2162. }
  2163. else
  2164. {
  2165. delete ev;
  2166. gs->map->events.pop_front();
  2167. }
  2168. }
  2169. }
  2170. bool CGameHandler::complain( const std::string &problem )
  2171. {
  2172. sendMessageToAll("Server encountered a problem: " + problem);
  2173. tlog1 << problem << std::endl;
  2174. return true;
  2175. }