CGameHandler.cpp 127 KB

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