CGameHandler.cpp 117 KB

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