CGameHandler.cpp 88 KB

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