CGameHandler.cpp 130 KB

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