CGameHandler.cpp 96 KB

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