CGameHandler.cpp 95 KB

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