CGameHandler.cpp 121 KB

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