CGameHandler.cpp 67 KB

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