CGameHandler.cpp 114 KB

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