CGameHandler.cpp 65 KB

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