CGameHandler.cpp 68 KB

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