CGameHandler.cpp 94 KB

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