CGameHandler.cpp 92 KB

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