CGameHandler.cpp 86 KB

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