CGameHandler.cpp 137 KB

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