CGameHandler.cpp 86 KB

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