CGameHandler.cpp 98 KB

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