CGameHandler.cpp 71 KB

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