CGameHandler.cpp 95 KB

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