CGameHandler.cpp 87 KB

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