CGameHandler.cpp 77 KB

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