CGameHandler.cpp 94 KB

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