CBattleInterface.cpp 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651
  1. #include "StdInc.h"
  2. #include "CBattleInterface.h"
  3. #include "../CGameInfo.h"
  4. #include "../UIFramework/SDL_Extensions.h"
  5. #include "../CAdvmapInterface.h"
  6. #include "../CAnimation.h"
  7. #include "../../lib/CObjectHandler.h"
  8. #include "../../lib/CHeroHandler.h"
  9. #include "../CDefHandler.h"
  10. #include "../../lib/CSpellHandler.h"
  11. #include "../CMusicHandler.h"
  12. #include "../CMessage.h"
  13. #include "../../CCallback.h"
  14. #include "../../lib/BattleState.h"
  15. #include "../../lib/CGeneralTextHandler.h"
  16. #include "CCreatureAnimation.h"
  17. #include "../Graphics.h"
  18. #include "../CSpellWindow.h"
  19. #include "../../lib/CConfigHandler.h"
  20. #include "../../lib/CondSh.h"
  21. #include "../../lib/NetPacks.h"
  22. #include "../CPlayerInterface.h"
  23. #include "../CCreatureWindow.h"
  24. #include "../CVideoHandler.h"
  25. #include "../../lib/CTownHandler.h"
  26. #include "../../lib/Map/CMap.h"
  27. #include "CBattleAnimations.h"
  28. #include "CBattleInterfaceClasses.h"
  29. #include "../UIFramework/CCursorHandler.h"
  30. #include "../UIFramework/CGuiHandler.h"
  31. #ifndef __GNUC__
  32. const double M_PI = 3.14159265358979323846;
  33. #else
  34. #define _USE_MATH_DEFINES
  35. #include <cmath>
  36. #endif
  37. #include "../../lib/UnlockGuard.h"
  38. using namespace boost::assign;
  39. const time_t CBattleInterface::HOVER_ANIM_DELTA = 1;
  40. /*
  41. * CBattleInterface.cpp, part of VCMI engine
  42. *
  43. * Authors: listed in file AUTHORS in main folder
  44. *
  45. * License: GNU General Public License v2.0 or later
  46. * Full text of license available in license.txt file, in main folder
  47. *
  48. */
  49. extern SDL_Surface * screen;
  50. CondSh<bool> CBattleInterface::animsAreDisplayed;
  51. struct CMP_stack2
  52. {
  53. inline bool operator ()(const CStack& a, const CStack& b)
  54. {
  55. return (a.Speed())>(b.Speed());
  56. }
  57. } cmpst2 ;
  58. static void transformPalette(SDL_Surface * surf, double rCor, double gCor, double bCor)
  59. {
  60. SDL_Color * colorsToChange = surf->format->palette->colors;
  61. for(int g=0; g<surf->format->palette->ncolors; ++g)
  62. {
  63. if((colorsToChange+g)->b != 132 &&
  64. (colorsToChange+g)->g != 231 &&
  65. (colorsToChange+g)->r != 255) //it's not yellow border
  66. {
  67. (colorsToChange+g)->r = static_cast<double>((colorsToChange+g)->r) * rCor;
  68. (colorsToChange+g)->g = static_cast<double>((colorsToChange+g)->g) * gCor;
  69. (colorsToChange+g)->b = static_cast<double>((colorsToChange+g)->b) * bCor;
  70. }
  71. }
  72. }
  73. //////////////////////
  74. void CBattleInterface::addNewAnim(CBattleAnimation * anim)
  75. {
  76. pendingAnims.push_back( std::make_pair(anim, false) );
  77. animsAreDisplayed.setn(true);
  78. }
  79. CBattleInterface::CBattleInterface(const CCreatureSet * army1, const CCreatureSet * army2, CGHeroInstance *hero1, CGHeroInstance *hero2, const SDL_Rect & myRect, CPlayerInterface * att, CPlayerInterface * defen)
  80. : queue(NULL), attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0),
  81. activeStack(NULL), stackToActivate(NULL), selectedStack(NULL), mouseHoveredStack(-1), lastMouseHoveredStackAnimationTime(-1), previouslyHoveredHex(-1),
  82. currentlyHoveredHex(-1), attackingHex(-1), tacticianInterface(NULL), stackCanCastSpell(false), creatureCasting(false), spellDestSelectMode(false), spellSelMode(NO_LOCATION), spellToCast(NULL), sp(NULL),
  83. siegeH(NULL), attackerInt(att), defenderInt(defen), curInt(att), animIDhelper(0),
  84. givenCommand(NULL), myTurn(false), resWindow(NULL), moveStarted(false), moveSh(-1), bresult(NULL)
  85. {
  86. OBJ_CONSTRUCTION;
  87. if(!curInt) curInt = LOCPLINT; //may happen when we are defending during network MP game
  88. animsAreDisplayed.setn(false);
  89. pos = myRect;
  90. strongInterest = true;
  91. givenCommand = new CondSh<BattleAction *>(NULL);
  92. if(attackerInt && attackerInt->cb->battleGetTacticDist()) //hotseat -> check tactics for both players (defender may be local human)
  93. tacticianInterface = attackerInt;
  94. else if(defenderInt && defenderInt->cb->battleGetTacticDist())
  95. tacticianInterface = defenderInt;
  96. tacticsMode = tacticianInterface; //if we found interface of player with tactics, then enter tactics mode
  97. //create stack queue
  98. bool embedQueue = screen->h < 700;
  99. queue = new CStackQueue(embedQueue, this);
  100. if(!embedQueue)
  101. {
  102. if(settings["battle"]["showQueue"].Bool())
  103. pos.y += queue->pos.h / 2; //center whole window
  104. queue->moveTo(Point(pos.x, pos.y - queue->pos.h));
  105. // queue->pos.x = pos.x;
  106. // queue->pos.y = pos.y - queue->pos.h;
  107. // pos.h += queue->pos.h;
  108. // center();
  109. }
  110. queue->update();
  111. //preparing siege info
  112. const CGTownInstance * town = curInt->cb->battleGetDefendedTown();
  113. if(town && town->hasFort())
  114. {
  115. siegeH = new SiegeHelper(town, this);
  116. }
  117. curInt->battleInt = this;
  118. //initializing armies
  119. this->army1 = army1;
  120. this->army2 = army2;
  121. std::vector<const CStack*> stacks = curInt->cb->battleGetAllStacks();
  122. BOOST_FOREACH(const CStack *s, stacks)
  123. {
  124. newStack(s);
  125. }
  126. //preparing menu background and terrain
  127. if(siegeH)
  128. {
  129. background = BitmapHandler::loadBitmap( siegeH->getSiegeName(0), false );
  130. ui8 siegeLevel = curInt->cb->battleGetSiegeLevel();
  131. if(siegeLevel >= 2) //citadel or castle
  132. {
  133. //print moat/mlip
  134. SDL_Surface * moat = BitmapHandler::loadBitmap( siegeH->getSiegeName(13) ),
  135. * mlip = BitmapHandler::loadBitmap( siegeH->getSiegeName(14) );
  136. auto & info = siegeH->town->town->clientInfo;
  137. Point moatPos(info.siegePositions[13].x, info.siegePositions[13].y);
  138. Point mlipPos(info.siegePositions[14].x, info.siegePositions[14].y);
  139. if(moat) //eg. tower has no moat
  140. blitAt(moat, moatPos.x,moatPos.y, background);
  141. if(mlip) //eg. tower has no mlip
  142. blitAt(mlip, mlipPos.x, mlipPos.y, background);
  143. SDL_FreeSurface(moat);
  144. SDL_FreeSurface(mlip);
  145. }
  146. }
  147. else
  148. {
  149. std::vector< std::string > & backref = graphics->battleBacks[ curInt->cb->battleGetBattlefieldType() ];
  150. background = BitmapHandler::loadBitmap(backref[ rand() % backref.size()], false );
  151. }
  152. //preparing menu background
  153. //graphics->blueToPlayersAdv(menu, hero1->tempOwner);
  154. //preparing graphics for displaying amounts of creatures
  155. amountNormal = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  156. CSDL_Ext::alphaTransform(amountNormal);
  157. transformPalette(amountNormal, 0.59, 0.19, 0.93);
  158. amountPositive = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  159. CSDL_Ext::alphaTransform(amountPositive);
  160. transformPalette(amountPositive, 0.18, 1.00, 0.18);
  161. amountNegative = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  162. CSDL_Ext::alphaTransform(amountNegative);
  163. transformPalette(amountNegative, 1.00, 0.18, 0.18);
  164. amountEffNeutral = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  165. CSDL_Ext::alphaTransform(amountEffNeutral);
  166. transformPalette(amountEffNeutral, 1.00, 1.00, 0.18);
  167. ////blitting menu background and terrain
  168. // blitAt(background, pos.x, pos.y);
  169. // blitAt(menu, pos.x, 556 + pos.y);
  170. //preparing buttons and console
  171. bOptions = new CAdventureMapButton (CGI->generaltexth->zelp[381].first, CGI->generaltexth->zelp[381].second, boost::bind(&CBattleInterface::bOptionsf,this), 3, 561, "icm003.def", SDLK_o);
  172. bSurrender = new CAdventureMapButton (CGI->generaltexth->zelp[379].first, CGI->generaltexth->zelp[379].second, boost::bind(&CBattleInterface::bSurrenderf,this), 54, 561, "icm001.def", SDLK_s);
  173. bFlee = new CAdventureMapButton (CGI->generaltexth->zelp[380].first, CGI->generaltexth->zelp[380].second, boost::bind(&CBattleInterface::bFleef,this), 105, 561, "icm002.def", SDLK_r);
  174. bFlee->block(!curInt->cb->battleCanFlee());
  175. bSurrender->block(curInt->cb->battleGetSurrenderCost() < 0);
  176. bAutofight = new CAdventureMapButton (CGI->generaltexth->zelp[382].first, CGI->generaltexth->zelp[382].second, boost::bind(&CBattleInterface::bAutofightf,this), 157, 561, "icm004.def", SDLK_a);
  177. bSpell = new CAdventureMapButton (CGI->generaltexth->zelp[385].first, CGI->generaltexth->zelp[385].second, boost::bind(&CBattleInterface::bSpellf,this), 645, 561, "icm005.def", SDLK_c);
  178. bSpell->block(true);
  179. bWait = new CAdventureMapButton (CGI->generaltexth->zelp[386].first, CGI->generaltexth->zelp[386].second, boost::bind(&CBattleInterface::bWaitf,this), 696, 561, "icm006.def", SDLK_w);
  180. bDefence = new CAdventureMapButton (CGI->generaltexth->zelp[387].first, CGI->generaltexth->zelp[387].second, boost::bind(&CBattleInterface::bDefencef,this), 747, 561, "icm007.def", SDLK_d);
  181. bDefence->assignedKeys.insert(SDLK_SPACE);
  182. bConsoleUp = new CAdventureMapButton (std::string(), std::string(), boost::bind(&CBattleInterface::bConsoleUpf,this), 624, 561, "ComSlide.def", SDLK_UP);
  183. bConsoleDown = new CAdventureMapButton (std::string(), std::string(), boost::bind(&CBattleInterface::bConsoleDownf,this), 624, 580, "ComSlide.def", SDLK_DOWN);
  184. bConsoleDown->setOffset(2);
  185. console = new CBattleConsole();
  186. console->pos.x += 211;
  187. console->pos.y += 560;
  188. console->pos.w = 406;
  189. console->pos.h = 38;
  190. if(tacticsMode)
  191. {
  192. btactNext = new CAdventureMapButton(std::string(), std::string(), boost::bind(&CBattleInterface::bTacticNextStack,this, (CStack*)NULL), 213, 560, "icm011.def", SDLK_SPACE);
  193. btactEnd = new CAdventureMapButton(std::string(), std::string(), boost::bind(&CBattleInterface::bEndTacticPhase,this), 419, 560, "icm012.def", SDLK_RETURN);
  194. bDefence->block(true);
  195. bWait->block(true);
  196. menu = BitmapHandler::loadBitmap("COPLACBR.BMP");
  197. }
  198. else
  199. {
  200. menu = BitmapHandler::loadBitmap("CBAR.BMP");
  201. btactEnd = btactNext = NULL;
  202. }
  203. graphics->blueToPlayersAdv(menu, curInt->playerID);
  204. //loading hero animations
  205. if(hero1) // attacking hero
  206. {
  207. int type = hero1->type->heroType;
  208. if ( type % 2 ) type--;
  209. if ( hero1->sex ) type++;
  210. attackingHero = new CBattleHero(graphics->battleHeroes[type], false, hero1->tempOwner, hero1->tempOwner == curInt->playerID ? hero1 : NULL, this);
  211. attackingHero->pos = genRect(attackingHero->dh->ourImages[0].bitmap->h, attackingHero->dh->ourImages[0].bitmap->w, pos.x - 43, pos.y - 19);
  212. }
  213. else
  214. {
  215. attackingHero = NULL;
  216. }
  217. if(hero2) // defending hero
  218. {
  219. int type = hero2->type->heroType;
  220. if ( type % 2 ) type--;
  221. if ( hero2->sex ) type++;
  222. defendingHero = new CBattleHero(graphics->battleHeroes[type ], true, hero2->tempOwner, hero2->tempOwner == curInt->playerID ? hero2 : NULL, this);
  223. defendingHero->pos = genRect(defendingHero->dh->ourImages[0].bitmap->h, defendingHero->dh->ourImages[0].bitmap->w, pos.x + 693, pos.y - 19);
  224. }
  225. else
  226. {
  227. defendingHero = NULL;
  228. }
  229. //preparing cells and hexes
  230. cellBorder = BitmapHandler::loadBitmap("CCELLGRD.BMP");
  231. CSDL_Ext::alphaTransform(cellBorder);
  232. cellShade = BitmapHandler::loadBitmap("CCELLSHD.BMP");
  233. CSDL_Ext::alphaTransform(cellShade);
  234. for(int h = 0; h < GameConstants::BFIELD_SIZE; ++h)
  235. {
  236. CClickableHex *hex = new CClickableHex();
  237. hex->myNumber = h;
  238. hex->pos = hexPosition(h);
  239. hex->accessible = true;
  240. hex->myInterface = this;
  241. bfield.push_back(hex);
  242. }
  243. //locking occupied positions on batlefield
  244. BOOST_FOREACH(const CStack *s, stacks) //stacks gained at top of this function
  245. if(s->position >= 0) //turrets have position < 0
  246. bfield[s->position]->accessible = false;
  247. //loading projectiles for units
  248. BOOST_FOREACH(const CStack *s, stacks)
  249. {
  250. if(s->getCreature()->isShooting())
  251. {
  252. CDefHandler *&projectile = idToProjectile[s->getCreature()->idNumber];
  253. const CCreature * creature;//creature whose shots should be loaded
  254. if (s->getCreature()->idNumber == 149)
  255. creature = CGI->creh->creatures[siegeH->town->town->clientInfo.siegeShooter];
  256. else
  257. creature = s->getCreature();
  258. projectile = CDefHandler::giveDef(creature->projectile);
  259. if(projectile->ourImages.size() > 2) //add symmetric images
  260. {
  261. for(int k = projectile->ourImages.size()-2; k > 1; --k)
  262. {
  263. Cimage ci;
  264. ci.bitmap = CSDL_Ext::rotate01(projectile->ourImages[k].bitmap);
  265. ci.groupNumber = 0;
  266. ci.imName = std::string();
  267. projectile->ourImages.push_back(ci);
  268. }
  269. }
  270. for(size_t s = 0; s < projectile->ourImages.size(); ++s) //alpha transforming
  271. {
  272. CSDL_Ext::alphaTransform(projectile->ourImages[s].bitmap);
  273. }
  274. }
  275. }
  276. //preparing graphic with cell borders
  277. cellBorders = CSDL_Ext::newSurface(background->w, background->h, cellBorder);
  278. //copying palette
  279. for(int g=0; g<cellBorder->format->palette->ncolors; ++g) //we assume that cellBorders->format->palette->ncolors == 256
  280. {
  281. cellBorders->format->palette->colors[g] = cellBorder->format->palette->colors[g];
  282. }
  283. //palette copied
  284. for(int i=0; i<GameConstants::BFIELD_HEIGHT; ++i) //rows
  285. {
  286. for(int j=0; j<GameConstants::BFIELD_WIDTH-2; ++j) //columns
  287. {
  288. int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
  289. int y = 86 + 42 * i;
  290. for(int cellX = 0; cellX < cellBorder->w; ++cellX)
  291. {
  292. for(int cellY = 0; cellY < cellBorder->h; ++cellY)
  293. {
  294. if(y+cellY < cellBorders->h && x+cellX < cellBorders->w)
  295. * ((Uint8*)cellBorders->pixels + (y+cellY) * cellBorders->pitch + (x+cellX)) |= * ((Uint8*)cellBorder->pixels + cellY * cellBorder->pitch + cellX);
  296. }
  297. }
  298. }
  299. }
  300. backgroundWithHexes = CSDL_Ext::newSurface(background->w, background->h, screen);
  301. //preparing obstacle defs
  302. auto obst = curInt->cb->battleGetAllObstacles();
  303. for(size_t t = 0; t < obst.size(); ++t)
  304. {
  305. const int ID = obst[t]->ID;
  306. if(obst[t]->obstacleType == CObstacleInstance::USUAL)
  307. {
  308. idToObstacle[ID] = CDefHandler::giveDef(obst[t]->getInfo().defName);
  309. for(size_t n = 0; n < idToObstacle[ID]->ourImages.size(); ++n)
  310. {
  311. SDL_SetColorKey(idToObstacle[ID]->ourImages[n].bitmap, SDL_SRCCOLORKEY, SDL_MapRGB(idToObstacle[ID]->ourImages[n].bitmap->format,0,255,255));
  312. }
  313. }
  314. else if(obst[t]->obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE)
  315. {
  316. idToAbsoluteObstacle[ID] = BitmapHandler::loadBitmap(obst[t]->getInfo().defName);
  317. }
  318. }
  319. quicksand = CDefHandler::giveDef("C17SPE1.DEF");
  320. landMine = CDefHandler::giveDef("C09SPF1.DEF");
  321. fireWall = CDefHandler::giveDef("C07SPF61");
  322. bigForceField[0] = CDefHandler::giveDef("C15SPE10.DEF");
  323. bigForceField[1] = CDefHandler::giveDef("C15SPE7.DEF");
  324. smallForceField[0] = CDefHandler::giveDef("C15SPE1.DEF");
  325. smallForceField[1] = CDefHandler::giveDef("C15SPE4.DEF");
  326. BOOST_FOREACH(auto hex, bfield)
  327. addChild(hex);
  328. if(tacticsMode)
  329. bTacticNextStack();
  330. CCS->musich->stopMusic();
  331. int channel = CCS->soundh->playSoundFromSet(CCS->soundh->battleIntroSounds);
  332. auto onIntroPlayed = []()
  333. {
  334. if (LOCPLINT->battleInt)
  335. CCS->musich->playMusicFromSet("battle", true);
  336. };
  337. CCS->soundh->setCallback(channel, onIntroPlayed);
  338. memset(stackCountOutsideHexes, 1, GameConstants::BFIELD_SIZE * sizeof(bool)); //initialize array with trues
  339. currentAction = INVALID;
  340. selectedAction = INVALID;
  341. addUsedEvents(RCLICK | MOVE | KEYBOARD);
  342. }
  343. CBattleInterface::~CBattleInterface()
  344. {
  345. curInt->battleInt = NULL;
  346. givenCommand->cond.notify_all(); //that two lines should make any activeStack waiting thread to finish
  347. if (active) //dirty fix for #485
  348. {
  349. deactivate();
  350. }
  351. SDL_FreeSurface(background);
  352. SDL_FreeSurface(menu);
  353. SDL_FreeSurface(amountNormal);
  354. SDL_FreeSurface(amountNegative);
  355. SDL_FreeSurface(amountPositive);
  356. SDL_FreeSurface(amountEffNeutral);
  357. SDL_FreeSurface(cellBorders);
  358. SDL_FreeSurface(backgroundWithHexes);
  359. delete bOptions;
  360. delete bSurrender;
  361. delete bFlee;
  362. delete bAutofight;
  363. delete bSpell;
  364. delete bWait;
  365. delete bDefence;
  366. BOOST_FOREACH(auto hex, bfield)
  367. delete hex;
  368. delete bConsoleUp;
  369. delete bConsoleDown;
  370. delete console;
  371. delete givenCommand;
  372. delete attackingHero;
  373. delete defendingHero;
  374. delete queue;
  375. SDL_FreeSurface(cellBorder);
  376. SDL_FreeSurface(cellShade);
  377. for(std::map< int, CCreatureAnimation * >::iterator g=creAnims.begin(); g!=creAnims.end(); ++g)
  378. delete g->second;
  379. for(std::map< int, CDefHandler * >::iterator g=idToProjectile.begin(); g!=idToProjectile.end(); ++g)
  380. delete g->second;
  381. for(std::map< int, CDefHandler * >::iterator g=idToObstacle.begin(); g!=idToObstacle.end(); ++g)
  382. delete g->second;
  383. delete quicksand;
  384. delete landMine;
  385. delete fireWall;
  386. delete smallForceField[0];
  387. delete smallForceField[1];
  388. delete bigForceField[0];
  389. delete bigForceField[1];
  390. delete siegeH;
  391. //TODO: play AI tracks if battle was during AI turn
  392. //if (!curInt->makingTurn)
  393. //CCS->musich->playMusicFromSet(CCS->musich->aiMusics, -1);
  394. if(adventureInt && adventureInt->selection)
  395. {
  396. int terrain = LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->terType;
  397. CCS->musich->playMusicFromSet("terrain", terrain, true);
  398. }
  399. }
  400. void CBattleInterface::setPrintCellBorders(bool set)
  401. {
  402. Settings cellBorders = settings.write["battle"]["cellBorders"];
  403. cellBorders->Bool() = set;
  404. redrawBackgroundWithHexes(activeStack);
  405. GH.totalRedraw();
  406. }
  407. void CBattleInterface::setPrintStackRange(bool set)
  408. {
  409. Settings stackRange = settings.write["battle"]["stackRange"];
  410. stackRange->Bool() = set;
  411. redrawBackgroundWithHexes(activeStack);
  412. GH.totalRedraw();
  413. }
  414. void CBattleInterface::setPrintMouseShadow(bool set)
  415. {
  416. Settings shadow = settings.write["battle"]["mouseShadow"];
  417. shadow->Bool() = set;
  418. }
  419. void CBattleInterface::activate()
  420. {
  421. CIntObject::activate();
  422. bOptions->activate();
  423. bSurrender->activate();
  424. bFlee->activate();
  425. bAutofight->activate();
  426. bSpell->activate();
  427. bWait->activate();
  428. bDefence->activate();
  429. BOOST_FOREACH(auto hex, bfield)
  430. hex->activate();
  431. if(attackingHero)
  432. attackingHero->activate();
  433. if(defendingHero)
  434. defendingHero->activate();
  435. if(settings["battle"]["showQueue"].Bool())
  436. queue->activate();
  437. if(tacticsMode)
  438. {
  439. btactNext->activate();
  440. btactEnd->activate();
  441. }
  442. else
  443. {
  444. bConsoleUp->activate();
  445. bConsoleDown->activate();
  446. }
  447. LOCPLINT->cingconsole->activate();
  448. }
  449. void CBattleInterface::deactivate()
  450. {
  451. CIntObject::deactivate();
  452. bOptions->deactivate();
  453. bSurrender->deactivate();
  454. bFlee->deactivate();
  455. bAutofight->deactivate();
  456. bSpell->deactivate();
  457. bWait->deactivate();
  458. bDefence->deactivate();
  459. BOOST_FOREACH(auto hex, bfield)
  460. hex->deactivate();
  461. if(attackingHero)
  462. attackingHero->deactivate();
  463. if(defendingHero)
  464. defendingHero->deactivate();
  465. if(settings["battle"]["showQueue"].Bool())
  466. queue->deactivate();
  467. if(tacticsMode)
  468. {
  469. btactNext->deactivate();
  470. btactEnd->deactivate();
  471. }
  472. else
  473. {
  474. bConsoleUp->deactivate();
  475. bConsoleDown->deactivate();
  476. }
  477. LOCPLINT->cingconsole->deactivate();
  478. }
  479. void CBattleInterface::showAll(SDL_Surface * to)
  480. {
  481. show(to);
  482. }
  483. void CBattleInterface::show(SDL_Surface * to)
  484. {
  485. std::vector<const CStack*> stacks = curInt->cb->battleGetAllStacks(); //used in a few places
  486. ++animCount;
  487. if(!to) //"evaluating" to
  488. to = screen;
  489. SDL_Rect buf;
  490. SDL_GetClipRect(to, &buf);
  491. SDL_SetClipRect(to, &pos);
  492. //printing background and hexes
  493. if(activeStack != NULL && creAnims[activeStack->ID]->getType() != 0) //show everything with range
  494. {
  495. blitAt(backgroundWithHexes, pos.x, pos.y, to);
  496. }
  497. else
  498. {
  499. //showing background
  500. blitAt(background, pos.x, pos.y, to);
  501. if(settings["battle"]["cellBorders"].Bool())
  502. {
  503. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, NULL, to, &pos);
  504. }
  505. //Blit absolute obstacles
  506. BOOST_FOREACH(auto &oi, curInt->cb->battleGetAllObstacles())
  507. if(oi->obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE)
  508. blitAt(imageOfObstacle(*oi), pos.x + oi->getInfo().width, pos.y + oi->getInfo().height, to);
  509. }
  510. //printing hovered cell
  511. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b)
  512. {
  513. if(bfield[b]->strictHovered && bfield[b]->hovered)
  514. {
  515. if(previouslyHoveredHex == -1) previouslyHoveredHex = b; //something to start with
  516. if(currentlyHoveredHex == -1) currentlyHoveredHex = b; //something to start with
  517. if(currentlyHoveredHex != b) //repair hover info
  518. {
  519. previouslyHoveredHex = currentlyHoveredHex;
  520. currentlyHoveredHex = b;
  521. }
  522. //print shade
  523. if(spellToCast) //when casting spell
  524. {
  525. //calculating spell school level
  526. const CSpell & spToCast = *CGI->spellh->spells[spellToCast->additionalInfo];
  527. ui8 schoolLevel = 0;
  528. if (activeStack->attackerOwned)
  529. {
  530. if(attackingHeroInstance)
  531. schoolLevel = attackingHeroInstance->getSpellSchoolLevel(&spToCast);
  532. }
  533. else
  534. {
  535. if (defendingHeroInstance)
  536. schoolLevel = defendingHeroInstance->getSpellSchoolLevel(&spToCast);
  537. }
  538. //obtaining range and printing it
  539. auto shaded = spToCast.rangeInHexes(b, schoolLevel, curInt->cb->battleGetMySide());
  540. BOOST_FOREACH(auto shadedHex, shaded) //for spells with range greater then one hex
  541. {
  542. if(settings["battle"]["mouseShadow"].Bool() && (shadedHex % GameConstants::BFIELD_WIDTH != 0) && (shadedHex % GameConstants::BFIELD_WIDTH != 16))
  543. {
  544. int x = 14 + ((shadedHex/GameConstants::BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(shadedHex%GameConstants::BFIELD_WIDTH) + pos.x;
  545. int y = 86 + 42 * (shadedHex/GameConstants::BFIELD_WIDTH) + pos.y;
  546. SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
  547. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, to, &temp_rect);
  548. }
  549. }
  550. }
  551. else if(settings["battle"]["mouseShadow"].Bool()) //when not casting spell
  552. {//TODO: do not check it every frame
  553. if (activeStack) //highlight all attackable hexes
  554. {
  555. std::set<BattleHex> set = curInt->cb->battleGetAttackedHexes(activeStack, currentlyHoveredHex, attackingHex);
  556. BOOST_FOREACH(BattleHex hex, set)
  557. {
  558. int x = 14 + ((hex/GameConstants::BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(hex%GameConstants::BFIELD_WIDTH) + pos.x;
  559. int y = 86 + 42 * (hex/GameConstants::BFIELD_WIDTH) + pos.y;
  560. SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
  561. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, to, &temp_rect);
  562. }
  563. }
  564. //patch by ench0: show enemy stack movement shadow
  565. // activeStack == NULL means it is opponent's turn...
  566. if(activeStack && settings["battle"]["stackRange"].Bool())
  567. {
  568. // display the movement shadow of the stack at b (i.e. stack under mouse)
  569. const CStack * const shere = curInt->cb->battleGetStackByPos(b, false);
  570. if (shere && shere != activeStack && shere->alive())
  571. {
  572. std::vector<BattleHex> v = curInt->cb->battleGetAvailableHexes(shere, true );
  573. BOOST_FOREACH (BattleHex hex, v)
  574. {
  575. int x = 14 + ((hex / GameConstants::BFIELD_WIDTH ) % 2 == 0 ? 22 : 0) + 44 * (hex % GameConstants::BFIELD_WIDTH) + pos.x;
  576. int y = 86 + 42 * (hex / GameConstants::BFIELD_WIDTH) + pos.y;
  577. SDL_Rect temp_rect = genRect (cellShade->h, cellShade->w, x, y);
  578. CSDL_Ext::blit8bppAlphaTo24bpp (cellShade, NULL, to, &temp_rect);
  579. }
  580. }
  581. }
  582. //always highlight pointed hex
  583. int x = 14 + ((b/GameConstants::BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(b%GameConstants::BFIELD_WIDTH) + pos.x;
  584. int y = 86 + 42 * (b/GameConstants::BFIELD_WIDTH) + pos.y;
  585. SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
  586. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, to, &temp_rect);
  587. }
  588. }
  589. }
  590. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  591. //prevents blitting outside this window
  592. SDL_GetClipRect(to, &buf);
  593. SDL_SetClipRect(to, &pos);
  594. //preparing obstacles to be shown
  595. auto obstacles = curInt->cb->battleGetAllObstacles();
  596. std::multimap<BattleHex, int> hexToObstacle;
  597. for(size_t b = 0; b < obstacles.size(); ++b)
  598. {
  599. const auto &oi = obstacles[b];
  600. if(oi->obstacleType != CObstacleInstance::ABSOLUTE_OBSTACLE && oi->obstacleType != CObstacleInstance::MOAT)
  601. {
  602. //BattleHex position = CGI->heroh->obstacles.find(obstacles[b].ID)->second.getMaxBlocked(obstacles[b].pos);
  603. hexToObstacle.insert(std::make_pair(oi->pos, b));
  604. }
  605. }
  606. ////showing units //a lot of work...
  607. std::vector<const CStack *> stackAliveByHex[GameConstants::BFIELD_SIZE];
  608. //double loop because dead stacks should be printed first
  609. for (size_t i = 0; i < stacks.size(); i++)
  610. {
  611. const CStack *s = stacks[i];
  612. if(creAnims.find(s->ID) == creAnims.end()) //e.g. for summoned but not yet handled stacks
  613. continue;
  614. if(creAnims[s->ID]->getType() != 5 && s->position >= 0) //don't show turrets here
  615. stackAliveByHex[s->position].push_back(s);
  616. }
  617. std::vector<const CStack *> stackDeadByHex[GameConstants::BFIELD_SIZE];
  618. for (size_t i = 0; i < stacks.size(); i++)
  619. {
  620. const CStack *s = stacks[i];
  621. if(creAnims.find(s->ID) == creAnims.end()) //e.g. for summoned but not yet handled stacks
  622. continue;
  623. if(creAnims[s->ID]->getType() == 5)
  624. stackDeadByHex[s->position].push_back(s);
  625. }
  626. //handle animations
  627. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
  628. {
  629. if(!it->first) //this animation should be deleted
  630. continue;
  631. if(!it->second)
  632. {
  633. it->second = it->first->init();
  634. }
  635. if(it->second && it->first)
  636. it->first->nextFrame();
  637. }
  638. //delete anims
  639. int preSize = pendingAnims.size();
  640. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
  641. {
  642. if(it->first == NULL)
  643. {
  644. pendingAnims.erase(it);
  645. it = pendingAnims.begin();
  646. break;
  647. }
  648. }
  649. if(preSize > 0 && pendingAnims.size() == 0)
  650. {
  651. //action finished, restore the interface
  652. if(!active)
  653. activate();
  654. bool changedStack = false;
  655. //activation of next stack
  656. if(pendingAnims.size() == 0 && stackToActivate != NULL)
  657. {
  658. activateStack();
  659. changedStack = true;
  660. }
  661. //anims ended
  662. animsAreDisplayed.setn(false);
  663. if(changedStack)
  664. {
  665. //we may have changed active interface (another side in hot-seat),
  666. // so we can't continue drawing with old setting. So we call ourselves again and end.
  667. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  668. show(to);
  669. return;
  670. }
  671. }
  672. for(int b=0; b<GameConstants::BFIELD_SIZE; ++b) //showing dead stacks
  673. {
  674. for(size_t v=0; v<stackDeadByHex[b].size(); ++v)
  675. {
  676. creAnims[stackDeadByHex[b][v]->ID]->nextFrame(to, creAnims[stackDeadByHex[b][v]->ID]->pos.x, creAnims[stackDeadByHex[b][v]->ID]->pos.y, creDir[stackDeadByHex[b][v]->ID], animCount, false); //increment always when moving, never if stack died
  677. }
  678. }
  679. std::vector<const CStack *> flyingStacks; //flying stacks should be displayed later, over other stacks and obstacles
  680. if (!siegeH)
  681. {
  682. for(int b = 0; b < GameConstants::BFIELD_SIZE; ++b) //showing alive stacks
  683. {
  684. showObstacles(&hexToObstacle, obstacles, b, to);
  685. showAliveStacks(stackAliveByHex, b, &flyingStacks, to);
  686. }
  687. }
  688. // Siege drawing
  689. else
  690. {
  691. for (int i = 0; i < 4; i++)
  692. {
  693. // xMin, xMax => go from hex x pos to hex x pos
  694. // yMin, yMax => go from hex y pos to hex y pos
  695. // xMove => 0: left side, 1: right side
  696. // xMoveDir => 0: decrement, 1: increment, alters every second hex line either xMin or xMax depending on xMove
  697. int xMin, xMax, yMin, yMax, xMove, xMoveDir = 0;
  698. switch (i)
  699. {
  700. // display units shown at the upper left side
  701. case 0:
  702. xMin = 0;
  703. yMin = 0;
  704. xMax = 11;
  705. yMax = 4;
  706. xMove = 1;
  707. break;
  708. // display wall/units shown at the upper wall area/right upper side
  709. case 1:
  710. xMin = 12;
  711. yMin = 0;
  712. xMax = 16;
  713. yMax = 4;
  714. xMove = 0;
  715. break;
  716. // display units shown at the lower wall area/right lower side
  717. case 2:
  718. xMin = 10;
  719. yMin = 5;
  720. xMax = 16;
  721. yMax = 10;
  722. xMove = 0;
  723. xMoveDir = 1;
  724. break;
  725. // display units shown at the left lower side
  726. case 3:
  727. xMin = 0;
  728. yMin = 5;
  729. xMax = 9;
  730. yMax = 10;
  731. xMove = 1;
  732. xMoveDir = 1;
  733. break;
  734. }
  735. int runNum = 0;
  736. for (int j = yMin; j <= yMax; j++)
  737. {
  738. if (runNum > 0)
  739. {
  740. if (xMin == xMax)
  741. xMax = xMin = ((runNum % 2) == 0) ? (xMin + (xMoveDir == 0 ? -1 : 1)) : xMin;
  742. else if (xMove == 1)
  743. xMax = ((runNum % 2) == 0) ? (xMax + (xMoveDir == 0 ? -1 : 1)) : xMax;
  744. else if (xMove == 0)
  745. xMin = ((runNum % 2) == 0) ? (xMin + (xMoveDir == 0 ? -1 : 1)) : xMin;
  746. }
  747. for (int k = xMin; k <= xMax; k++)
  748. {
  749. int hex = j * 17 + k;
  750. showObstacles(&hexToObstacle, obstacles, hex, to);
  751. showAliveStacks(stackAliveByHex, hex, &flyingStacks, to);
  752. showPieceOfWall(to, hex, stacks);
  753. }
  754. ++runNum;
  755. }
  756. }
  757. }
  758. for(size_t b = 0; b < flyingStacks.size(); ++b) //showing flying stacks
  759. showAliveStack(flyingStacks[b], to);
  760. //units shown
  761. // Show projectiles
  762. projectileShowHelper(to);
  763. //showing spell effects
  764. if(battleEffects.size())
  765. {
  766. for(std::list<BattleEffect>::iterator it = battleEffects.begin(); it!=battleEffects.end(); ++it)
  767. {
  768. SDL_Surface * bitmapToBlit = it->anim->ourImages[(it->frame)%it->anim->ourImages.size()].bitmap;
  769. SDL_Rect temp_rect = genRect(bitmapToBlit->h, bitmapToBlit->w, it->x, it->y);
  770. SDL_BlitSurface(bitmapToBlit, NULL, to, &temp_rect);
  771. }
  772. }
  773. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  774. //showing menu background and console
  775. blitAt(menu, pos.x, 556 + pos.y, to);
  776. if(tacticsMode)
  777. {
  778. btactNext->showAll(to);
  779. btactEnd->showAll(to);
  780. }
  781. else
  782. {
  783. console->showAll(to);
  784. bConsoleUp->showAll(to);
  785. bConsoleDown->showAll(to);
  786. }
  787. //showing buttons
  788. bOptions->showAll(to);
  789. bSurrender->showAll(to);
  790. bFlee->showAll(to);
  791. bAutofight->showAll(to);
  792. bSpell->showAll(to);
  793. bWait->showAll(to);
  794. bDefence->showAll(to);
  795. //showing in-game console
  796. LOCPLINT->cingconsole->show(to);
  797. Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
  798. if(settings["battle"]["showQueue"].Bool())
  799. {
  800. if(!queue->embedded)
  801. {
  802. posWithQueue.y -= queue->pos.h;
  803. posWithQueue.h += queue->pos.h;
  804. }
  805. //showing queue
  806. if(!bresult)
  807. queue->showAll(to);
  808. else
  809. queue->blitBg(to);
  810. }
  811. //printing border around interface
  812. if(screen->w != 800 || screen->h !=600)
  813. {
  814. CMessage::drawBorder(curInt->playerID,to,posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
  815. }
  816. }
  817. void CBattleInterface::showAliveStacks(std::vector<const CStack *> *aliveStacks, int hex, std::vector<const CStack *> *flyingStacks, SDL_Surface *to)
  818. {
  819. //showing hero animations
  820. if (hex == 0)
  821. if(attackingHero)
  822. attackingHero->show(to);
  823. if (hex == 16)
  824. if(defendingHero)
  825. defendingHero->show(to);
  826. for(size_t v = 0; v < aliveStacks[hex].size(); ++v)
  827. {
  828. const CStack *s = aliveStacks[hex][v];
  829. if(!s->hasBonusOfType(Bonus::FLYING) || creAnims[s->ID]->getType() != 0)
  830. showAliveStack(s, to);
  831. else
  832. flyingStacks->push_back(s);
  833. }
  834. }
  835. void CBattleInterface::showObstacles(std::multimap<BattleHex, int> *hexToObstacle, std::vector<shared_ptr<const CObstacleInstance> > &obstacles, int hex, SDL_Surface *to)
  836. {
  837. std::pair<std::multimap<BattleHex, int>::const_iterator, std::multimap<BattleHex, int>::const_iterator> obstRange =
  838. hexToObstacle->equal_range(hex);
  839. for(std::multimap<BattleHex, int>::const_iterator it = obstRange.first; it != obstRange.second; ++it)
  840. {
  841. const CObstacleInstance & curOb = *obstacles[it->second];
  842. SDL_Surface *toBlit = imageOfObstacle(curOb);
  843. Point p = whereToBlitObstacleImage(toBlit, curOb);
  844. blitAt(toBlit, p.x, p.y, to);
  845. }
  846. }
  847. void CBattleInterface::keyPressed(const SDL_KeyboardEvent & key)
  848. {
  849. if(key.keysym.sym == SDLK_q && key.state == SDL_PRESSED)
  850. {
  851. if(settings["battle"]["showQueue"].Bool()) //hide queue
  852. hideQueue();
  853. else
  854. showQueue();
  855. }
  856. else if(key.keysym.sym == SDLK_ESCAPE && spellDestSelectMode)
  857. {
  858. endCastingSpell();
  859. }
  860. }
  861. void CBattleInterface::mouseMoved(const SDL_MouseMotionEvent &sEvent)
  862. {
  863. auto hexItr = std::find_if(bfield.begin(), bfield.end(), [](const CClickableHex *hex)
  864. {
  865. return hex->hovered && hex->strictHovered;
  866. });
  867. handleHex(hexItr == bfield.end() ? -1 : (*hexItr)->myNumber, MOVE);
  868. }
  869. void CBattleInterface::setBattleCursor(const int myNumber)
  870. {
  871. const CClickableHex & hoveredHex = *bfield[myNumber];
  872. CCursorHandler *cursor = CCS->curh;
  873. const double subdividingAngle = 2.0*M_PI/6.0; // Divide a hex into six sectors.
  874. const double hexMidX = hoveredHex.pos.x + hoveredHex.pos.w/2;
  875. const double hexMidY = hoveredHex.pos.y + hoveredHex.pos.h/2;
  876. const double cursorHexAngle = M_PI - atan2(hexMidY - cursor->ypos, cursor->xpos - hexMidX) + subdividingAngle/2; //TODO: refactor this nightmare
  877. const double sector = fmod(cursorHexAngle/subdividingAngle, 6.0);
  878. const int zigzagCorrection = !((myNumber/GameConstants::BFIELD_WIDTH)%2); // Off-by-one correction needed to deal with the odd battlefield rows.
  879. std::vector<int> sectorCursor; // From left to bottom left.
  880. sectorCursor.push_back(8);
  881. sectorCursor.push_back(9);
  882. sectorCursor.push_back(10);
  883. sectorCursor.push_back(11);
  884. sectorCursor.push_back(12);
  885. sectorCursor.push_back(7);
  886. const bool doubleWide = activeStack->doubleWide();
  887. bool aboveAttackable = true, belowAttackable = true;
  888. // Exclude directions which cannot be attacked from.
  889. // Check to the left.
  890. if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - 1))
  891. {
  892. sectorCursor[0] = -1;
  893. }
  894. // Check top left, top right as well as above for 2-hex creatures.
  895. if (myNumber/GameConstants::BFIELD_WIDTH == 0)
  896. {
  897. sectorCursor[1] = -1;
  898. sectorCursor[2] = -1;
  899. aboveAttackable = false;
  900. }
  901. else
  902. {
  903. if (doubleWide)
  904. {
  905. bool attackRow[4] = {true, true, true, true};
  906. if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 2 + zigzagCorrection))
  907. attackRow[0] = false;
  908. if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
  909. attackRow[1] = false;
  910. if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection))
  911. attackRow[2] = false;
  912. if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + 1 + zigzagCorrection))
  913. attackRow[3] = false;
  914. if (!(attackRow[0] && attackRow[1]))
  915. sectorCursor[1] = -1;
  916. if (!(attackRow[1] && attackRow[2]))
  917. aboveAttackable = false;
  918. if (!(attackRow[2] && attackRow[3]))
  919. sectorCursor[2] = -1;
  920. }
  921. else
  922. {
  923. if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
  924. sectorCursor[1] = -1;
  925. if (!vstd::contains(occupyableHexes, myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection))
  926. sectorCursor[2] = -1;
  927. }
  928. }
  929. // Check to the right.
  930. if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + 1))
  931. {
  932. sectorCursor[3] = -1;
  933. }
  934. // Check bottom right, bottom left as well as below for 2-hex creatures.
  935. if (myNumber/GameConstants::BFIELD_WIDTH == GameConstants::BFIELD_HEIGHT - 1)
  936. {
  937. sectorCursor[4] = -1;
  938. sectorCursor[5] = -1;
  939. belowAttackable = false;
  940. }
  941. else
  942. {
  943. if (doubleWide)
  944. {
  945. bool attackRow[4] = {true, true, true, true};
  946. if (myNumber%GameConstants::BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 2 + zigzagCorrection))
  947. attackRow[0] = false;
  948. if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
  949. attackRow[1] = false;
  950. if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection))
  951. attackRow[2] = false;
  952. if (myNumber%GameConstants::BFIELD_WIDTH >= GameConstants::BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + 1 + zigzagCorrection))
  953. attackRow[3] = false;
  954. if (!(attackRow[0] && attackRow[1]))
  955. sectorCursor[5] = -1;
  956. if (!(attackRow[1] && attackRow[2]))
  957. belowAttackable = false;
  958. if (!(attackRow[2] && attackRow[3]))
  959. sectorCursor[4] = -1;
  960. }
  961. else
  962. {
  963. if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection))
  964. sectorCursor[4] = -1;
  965. if (!vstd::contains(occupyableHexes, myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection))
  966. sectorCursor[5] = -1;
  967. }
  968. }
  969. // Determine index from sector.
  970. int cursorIndex;
  971. if (doubleWide)
  972. {
  973. sectorCursor.insert(sectorCursor.begin() + 5, belowAttackable ? 13 : -1);
  974. sectorCursor.insert(sectorCursor.begin() + 2, aboveAttackable ? 14 : -1);
  975. if (sector < 1.5)
  976. cursorIndex = sector;
  977. else if (sector >= 1.5 && sector < 2.5)
  978. cursorIndex = 2;
  979. else if (sector >= 2.5 && sector < 4.5)
  980. cursorIndex = (int) sector + 1;
  981. else if (sector >= 4.5 && sector < 5.5)
  982. cursorIndex = 6;
  983. else
  984. cursorIndex = (int) sector + 2;
  985. }
  986. else
  987. {
  988. cursorIndex = sector;
  989. }
  990. // Generally should NEVER happen, but to avoid the possibility of having endless loop below... [#1016]
  991. if(!vstd::contains_if(sectorCursor, [](int sc) { return sc != -1; }))
  992. {
  993. tlog1 << "Error: for hex " << myNumber << " cannot find a hex to attack from!\n";
  994. attackingHex = -1;
  995. return;
  996. }
  997. // Find the closest direction attackable, starting with the right one.
  998. // FIXME: Is this really how the original H3 client does it?
  999. int i = 0;
  1000. while (sectorCursor[(cursorIndex + i)%sectorCursor.size()] == -1) //Why hast thou forsaken me?
  1001. i = i <= 0 ? 1 - i : -i; // 0, 1, -1, 2, -2, 3, -3 etc..
  1002. int index = (cursorIndex + i)%sectorCursor.size(); //hopefully we get elements from sectorCursor
  1003. cursor->changeGraphic(1, sectorCursor[index]);
  1004. switch (index)
  1005. {
  1006. case 0:
  1007. attackingHex = myNumber - 1; //left
  1008. break;
  1009. case 1:
  1010. attackingHex = myNumber - GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection; //top left
  1011. break;
  1012. case 2:
  1013. attackingHex = myNumber - GameConstants::BFIELD_WIDTH + zigzagCorrection; //top right
  1014. break;
  1015. case 3:
  1016. break;
  1017. attackingHex = myNumber + 1; //right
  1018. case 4:
  1019. break;
  1020. attackingHex = myNumber + GameConstants::BFIELD_WIDTH + zigzagCorrection; //bottom right
  1021. case 5:
  1022. attackingHex = myNumber + GameConstants::BFIELD_WIDTH - 1 + zigzagCorrection; //bottom left
  1023. break;
  1024. }
  1025. BattleHex hex(attackingHex);
  1026. if (!hex.isValid())
  1027. attackingHex = -1;
  1028. }
  1029. void CBattleInterface::clickRight(tribool down, bool previousState)
  1030. {
  1031. if(!down && spellDestSelectMode)
  1032. {
  1033. endCastingSpell();
  1034. }
  1035. }
  1036. void CBattleInterface::bOptionsf()
  1037. {
  1038. if(spellDestSelectMode) //we are casting a spell
  1039. return;
  1040. CCS->curh->changeGraphic(0,0);
  1041. Rect tempRect = genRect(431, 481, 160, 84);
  1042. tempRect += pos.topLeft();
  1043. CBattleOptionsWindow * optionsWin = new CBattleOptionsWindow(tempRect, this);
  1044. GH.pushInt(optionsWin);
  1045. }
  1046. void CBattleInterface::bSurrenderf()
  1047. {
  1048. if(spellDestSelectMode) //we are casting a spell
  1049. return;
  1050. int cost = curInt->cb->battleGetSurrenderCost();
  1051. if(cost >= 0)
  1052. {
  1053. const CGHeroInstance *opponent = curInt->cb->battleGetFightingHero(1);
  1054. std::string enemyHeroName = opponent ? opponent->name : "#ENEMY#"; //TODO: should surrendering without enemy hero be enabled?
  1055. std::string surrenderMessage = boost::str(boost::format(CGI->generaltexth->allTexts[32]) % enemyHeroName % cost); //%s states: "I will accept your surrender and grant you and your troops safe passage for the price of %d gold."
  1056. curInt->showYesNoDialog(surrenderMessage, boost::bind(&CBattleInterface::reallySurrender,this), 0, false);
  1057. }
  1058. }
  1059. void CBattleInterface::bFleef()
  1060. {
  1061. if(spellDestSelectMode) //we are casting a spell
  1062. return;
  1063. if( curInt->cb->battleCanFlee() )
  1064. {
  1065. CFunctionList<void()> ony = boost::bind(&CBattleInterface::reallyFlee,this);
  1066. curInt->showYesNoDialog(CGI->generaltexth->allTexts[28], ony, 0, false); //Are you sure you want to retreat?
  1067. }
  1068. else
  1069. {
  1070. std::vector<CComponent*> comps;
  1071. std::string heroName;
  1072. //calculating fleeing hero's name
  1073. if(attackingHeroInstance)
  1074. if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor())
  1075. heroName = attackingHeroInstance->name;
  1076. if(defendingHeroInstance)
  1077. if(defendingHeroInstance->tempOwner == curInt->cb->getMyColor())
  1078. heroName = defendingHeroInstance->name;
  1079. //calculating text
  1080. char buffer[1000];
  1081. sprintf(buffer, CGI->generaltexth->allTexts[340].c_str(), heroName.c_str()); //The Shackles of War are present. %s can not retreat!
  1082. //printing message
  1083. curInt->showInfoDialog(std::string(buffer), comps);
  1084. }
  1085. }
  1086. void CBattleInterface::reallyFlee()
  1087. {
  1088. giveCommand(BattleAction::RETREAT,0,0);
  1089. CCS->curh->changeGraphic(0, 0);
  1090. }
  1091. void CBattleInterface::reallySurrender()
  1092. {
  1093. if(curInt->cb->getResourceAmount(Res::GOLD) < curInt->cb->battleGetSurrenderCost())
  1094. {
  1095. curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
  1096. }
  1097. else
  1098. {
  1099. giveCommand(BattleAction::SURRENDER,0,0);
  1100. CCS->curh->changeGraphic(0, 0);
  1101. }
  1102. }
  1103. void CBattleInterface::bAutofightf()
  1104. {
  1105. if(spellDestSelectMode) //we are casting a spell
  1106. return;
  1107. }
  1108. void CBattleInterface::bSpellf()
  1109. {
  1110. if(spellDestSelectMode) //we are casting a spell
  1111. return;
  1112. CCS->curh->changeGraphic(0,0);
  1113. if(!myTurn)
  1114. return;
  1115. auto myHero = currentHero();
  1116. ESpellCastProblem::ESpellCastProblem spellCastProblem;
  1117. if (curInt->cb->battleCanCastSpell(&spellCastProblem))
  1118. {
  1119. CSpellWindow * spellWindow = new CSpellWindow(genRect(595, 620, (screen->w - 620)/2, (screen->h - 595)/2), myHero, curInt);
  1120. GH.pushInt(spellWindow);
  1121. }
  1122. else if(spellCastProblem == ESpellCastProblem::MAGIC_IS_BLOCKED)
  1123. {
  1124. //Handle Orb of Inhibition-like effects -> we want to display dialog with info, why casting is impossible
  1125. auto blockingBonus = currentHero()->getBonusLocalFirst(Selector::type(Bonus::BLOCK_ALL_MAGIC));
  1126. if(!blockingBonus)
  1127. return;;
  1128. if(blockingBonus->source == Bonus::ARTIFACT)
  1129. {
  1130. const int artID = blockingBonus->sid;
  1131. //If we have artifact, put name of our hero. Otherwise assume it's the enemy.
  1132. //TODO check who *really* is source of bonus
  1133. std::string heroName = myHero->hasArt(artID) ? myHero->name : enemyHero().name;
  1134. //%s wields the %s, an ancient artifact which creates a p dead to all magic.
  1135. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[683])
  1136. % heroName % CGI->arth->artifacts[artID]->Name()));
  1137. }
  1138. }
  1139. }
  1140. void CBattleInterface::bWaitf()
  1141. {
  1142. if(spellDestSelectMode) //we are casting a spell
  1143. return;
  1144. if(activeStack != NULL)
  1145. giveCommand(8,0,activeStack->ID);
  1146. }
  1147. void CBattleInterface::bDefencef()
  1148. {
  1149. if(spellDestSelectMode) //we are casting a spell
  1150. return;
  1151. if(activeStack != NULL)
  1152. giveCommand(3,0,activeStack->ID);
  1153. }
  1154. void CBattleInterface::bConsoleUpf()
  1155. {
  1156. if(spellDestSelectMode) //we are casting a spell
  1157. return;
  1158. console->scrollUp();
  1159. }
  1160. void CBattleInterface::bConsoleDownf()
  1161. {
  1162. if(spellDestSelectMode) //we are casting a spell
  1163. return;
  1164. console->scrollDown();
  1165. }
  1166. void CBattleInterface::newStack(const CStack * stack)
  1167. {
  1168. Point coords = CClickableHex::getXYUnitAnim(stack->position, stack->owner == attackingHeroInstance->tempOwner, stack, this);
  1169. if(stack->position < 0) //turret
  1170. {
  1171. const CCreature & turretCreature = *CGI->creh->creatures[siegeH->town->town->clientInfo.siegeShooter];
  1172. creAnims[stack->ID] = new CCreatureAnimation(turretCreature.animDefName);
  1173. // Turret positions are read out of the /config/wall_pos.txt
  1174. int posID = 0;
  1175. switch (stack->position)
  1176. {
  1177. case -2: // keep creature
  1178. posID = 18;
  1179. break;
  1180. case -3: // bottom creature
  1181. posID = 19;
  1182. break;
  1183. case -4: // upper creature
  1184. posID = 20;
  1185. break;
  1186. }
  1187. if (posID != 0)
  1188. {
  1189. coords.x = siegeH->town->town->clientInfo.siegePositions[posID].x + this->pos.x;
  1190. coords.y = siegeH->town->town->clientInfo.siegePositions[posID].y + this->pos.y;
  1191. }
  1192. }
  1193. else
  1194. {
  1195. creAnims[stack->ID] = new CCreatureAnimation(stack->getCreature()->animDefName);
  1196. }
  1197. creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  1198. creAnims[stack->ID]->pos = Rect(coords.x, coords.y, creAnims[stack->ID]->fullWidth, creAnims[stack->ID]->fullHeight);
  1199. creDir[stack->ID] = stack->attackerOwned;
  1200. }
  1201. void CBattleInterface::stackRemoved(int stackID)
  1202. {
  1203. delete creAnims[stackID];
  1204. creAnims.erase(stackID);
  1205. creDir.erase(stackID);
  1206. redrawBackgroundWithHexes(activeStack);
  1207. queue->update();
  1208. }
  1209. void CBattleInterface::stackActivated(const CStack * stack) //TODO: check it all before game state is changed due to abilities
  1210. {
  1211. //givenCommand = NULL;
  1212. stackToActivate = stack;
  1213. waitForAnims();
  1214. //if(pendingAnims.size() == 0)
  1215. if(stackToActivate) //during waiting stack may have gotten activated through show
  1216. activateStack();
  1217. }
  1218. void CBattleInterface::stackMoved(const CStack * stack, std::vector<BattleHex> destHex, int distance)
  1219. {
  1220. addNewAnim(new CMovementAnimation(this, stack, destHex, distance));
  1221. waitForAnims();
  1222. }
  1223. void CBattleInterface::stacksAreAttacked(std::vector<StackAttackedInfo> attackedInfos)
  1224. {
  1225. for (size_t h = 0; h < attackedInfos.size(); ++h)
  1226. {
  1227. if (!attackedInfos[h].cloneKilled) //FIXME: play dead animation for cloned creature before it vanishes
  1228. addNewAnim(new CDefenceAnimation(attackedInfos[h], this));
  1229. if (attackedInfos[h].rebirth)
  1230. {
  1231. displayEffect(50, attackedInfos[h].defender->position); //TODO: play reverse death animation
  1232. CCS->soundh->playSound(soundBase::RESURECT);
  1233. }
  1234. }
  1235. waitForAnims();
  1236. int targets = 0, killed = 0, damage = 0;
  1237. for(size_t h = 0; h < attackedInfos.size(); ++h)
  1238. {
  1239. ++targets;
  1240. killed += attackedInfos[h].amountKilled;
  1241. damage += attackedInfos[h].dmg;
  1242. }
  1243. if (attackedInfos.front().cloneKilled) //FIXME: cloned stack is already removed
  1244. return;
  1245. if (targets > 1)
  1246. printConsoleAttacked(attackedInfos.front().defender, damage, killed, attackedInfos.front().attacker, true); //creatures perish
  1247. else
  1248. printConsoleAttacked(attackedInfos.front().defender, damage, killed, attackedInfos.front().attacker, false);
  1249. for(size_t h = 0; h < attackedInfos.size(); ++h)
  1250. {
  1251. if (attackedInfos[h].rebirth)
  1252. creAnims[attackedInfos[h].defender->ID]->setType(CCreatureAnim::HOLDING);
  1253. if (attackedInfos[h].cloneKilled)
  1254. stackRemoved(attackedInfos[h].defender->ID);
  1255. }
  1256. }
  1257. void CBattleInterface::stackAttacking( const CStack * attacker, BattleHex dest, const CStack * attacked, bool shooting )
  1258. {
  1259. if (shooting)
  1260. {
  1261. addNewAnim(new CShootingAnimation(this, attacker, dest, attacked));
  1262. }
  1263. else
  1264. {
  1265. addNewAnim(new CMeleeAttackAnimation(this, attacker, dest, attacked));
  1266. }
  1267. waitForAnims();
  1268. }
  1269. void CBattleInterface::newRoundFirst( int round )
  1270. {
  1271. //handle regeneration
  1272. std::vector<const CStack*> stacks = curInt->cb->battleGetStacks(); //gets only alive stacks
  1273. // BOOST_FOREACH(const CStack *s, stacks)
  1274. // {
  1275. // }
  1276. waitForAnims();
  1277. }
  1278. void CBattleInterface::newRound(int number)
  1279. {
  1280. console->addText(CGI->generaltexth->allTexts[412]);
  1281. //unlock spellbook
  1282. //bSpell->block(!curInt->cb->battleCanCastSpell());
  1283. //don't unlock spellbook - this should be done when we have axctive creature
  1284. }
  1285. void CBattleInterface::giveCommand(ui8 action, BattleHex tile, ui32 stackID, si32 additional, si32 selected)
  1286. {
  1287. const CStack *stack = curInt->cb->battleGetStackByID(stackID);
  1288. if(!stack && action != BattleAction::HERO_SPELL && action != BattleAction::RETREAT && action != BattleAction::SURRENDER)
  1289. {
  1290. return;
  1291. }
  1292. if(stack && stack != activeStack)
  1293. tlog3 << "Warning: giving an order to a non-active stack?\n";
  1294. BattleAction * ba = new BattleAction(); //is deleted in CPlayerInterface::activeStack()
  1295. ba->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
  1296. ba->actionType = action;
  1297. ba->destinationTile = tile;
  1298. ba->stackNumber = stackID;
  1299. ba->additionalInfo = additional;
  1300. ba->selectedStack = selected;
  1301. //some basic validations
  1302. switch(action)
  1303. {
  1304. case BattleAction::WALK_AND_ATTACK:
  1305. assert(curInt->cb->battleGetStackByPos(additional)); //stack to attack must exist
  1306. case BattleAction::WALK:
  1307. case BattleAction::SHOOT:
  1308. case BattleAction::CATAPULT:
  1309. assert(tile < GameConstants::BFIELD_SIZE);
  1310. break;
  1311. }
  1312. if(!tacticsMode)
  1313. {
  1314. tlog5 << "Setting command for " << (stack ? stack->nodeName() : "hero") << std::endl;
  1315. myTurn = false;
  1316. activeStack = NULL;
  1317. givenCommand->setn(ba);
  1318. }
  1319. else
  1320. {
  1321. curInt->cb->battleMakeTacticAction(ba);
  1322. vstd::clear_pointer(ba);
  1323. activeStack = NULL;
  1324. //next stack will be activated when action ends
  1325. }
  1326. }
  1327. bool CBattleInterface::isTileAttackable(const BattleHex & number) const
  1328. {
  1329. for(size_t b=0; b<occupyableHexes.size(); ++b)
  1330. {
  1331. if(BattleHex::mutualPosition(occupyableHexes[b], number) != -1 || occupyableHexes[b] == number)
  1332. return true;
  1333. }
  1334. return false;
  1335. }
  1336. bool CBattleInterface::isCatapultAttackable(BattleHex hex) const
  1337. {
  1338. if(!siegeH || tacticsMode)
  1339. return false;
  1340. int wallUnder = curInt->cb->battleHexToWallPart(hex);
  1341. if(wallUnder < 0) //invalid or indestructible
  1342. return false;
  1343. return curInt->cb->battleGetWallState(wallUnder) < EWallState::DESTROYED;
  1344. }
  1345. const CGHeroInstance * CBattleInterface::getActiveHero()
  1346. {
  1347. const CStack * attacker = activeStack;
  1348. if (!attacker)
  1349. {
  1350. return NULL;
  1351. }
  1352. if (attacker->attackerOwned)
  1353. {
  1354. return attackingHeroInstance;
  1355. }
  1356. return defendingHeroInstance;
  1357. }
  1358. void CBattleInterface::hexLclicked(int whichOne)
  1359. {
  1360. handleHex(whichOne, LCLICK);
  1361. }
  1362. void CBattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  1363. {
  1364. for(std::set< std::pair< std::pair< ui8, si16 >, ui8> >::const_iterator it = ca.attackedParts.begin(); it != ca.attackedParts.end(); ++it)
  1365. {
  1366. const CStack * stack = curInt->cb->battleGetStackByID(ca.attacker);
  1367. addNewAnim(new CShootingAnimation(this, stack, it->first.second, NULL, true, it->second));
  1368. SDL_FreeSurface(siegeH->walls[it->first.first + 2]);
  1369. siegeH->walls[it->first.first + 2] = BitmapHandler::loadBitmap(
  1370. siegeH->getSiegeName(it->first.first + 2, curInt->cb->battleGetWallState(it->first.first)) );
  1371. }
  1372. waitForAnims();
  1373. }
  1374. void CBattleInterface::battleFinished(const BattleResult& br)
  1375. {
  1376. bresult = &br;
  1377. {
  1378. auto unlockPim = vstd::makeUnlockGuard(*LOCPLINT->pim);
  1379. animsAreDisplayed.waitUntil(false);
  1380. }
  1381. displayBattleFinished();
  1382. activeStack = NULL;
  1383. }
  1384. void CBattleInterface::displayBattleFinished()
  1385. {
  1386. CCS->curh->changeGraphic(0,0);
  1387. SDL_Rect temp_rect = genRect(561, 470, (screen->w - 800)/2 + 165, (screen->h - 600)/2 + 19);
  1388. resWindow = new CBattleResultWindow(*bresult, temp_rect, this);
  1389. GH.pushInt(resWindow);
  1390. }
  1391. void CBattleInterface::spellCast( const BattleSpellCast * sc )
  1392. {
  1393. const CSpell &spell = *CGI->spellh->spells[sc->id];
  1394. //spell opening battle is cast when no stack is active
  1395. if(sc->castedByHero && ( activeStack == NULL || sc->side == !activeStack->attackerOwned) )
  1396. bSpell->block(true);
  1397. std::vector< std::string > anims; //for magic arrow and ice bolt
  1398. if (vstd::contains(CCS->soundh->spellSounds, &spell))
  1399. CCS->soundh->playSound(CCS->soundh->spellSounds[&spell]);
  1400. switch(sc->id)
  1401. {
  1402. case Spells::MAGIC_ARROW:
  1403. {
  1404. //initialization of anims
  1405. anims.push_back("C20SPX0.DEF"); anims.push_back("C20SPX1.DEF"); anims.push_back("C20SPX2.DEF"); anims.push_back("C20SPX3.DEF"); anims.push_back("C20SPX4.DEF");
  1406. }
  1407. case Spells::ICE_BOLT:
  1408. {
  1409. if(anims.size() == 0) //initialization of anims
  1410. {
  1411. anims.push_back("C08SPW0.DEF"); anims.push_back("C08SPW1.DEF"); anims.push_back("C08SPW2.DEF"); anims.push_back("C08SPW3.DEF"); anims.push_back("C08SPW4.DEF");
  1412. }
  1413. } //end of ice bolt only part
  1414. { //common ice bolt and magic arrow part
  1415. //initial variables
  1416. std::string animToDisplay;
  1417. Point srccoord = (sc->side ? Point(770, 60) : Point(30, 60)) + pos;
  1418. Point destcoord = CClickableHex::getXYUnitAnim(sc->tile, !sc->side, curInt->cb->battleGetStackByPos(sc->tile), this); //position attacked by arrow
  1419. destcoord.x += 250; destcoord.y += 240;
  1420. //animation angle
  1421. double angle = atan2(static_cast<double>(destcoord.x - srccoord.x), static_cast<double>(destcoord.y - srccoord.y));
  1422. bool Vflip = false;
  1423. if (angle < 0)
  1424. {
  1425. Vflip = true;
  1426. angle = -angle;
  1427. }
  1428. //choosing animation by angle
  1429. if(angle > 1.50)
  1430. animToDisplay = anims[0];
  1431. else if(angle > 1.20)
  1432. animToDisplay = anims[1];
  1433. else if(angle > 0.90)
  1434. animToDisplay = anims[2];
  1435. else if(angle > 0.60)
  1436. animToDisplay = anims[3];
  1437. else
  1438. animToDisplay = anims[4];
  1439. //displaying animation
  1440. CDefEssential * animDef = CDefHandler::giveDefEss(animToDisplay);
  1441. int steps = sqrt(static_cast<double>((destcoord.x - srccoord.x)*(destcoord.x - srccoord.x) + (destcoord.y - srccoord.y) * (destcoord.y - srccoord.y))) / 40;
  1442. if(steps <= 0)
  1443. steps = 1;
  1444. int dx = (destcoord.x - srccoord.x - animDef->ourImages[0].bitmap->w)/steps, dy = (destcoord.y - srccoord.y - animDef->ourImages[0].bitmap->h)/steps;
  1445. delete animDef;
  1446. addNewAnim(new CSpellEffectAnimation(this, animToDisplay, srccoord.x, srccoord.y, dx, dy, Vflip));
  1447. break; //for 15 and 16 cases
  1448. }
  1449. case Spells::LIGHTNING_BOLT:
  1450. case Spells::TITANS_LIGHTNING_BOLT:
  1451. case Spells::THUNDERBOLT:
  1452. case Spells::CHAIN_LIGHTNING: //TODO: zigzag effect
  1453. for (auto it = sc->affectedCres.begin(); it != sc->affectedCres.end(); ++it) //in case we have multiple targets
  1454. {
  1455. displayEffect(1, curInt->cb->battleGetStackByID(*it, false)->position);
  1456. displayEffect(spell.mainEffectAnim, curInt->cb->battleGetStackByID(*it, false)->position);
  1457. }
  1458. break;
  1459. case Spells::DISPEL:
  1460. case Spells::CURE:
  1461. case Spells::RESURRECTION:
  1462. case Spells::ANIMATE_DEAD:
  1463. case Spells::DISPEL_HELPFUL_SPELLS:
  1464. case Spells::SACRIFICE: //TODO: animation upon killed stack
  1465. for(std::set<ui32>::const_iterator it = sc->affectedCres.begin(); it != sc->affectedCres.end(); ++it)
  1466. {
  1467. displayEffect(spell.mainEffectAnim, curInt->cb->battleGetStackByID(*it, false)->position);
  1468. }
  1469. break;
  1470. case Spells::SUMMON_FIRE_ELEMENTAL:
  1471. case Spells::SUMMON_EARTH_ELEMENTAL:
  1472. case Spells::SUMMON_WATER_ELEMENTAL:
  1473. case Spells::SUMMON_AIR_ELEMENTAL:
  1474. case Spells::CLONE:
  1475. case Spells::REMOVE_OBSTACLE:
  1476. addNewAnim(new CDummyAnimation(this, 2)); //interface won't return until animation is played. TODO: make it smarter?
  1477. break;
  1478. } //switch(sc->id)
  1479. //support for resistance
  1480. for(size_t j = 0; j < sc->resisted.size(); ++j)
  1481. {
  1482. int tile = curInt->cb->battleGetStackByID(sc->resisted[j])->position;
  1483. displayEffect(78, tile);
  1484. }
  1485. //displaying message in console
  1486. bool customSpell = false;
  1487. bool plural = false; //add singular / plural form of creature text if this is true
  1488. int textID = 0;
  1489. if(sc->affectedCres.size() == 1)
  1490. {
  1491. std::string text = CGI->generaltexth->allTexts[195];
  1492. if(sc->castedByHero)
  1493. {
  1494. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetFightingHero(sc->side)->name);
  1495. boost::algorithm::replace_first(text, "%s", CGI->spellh->spells[sc->id]->name); //spell name
  1496. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin(), false)->getCreature()->namePl ); //target
  1497. }
  1498. else
  1499. {
  1500. switch(sc->id)
  1501. {
  1502. case Spells::STONE_GAZE:
  1503. customSpell = true;
  1504. plural = true;
  1505. textID = 558;
  1506. break;
  1507. case Spells::POISON:
  1508. customSpell = true;
  1509. plural = true;
  1510. textID = 561;
  1511. break;
  1512. case Spells::BIND:
  1513. customSpell = true;
  1514. text = CGI->generaltexth->allTexts[560];
  1515. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin(), false)->getCreature()->namePl );
  1516. break; //Roots and vines bind the %s to the ground!
  1517. case Spells::DISEASE:
  1518. customSpell = true;
  1519. plural = true;
  1520. textID = 553;
  1521. break;
  1522. case Spells::PARALYZE:
  1523. customSpell = true;
  1524. plural = true;
  1525. textID = 563;
  1526. break;
  1527. case Spells::AGE:
  1528. {
  1529. customSpell = true;
  1530. if (curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->count > 1)
  1531. {
  1532. text = CGI->generaltexth->allTexts[552];
  1533. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->namePl);
  1534. }
  1535. else
  1536. {
  1537. text = CGI->generaltexth->allTexts[551];
  1538. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->nameSing);
  1539. }
  1540. //The %s shrivel with age, and lose %d hit points."
  1541. TBonusListPtr bl = curInt->cb->battleGetStackByID(*sc->affectedCres.begin(), false)->getBonuses(Selector::type(Bonus::STACK_HEALTH));
  1542. bl->remove_if(Selector::source(Bonus::SPELL_EFFECT, 75));
  1543. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(bl->totalValue()/2));
  1544. }
  1545. break;
  1546. case Spells::THUNDERBOLT:
  1547. text = CGI->generaltexth->allTexts[367];
  1548. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->namePl);
  1549. console->addText(text);
  1550. text = CGI->generaltexth->allTexts[343].substr(1, CGI->generaltexth->allTexts[343].size() - 1); //Does %d points of damage.
  1551. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(sc->dmgToDisplay)); //no more text afterwards
  1552. console->addText(text);
  1553. customSpell = true;
  1554. text = ""; //yeah, it's a terrible mess
  1555. break;
  1556. case Spells::DISPEL_HELPFUL_SPELLS:
  1557. text = CGI->generaltexth->allTexts[555];
  1558. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->namePl);
  1559. customSpell = true;
  1560. break;
  1561. case Spells::DEATH_STARE:
  1562. customSpell = true;
  1563. if (sc->dmgToDisplay)
  1564. {
  1565. if (sc->dmgToDisplay > 1)
  1566. {
  1567. text = CGI->generaltexth->allTexts[119]; //%d %s die under the terrible gaze of the %s.
  1568. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(sc->dmgToDisplay));
  1569. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin(), false)->getCreature()->namePl );
  1570. }
  1571. else
  1572. {
  1573. text = CGI->generaltexth->allTexts[118]; //One %s dies under the terrible gaze of the %s.
  1574. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->nameSing);
  1575. }
  1576. boost::algorithm::replace_first(text, "%s", CGI->creh->creatures[sc->attackerType]->namePl); //casting stack
  1577. }
  1578. else
  1579. text = "";
  1580. break;
  1581. default:
  1582. text = CGI->generaltexth->allTexts[565]; //The %s casts %s
  1583. boost::algorithm::replace_first(text, "%s", CGI->creh->creatures[sc->attackerType]->namePl); //casting stack
  1584. }
  1585. if (plural)
  1586. {
  1587. if (curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->count > 1)
  1588. {
  1589. text = CGI->generaltexth->allTexts[textID + 1];
  1590. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->getName());
  1591. }
  1592. else
  1593. {
  1594. text = CGI->generaltexth->allTexts[textID];
  1595. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->getName());
  1596. }
  1597. }
  1598. }
  1599. if (!customSpell && !sc->dmgToDisplay)
  1600. boost::algorithm::replace_first(text, "%s", CGI->spellh->spells[sc->id]->name); //simple spell name
  1601. if (text.size())
  1602. console->addText(text);
  1603. }
  1604. else
  1605. {
  1606. std::string text = CGI->generaltexth->allTexts[196];
  1607. if(sc->castedByHero)
  1608. {
  1609. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetFightingHero(sc->side)->name);
  1610. }
  1611. else if(sc->attackerType < CGI->creh->creatures.size())
  1612. {
  1613. boost::algorithm::replace_first(text, "%s", CGI->creh->creatures[sc->attackerType]->namePl); //creature caster
  1614. }
  1615. else
  1616. {
  1617. //TODO artifacts that cast spell; scripts some day
  1618. boost::algorithm::replace_first(text, "%s", "Something");
  1619. }
  1620. boost::algorithm::replace_first(text, "%s", CGI->spellh->spells[sc->id]->name);
  1621. console->addText(text);
  1622. }
  1623. if(sc->dmgToDisplay && !customSpell)
  1624. {
  1625. std::string dmgInfo = CGI->generaltexth->allTexts[376];
  1626. boost::algorithm::replace_first(dmgInfo, "%s", CGI->spellh->spells[sc->id]->name); //simple spell name
  1627. boost::algorithm::replace_first(dmgInfo, "%d", boost::lexical_cast<std::string>(sc->dmgToDisplay));
  1628. console->addText(dmgInfo); //todo: casualties (?)
  1629. }
  1630. waitForAnims();
  1631. //mana absorption
  1632. if (sc->manaGained)
  1633. {
  1634. Point leftHero = Point(15, 30) + pos;
  1635. Point rightHero = Point(755, 30) + pos;
  1636. addNewAnim(new CSpellEffectAnimation(this, sc->side ? "SP07_A.DEF" : "SP07_B.DEF", leftHero.x, leftHero.y, 0, 0, false));
  1637. addNewAnim(new CSpellEffectAnimation(this, sc->side ? "SP07_B.DEF" : "SP07_A.DEF", rightHero.x, rightHero.y, 0, 0, false));
  1638. }
  1639. }
  1640. void CBattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  1641. {
  1642. int effID = sse.effect.back().sid;
  1643. if(effID != -1) //can be -1 for defensive stance effect
  1644. {
  1645. for(std::vector<ui32>::const_iterator ci = sse.stacks.begin(); ci!=sse.stacks.end(); ++ci)
  1646. {
  1647. displayEffect(CGI->spellh->spells[effID]->mainEffectAnim, curInt->cb->battleGetStackByID(*ci)->position);
  1648. }
  1649. }
  1650. else if (sse.stacks.size() == 1 && sse.effect.size() == 2)
  1651. {
  1652. const Bonus & bns = sse.effect.front();
  1653. if (bns.source == Bonus::OTHER && bns.type == Bonus::PRIMARY_SKILL)
  1654. {
  1655. //defensive stance
  1656. const CStack * stack = LOCPLINT->cb->battleGetStackByID(*sse.stacks.begin());
  1657. int txtid = 120;
  1658. if(stack->count != 1)
  1659. txtid++; //move to plural text
  1660. char txt[4000];
  1661. BonusList defenseBonuses = *(stack->getBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE)));
  1662. defenseBonuses.remove_if(Selector::durationType(Bonus::STACK_GETS_TURN)); //remove bonuses gained from defensive stance
  1663. int val = stack->Defense() - defenseBonuses.totalValue();
  1664. sprintf(txt, CGI->generaltexth->allTexts[txtid].c_str(), (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str(), val);
  1665. console->addText(txt);
  1666. }
  1667. }
  1668. if (activeStack != NULL) //it can be -1 when a creature casts effect
  1669. {
  1670. redrawBackgroundWithHexes(activeStack);
  1671. }
  1672. }
  1673. void CBattleInterface::castThisSpell(int spellID)
  1674. {
  1675. BattleAction * ba = new BattleAction;
  1676. ba->actionType = BattleAction::HERO_SPELL;
  1677. ba->additionalInfo = spellID; //spell number
  1678. ba->destinationTile = -1;
  1679. ba->stackNumber = (attackingHeroInstance->tempOwner == curInt->playerID) ? -1 : -2;
  1680. ba->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
  1681. spellToCast = ba;
  1682. spellDestSelectMode = true;
  1683. //choosing possible tragets
  1684. const CGHeroInstance * castingHero = (attackingHeroInstance->tempOwner == curInt->playerID) ? attackingHeroInstance : defendingHeroInstance;
  1685. sp = CGI->spellh->spells[spellID];
  1686. spellSelMode = ANY_LOCATION;
  1687. if(sp->getTargetType() == CSpell::CREATURE)
  1688. {
  1689. spellSelMode = selectionTypeByPositiveness(*sp);
  1690. }
  1691. if(sp->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  1692. {
  1693. if(castingHero && castingHero->getSpellSchoolLevel(sp) < 3)
  1694. spellSelMode = selectionTypeByPositiveness(*sp);
  1695. else
  1696. spellSelMode = NO_LOCATION;
  1697. }
  1698. if(sp->getTargetType() == CSpell::OBSTACLE)
  1699. {
  1700. spellSelMode = OBSTACLE;
  1701. } //FIXME: Remove Obstacle has range X, unfortunatelly :(
  1702. else if(sp->range[ castingHero->getSpellSchoolLevel(sp) ] == "X") //spell has no range
  1703. {
  1704. spellSelMode = NO_LOCATION;
  1705. }
  1706. if(sp->range[ castingHero->getSpellSchoolLevel(sp) ].size() > 1) //spell has many-hex range
  1707. {
  1708. spellSelMode = ANY_LOCATION;
  1709. }
  1710. if(spellID == Spells::FIRE_WALL || spellID == Spells::FORCE_FIELD)
  1711. {
  1712. spellSelMode = FREE_LOCATION;
  1713. }
  1714. if (spellSelMode == NO_LOCATION) //user does not have to select location
  1715. {
  1716. spellToCast->destinationTile = -1;
  1717. curInt->cb->battleMakeAction(spellToCast);
  1718. endCastingSpell();
  1719. }
  1720. else
  1721. {
  1722. possibleActions.clear();
  1723. possibleActions.push_back (spellSelMode); //only this one action can be performed at the moment
  1724. GH.fakeMouseMove();//update cursor
  1725. }
  1726. }
  1727. void CBattleInterface::displayEffect(ui32 effect, int destTile)
  1728. {
  1729. addNewAnim(new CSpellEffectAnimation(this, effect, destTile));
  1730. }
  1731. void CBattleInterface::battleTriggerEffect(const BattleTriggerEffect & bte)
  1732. {
  1733. const CStack * stack = curInt->cb->battleGetStackByID(bte.stackID);
  1734. //don't show animation when no HP is regenerated
  1735. switch (bte.effect)
  1736. {
  1737. case Bonus::HP_REGENERATION:
  1738. displayEffect(74, stack->position);
  1739. CCS->soundh->playSound(soundBase::REGENER);
  1740. break;
  1741. case Bonus::MANA_DRAIN:
  1742. displayEffect(77, stack->position);
  1743. CCS->soundh->playSound(soundBase::MANADRAI);
  1744. break;
  1745. case Bonus::POISON:
  1746. displayEffect(67, stack->position);
  1747. CCS->soundh->playSound(soundBase::POISON);
  1748. break;
  1749. case Bonus::FEAR:
  1750. displayEffect(15, stack->position);
  1751. CCS->soundh->playSound(soundBase::FEAR);
  1752. break;
  1753. case Bonus::MORALE:
  1754. {
  1755. std::string hlp = CGI->generaltexth->allTexts[33];
  1756. boost::algorithm::replace_first(hlp,"%s",(stack->getName()));
  1757. displayEffect(20,stack->position);
  1758. console->addText(hlp);
  1759. break;
  1760. }
  1761. default:
  1762. return;
  1763. }
  1764. //waitForAnims(); //fixme: freezes game :?
  1765. }
  1766. void CBattleInterface::setAnimSpeed(int set)
  1767. {
  1768. Settings speed = settings.write["battle"]["animationSpeed"];
  1769. speed->Float() = set;
  1770. }
  1771. int CBattleInterface::getAnimSpeed() const
  1772. {
  1773. return settings["battle"]["animationSpeed"].Float();
  1774. }
  1775. void CBattleInterface::activateStack()
  1776. {
  1777. activeStack = stackToActivate;
  1778. stackToActivate = NULL;
  1779. const CStack *s = activeStack;
  1780. myTurn = true;
  1781. if(attackerInt && defenderInt) //hotseat -> need to pick which interface "takes over" as active
  1782. curInt = attackerInt->playerID == s->owner ? attackerInt : defenderInt;
  1783. queue->update();
  1784. redrawBackgroundWithHexes(activeStack);
  1785. bWait->block(s->waited()); //block waiting button if stack has been already waiting
  1786. //block cast spell button if hero doesn't have a spellbook
  1787. ESpellCastProblem::ESpellCastProblem spellcastingProblem;
  1788. bool canCastSpells = curInt->cb->battleCanCastSpell(&spellcastingProblem);
  1789. bSpell->block(!canCastSpells && spellcastingProblem != ESpellCastProblem::MAGIC_IS_BLOCKED); //if magic is blocked, we leave button active, so the message can be displayed (cf bug #97)
  1790. bSurrender->block((curInt == attackerInt ? defendingHeroInstance : attackingHeroInstance) == NULL);
  1791. bFlee->block(!curInt->cb->battleCanFlee());
  1792. bSurrender->block(curInt->cb->battleGetSurrenderCost() < 0);
  1793. //set casting flag to true if creature can use it to not check it every time
  1794. const Bonus *spellcaster = s->getBonusLocalFirst(Selector::type(Bonus::SPELLCASTER)),
  1795. *randomSpellcaster = s->getBonusLocalFirst(Selector::type(Bonus::RANDOM_SPELLCASTER));
  1796. if (s->casts && (spellcaster || randomSpellcaster))
  1797. {
  1798. stackCanCastSpell = true;
  1799. if(randomSpellcaster)
  1800. creatureSpellToCast = -1;
  1801. else
  1802. creatureSpellToCast = curInt->cb->battleGetRandomStackSpell(s, CBattleInfoCallback::RANDOM_AIMED); //faerie dragon can cast only one spell until their next move
  1803. }
  1804. else
  1805. {
  1806. stackCanCastSpell = false;
  1807. creatureSpellToCast = -1;
  1808. }
  1809. getPossibleActionsForStack (s);
  1810. if(!pendingAnims.size() && !active)
  1811. activate();
  1812. GH.fakeMouseMove();
  1813. }
  1814. double CBattleInterface::getAnimSpeedMultiplier() const
  1815. {
  1816. switch(getAnimSpeed())
  1817. {
  1818. case 1:
  1819. return 3.5;
  1820. case 2:
  1821. return 2.2;
  1822. case 4:
  1823. return 1.0;
  1824. default:
  1825. return 0.0;
  1826. }
  1827. }
  1828. void CBattleInterface::endCastingSpell()
  1829. {
  1830. assert(spellDestSelectMode);
  1831. delete spellToCast;
  1832. spellToCast = NULL;
  1833. sp = NULL;
  1834. spellDestSelectMode = false;
  1835. CCS->curh->changeGraphic(1, 6);
  1836. if (activeStack)
  1837. {
  1838. getPossibleActionsForStack (activeStack); //restore actions after they were cleared
  1839. myTurn = true;
  1840. }
  1841. }
  1842. void CBattleInterface::getPossibleActionsForStack(const CStack * stack)
  1843. {
  1844. possibleActions.clear();
  1845. if (tacticsMode)
  1846. {
  1847. possibleActions += MOVE_TACTICS, CHOOSE_TACTICS_STACK;
  1848. }
  1849. else
  1850. {
  1851. //first action will be prioritized over later ones
  1852. if (stack->casts) //TODO: check for battlefield effects that prevent casting?
  1853. {
  1854. if (stack->hasBonusOfType (Bonus::SPELLCASTER))
  1855. {
  1856. //TODO: poll possible spells
  1857. const CSpell * spell;
  1858. BonusList spellBonuses = *stack->getBonuses (Selector::type(Bonus::SPELLCASTER));
  1859. BOOST_FOREACH (Bonus * spellBonus, spellBonuses)
  1860. {
  1861. spell = CGI->spellh->spells[spellBonus->subtype];
  1862. if (spell->isRisingSpell())
  1863. {
  1864. possibleActions.push_back (RISING_SPELL);
  1865. }
  1866. //possibleActions.push_back (NO_LOCATION);
  1867. //possibleActions.push_back (ANY_LOCATION);
  1868. //TODO: allow stacks cast aimed spells
  1869. //possibleActions.push_back (OTHER_SPELL);
  1870. else
  1871. {
  1872. switch (spellBonus->subtype)
  1873. {
  1874. case Spells::REMOVE_OBSTACLE:
  1875. possibleActions.push_back (OBSTACLE);
  1876. break;
  1877. default:
  1878. possibleActions.push_back (selectionTypeByPositiveness (*spell));
  1879. break;
  1880. }
  1881. }
  1882. }
  1883. std::sort(possibleActions.begin(), possibleActions.end());
  1884. auto it = std::unique (possibleActions.begin(), possibleActions.end());
  1885. possibleActions.erase (it, possibleActions.end());
  1886. }
  1887. if (stack->hasBonusOfType (Bonus::RANDOM_SPELLCASTER))
  1888. possibleActions.push_back (RANDOM_GENIE_SPELL);
  1889. if (stack->hasBonusOfType (Bonus::DAEMON_SUMMONING))
  1890. possibleActions.push_back (RISE_DEMONS);
  1891. }
  1892. if (stack->shots && stack->hasBonusOfType (Bonus::SHOOTER))
  1893. possibleActions.push_back (SHOOT);
  1894. if (stack->hasBonusOfType (Bonus::RETURN_AFTER_STRIKE))
  1895. possibleActions.push_back (ATTACK_AND_RETURN);
  1896. possibleActions.push_back(ATTACK); //all active stacks can attack
  1897. possibleActions.push_back(WALK_AND_ATTACK); //not all stacks can always walk, but we will check this elsewhere
  1898. if (stack->canMove() && stack->Speed()) //probably no reason to try move war machines or bound stacks
  1899. possibleActions.push_back (MOVE_STACK); //all active stacks can attack
  1900. if (siegeH && stack->hasBonusOfType (Bonus::CATAPULT)) //TODO: check shots
  1901. possibleActions.push_back (CATAPULT);
  1902. if (stack->hasBonusOfType (Bonus::HEALER))
  1903. possibleActions.push_back (HEAL);
  1904. }
  1905. }
  1906. void CBattleInterface::showAliveStack(const CStack *stack, SDL_Surface * to)
  1907. {
  1908. int ID = stack->ID;
  1909. if(creAnims.find(ID) == creAnims.end()) //eg. for summoned but not yet handled stacks
  1910. return;
  1911. const CCreature *creature = stack->getCreature();
  1912. SDL_Rect unitRect = {creAnims[ID]->pos.x, creAnims[ID]->pos.y, uint16_t(creAnims[ID]->fullWidth), uint16_t(creAnims[ID]->fullHeight)};
  1913. int animType = creAnims[ID]->getType();
  1914. int affectingSpeed = getAnimSpeed();
  1915. if(animType == 1 || animType == 2) //standing stacks should not stand faster :)
  1916. affectingSpeed = 2;
  1917. bool incrementFrame = (animCount%(4/affectingSpeed)==0) && animType!=5 && animType!=20 && animType!=2;
  1918. if (creature->idNumber == 149)
  1919. {
  1920. // a turret creature has a limited height, so cut it at a certain position; turret creature has no standing anim
  1921. unitRect.h = siegeH->town->town->clientInfo.siegeShooterCropHeight;
  1922. }
  1923. else
  1924. {
  1925. // standing animation
  1926. if(animType == 2)
  1927. {
  1928. if(standingFrame.find(ID)!=standingFrame.end())
  1929. {
  1930. incrementFrame = (animCount%(8/affectingSpeed)==0);
  1931. if(incrementFrame)
  1932. {
  1933. ++standingFrame[ID];
  1934. if(standingFrame[ID] == creAnims[ID]->framesInGroup(CCreatureAnim::HOLDING))
  1935. {
  1936. standingFrame.erase(standingFrame.find(ID));
  1937. }
  1938. }
  1939. }
  1940. else
  1941. {
  1942. if((rand()%50) == 0)
  1943. {
  1944. standingFrame.insert(std::make_pair(ID, 0));
  1945. }
  1946. }
  1947. }
  1948. }
  1949. // As long as the projectile of the shooter-stack is flying incrementFrame should be false
  1950. //bool shootingFinished = true;
  1951. for (std::list<ProjectileInfo>::iterator it = projectiles.begin(); it != projectiles.end(); ++it)
  1952. {
  1953. if (it->stackID == ID)
  1954. {
  1955. //shootingFinished = false;
  1956. if (it->animStartDelay == 0)
  1957. incrementFrame = false;
  1958. }
  1959. }
  1960. // Increment always when moving, never if stack died
  1961. creAnims[ID]->nextFrame(to, unitRect.x, unitRect.y, creDir[ID], animCount, incrementFrame, activeStack && ID==activeStack->ID, ID==mouseHoveredStack, &unitRect);
  1962. //printing amount
  1963. if(stack->count > 0 //don't print if stack is not alive
  1964. && (!curInt->curAction
  1965. || (curInt->curAction->stackNumber != ID //don't print if stack is currently taking an action
  1966. && (curInt->curAction->actionType != BattleAction::WALK_AND_ATTACK || stack->position != curInt->curAction->additionalInfo) //nor if it's an object of attack
  1967. && (curInt->curAction->destinationTile != stack->position) //nor if it's on destination tile for current action
  1968. )
  1969. )
  1970. && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON) //and not a war machine...
  1971. )
  1972. {
  1973. const BattleHex nextPos = stack->position + (stack->attackerOwned ? 1 : -1);
  1974. const bool edge = stack->position % GameConstants::BFIELD_WIDTH == (stack->attackerOwned ? GameConstants::BFIELD_WIDTH - 2 : 1);
  1975. const bool moveInside = !edge && !stackCountOutsideHexes[nextPos];
  1976. int xAdd = (stack->attackerOwned ? 220 : 202) +
  1977. (stack->doubleWide() ? 44 : 0) * (stack->attackerOwned ? +1 : -1) +
  1978. (moveInside ? amountNormal->w + 10 : 0) * (stack->attackerOwned ? -1 : +1);
  1979. int yAdd = 260 + ((stack->attackerOwned || moveInside) ? 0 : -15);
  1980. //blitting amount background box
  1981. SDL_Surface *amountBG = NULL;
  1982. TBonusListPtr spellEffects = stack->getSpellBonuses();
  1983. if(!spellEffects->size())
  1984. {
  1985. amountBG = amountNormal;
  1986. }
  1987. else
  1988. {
  1989. int pos=0; //determining total positiveness of effects
  1990. std::vector<si32> spellIds = stack->activeSpells();
  1991. for(std::vector<si32>::const_iterator it = spellIds.begin(); it != spellIds.end(); it++)
  1992. {
  1993. pos += CGI->spellh->spells[ *it ]->positiveness;
  1994. }
  1995. if(pos > 0)
  1996. {
  1997. amountBG = amountPositive;
  1998. }
  1999. else if(pos < 0)
  2000. {
  2001. amountBG = amountNegative;
  2002. }
  2003. else
  2004. {
  2005. amountBG = amountEffNeutral;
  2006. }
  2007. }
  2008. SDL_Rect temp_rect = genRect(amountNormal->h, amountNormal->w, creAnims[ID]->pos.x + xAdd, creAnims[ID]->pos.y + yAdd);
  2009. SDL_BlitSurface(amountBG, NULL, to, &temp_rect);
  2010. //blitting amount
  2011. CSDL_Ext::printAtMiddle(
  2012. makeNumberShort(stack->count),
  2013. creAnims[ID]->pos.x + xAdd + 15,
  2014. creAnims[ID]->pos.y + yAdd + 5,
  2015. FONT_TINY,
  2016. Colors::WHITE,
  2017. to
  2018. );
  2019. }
  2020. }
  2021. void CBattleInterface::showPieceOfWall(SDL_Surface * to, int hex, const std::vector<const CStack*> & stacks)
  2022. {
  2023. if(!siegeH)
  2024. return;
  2025. #ifdef CPP11_USE_INITIALIZERS_LIST
  2026. //note - std::list<int> must be specified to avoid type deduction by gcc (may not work in other compilers)
  2027. static const std::map<int, std::list<int> > hexToPart = {
  2028. {12, std::list<int>{8, 1, 7}}, {45, std::list<int>{12, 6}},
  2029. {101, std::list<int>{10}}, {118, std::list<int>{2}},
  2030. {165, std::list<int>{11}}, {186, std::list<int>{3}}};
  2031. #else
  2032. using namespace boost::assign;
  2033. std::map<int, std::list<int> > hexToPart;
  2034. hexToPart[12] = list_of<int>(8)(1)(7);
  2035. hexToPart[45] = list_of<int>(12)(6);
  2036. hexToPart[101] = list_of<int>(10);
  2037. hexToPart[118] = list_of<int>(2);
  2038. hexToPart[165] = list_of<int>(11);
  2039. hexToPart[186] = list_of<int>(3);
  2040. #endif
  2041. std::map<int, std::list<int> >::const_iterator it = hexToPart.find(hex);
  2042. if(it != hexToPart.end())
  2043. {
  2044. BOOST_FOREACH(int wallNum, it->second)
  2045. {
  2046. siegeH->printPartOfWall(to, wallNum);
  2047. //print creature in turret
  2048. int posToSeek = -1;
  2049. switch(wallNum)
  2050. {
  2051. case 3: //bottom turret
  2052. posToSeek = -3;
  2053. break;
  2054. case 8: //upper turret
  2055. posToSeek = -4;
  2056. break;
  2057. case 2: //keep
  2058. posToSeek = -2;
  2059. break;
  2060. }
  2061. if(posToSeek != -1)
  2062. {
  2063. const CStack *turret = NULL;
  2064. BOOST_FOREACH(const CStack *s, stacks)
  2065. {
  2066. if(s->position == posToSeek)
  2067. {
  2068. turret = s;
  2069. break;
  2070. }
  2071. }
  2072. if(turret)
  2073. {
  2074. showAliveStack(turret, to);
  2075. //blitting creature cover
  2076. switch(posToSeek)
  2077. {
  2078. case -3: //bottom turret
  2079. siegeH->printPartOfWall(to, 16);
  2080. break;
  2081. case -4: //upper turret
  2082. siegeH->printPartOfWall(to, 17);
  2083. break;
  2084. case -2: //keep
  2085. siegeH->printPartOfWall(to, 15);
  2086. break;
  2087. }
  2088. }
  2089. }
  2090. }
  2091. }
  2092. // Damaged wall below gate have to be drawn earlier than a non-damaged wall below gate.
  2093. if ((hex == 112 && curInt->cb->battleGetWallState(3) == 3) || (hex == 147 && curInt->cb->battleGetWallState(3) != 3))
  2094. siegeH->printPartOfWall(to, 5);
  2095. // Damaged bottom wall have to be drawn earlier than a non-damaged bottom wall.
  2096. if ((hex == 165 && curInt->cb->battleGetWallState(4) == 3) || (hex == 185 && curInt->cb->battleGetWallState(4) != 3))
  2097. siegeH->printPartOfWall(to, 4);
  2098. }
  2099. void CBattleInterface::redrawBackgroundWithHexes(const CStack * activeStack)
  2100. {
  2101. attackableHexes.clear();
  2102. if (activeStack)
  2103. occupyableHexes = curInt->cb->battleGetAvailableHexes(activeStack, true, &attackableHexes);
  2104. curInt->cb->battleGetStackCountOutsideHexes(stackCountOutsideHexes);
  2105. //preparating background graphic with hexes and shaded hexes
  2106. blitAt(background, 0, 0, backgroundWithHexes);
  2107. //draw absolute obstacles (cliffs and so on)
  2108. BOOST_FOREACH(auto &oi, curInt->cb->battleGetAllObstacles())
  2109. {
  2110. if(oi->obstacleType == CObstacleInstance::ABSOLUTE_OBSTACLE/* || oi.obstacleType == CObstacleInstance::MOAT*/)
  2111. blitAt(imageOfObstacle(*oi), oi->getInfo().width, oi->getInfo().height, backgroundWithHexes);
  2112. }
  2113. if(settings["battle"]["cellBorders"].Bool())
  2114. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, NULL, backgroundWithHexes, NULL);
  2115. if(settings["battle"]["stackRange"].Bool())
  2116. {
  2117. std::vector<BattleHex> hexesToShade = occupyableHexes;
  2118. hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
  2119. BOOST_FOREACH(BattleHex hex, hexesToShade)
  2120. {
  2121. int i = hex.getY(); //row
  2122. int j = hex.getX()-1; //column
  2123. int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
  2124. int y = 86 + 42 * i;
  2125. SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
  2126. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, backgroundWithHexes, &temp_rect);
  2127. }
  2128. }
  2129. }
  2130. void CBattleInterface::printConsoleAttacked( const CStack * defender, int dmg, int killed, const CStack * attacker, bool multiple )
  2131. {
  2132. char tabh[200] = {0};
  2133. int end = 0;
  2134. if (attacker) //ignore if stacks were killed by spell
  2135. {
  2136. end = sprintf(tabh, CGI->generaltexth->allTexts[attacker->count > 1 ? 377 : 376].c_str(),
  2137. (attacker->count > 1 ? attacker->getCreature()->namePl.c_str() : attacker->getCreature()->nameSing.c_str()), dmg);
  2138. }
  2139. if(killed > 0)
  2140. {
  2141. if(killed > 1)
  2142. {
  2143. sprintf(tabh + end, CGI->generaltexth->allTexts[379].c_str(), killed,
  2144. multiple ? CGI->generaltexth->allTexts[43].c_str() : defender->getCreature()->namePl.c_str()); // creatures perish
  2145. }
  2146. else //killed == 1
  2147. {
  2148. sprintf(tabh + end, CGI->generaltexth->allTexts[378].c_str(),
  2149. multiple ? CGI->generaltexth->allTexts[42].c_str() : defender->getCreature()->nameSing.c_str()); // creature perishes
  2150. }
  2151. }
  2152. console->addText(std::string(tabh));
  2153. }
  2154. void CBattleInterface::projectileShowHelper(SDL_Surface * to)
  2155. {
  2156. if(to == NULL)
  2157. to = screen;
  2158. std::list< std::list<ProjectileInfo>::iterator > toBeDeleted;
  2159. for(std::list<ProjectileInfo>::iterator it=projectiles.begin(); it!=projectiles.end(); ++it)
  2160. {
  2161. // Creature have to be in a shooting anim and the anim start delay must be over.
  2162. // Otherwise abort to start moving the projectile.
  2163. if (it->animStartDelay > 0)
  2164. {
  2165. if(it->animStartDelay == creAnims[it->stackID]->getAnimationFrame() + 1
  2166. && creAnims[it->stackID]->getType() >= 14 && creAnims[it->stackID]->getType() <= 16)
  2167. it->animStartDelay = 0;
  2168. else
  2169. continue;
  2170. }
  2171. SDL_Rect dst;
  2172. dst.h = idToProjectile[it->creID]->ourImages[it->frameNum].bitmap->h;
  2173. dst.w = idToProjectile[it->creID]->ourImages[it->frameNum].bitmap->w;
  2174. dst.x = it->x;
  2175. dst.y = it->y;
  2176. // The equation below calculates the center pos of the canon, but we need the top left pos
  2177. // of it for drawing
  2178. if (it->catapultInfo)
  2179. {
  2180. dst.x -= 17.;
  2181. dst.y -= 10.;
  2182. }
  2183. if(it->reverse)
  2184. {
  2185. SDL_Surface * rev = CSDL_Ext::rotate01(idToProjectile[it->creID]->ourImages[it->frameNum].bitmap);
  2186. CSDL_Ext::blit8bppAlphaTo24bpp(rev, NULL, to, &dst);
  2187. SDL_FreeSurface(rev);
  2188. }
  2189. else
  2190. {
  2191. CSDL_Ext::blit8bppAlphaTo24bpp(idToProjectile[it->creID]->ourImages[it->frameNum].bitmap, NULL, to, &dst);
  2192. }
  2193. // Update projectile
  2194. ++it->step;
  2195. if(it->step == it->lastStep)
  2196. {
  2197. toBeDeleted.insert(toBeDeleted.end(), it);
  2198. }
  2199. else
  2200. {
  2201. if (it->catapultInfo)
  2202. {
  2203. // Parabolic shot of the trajectory, as follows: f(x) = ax^2 + bx + c
  2204. it->x += it->dx;
  2205. it->y = it->catapultInfo->calculateY(it->x - this->pos.x) + this->pos.y;
  2206. }
  2207. else
  2208. {
  2209. // Normal projectile, just add the calculated "deltas" to the x and y positions.
  2210. it->x += it->dx;
  2211. it->y += it->dy;
  2212. }
  2213. if(it->spin)
  2214. {
  2215. ++(it->frameNum);
  2216. it->frameNum %= idToProjectile[it->creID]->ourImages.size();
  2217. }
  2218. }
  2219. }
  2220. for(std::list< std::list<ProjectileInfo>::iterator >::iterator it = toBeDeleted.begin(); it!= toBeDeleted.end(); ++it)
  2221. {
  2222. projectiles.erase(*it);
  2223. }
  2224. }
  2225. void CBattleInterface::endAction(const BattleAction* action)
  2226. {
  2227. const CStack * stack = curInt->cb->battleGetStackByID(action->stackNumber);
  2228. //if((action->actionType==2 || (action->actionType==6 && action->destinationTile!=cb->battleGetPos(action->stackNumber)))) //activating interface when move is finished
  2229. // {
  2230. // activate();
  2231. // }
  2232. if(action->actionType == BattleAction::HERO_SPELL)
  2233. {
  2234. if(action->side)
  2235. defendingHero->setPhase(0);
  2236. else
  2237. attackingHero->setPhase(0);
  2238. }
  2239. if(stack && action->actionType == BattleAction::WALK && creAnims[action->stackNumber]->getType() != 2) //walk or walk & attack
  2240. {
  2241. pendingAnims.push_back(std::make_pair(new CMovementEndAnimation(this, stack, action->destinationTile), false));
  2242. }
  2243. if(action->actionType == BattleAction::CATAPULT) //catapult
  2244. {
  2245. }
  2246. //check if we should reverse stacks
  2247. //for some strange reason, it's not enough
  2248. // std::set<const CStack *> stacks;
  2249. // stacks.insert(LOCPLINT->cb->battleGetStackByID(action->stackNumber));
  2250. // stacks.insert(LOCPLINT->cb->battleGetStackByPos(action->destinationTile));
  2251. TStacks stacks = curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  2252. BOOST_FOREACH(const CStack *s, stacks)
  2253. {
  2254. if(s && creDir[s->ID] != bool(s->attackerOwned) && s->alive())
  2255. {
  2256. addNewAnim(new CReverseAnimation(this, s, s->position, false));
  2257. }
  2258. }
  2259. queue->update();
  2260. if(tacticsMode) //stack ended movement in tactics phase -> select the next one
  2261. bTacticNextStack(stack);
  2262. if( action->actionType == BattleAction::HERO_SPELL) //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  2263. redrawBackgroundWithHexes(activeStack);
  2264. }
  2265. void CBattleInterface::hideQueue()
  2266. {
  2267. Settings showQueue = settings.write["battle"]["showQueue"];
  2268. showQueue->Bool() = false;
  2269. queue->deactivate();
  2270. if(!queue->embedded)
  2271. {
  2272. moveBy(Point(0, -queue->pos.h / 2));
  2273. GH.totalRedraw();
  2274. }
  2275. }
  2276. void CBattleInterface::showQueue()
  2277. {
  2278. Settings showQueue = settings.write["battle"]["showQueue"];
  2279. showQueue->Bool() = true;
  2280. queue->activate();
  2281. if(!queue->embedded)
  2282. {
  2283. moveBy(Point(0, +queue->pos.h / 2));
  2284. GH.totalRedraw();
  2285. }
  2286. }
  2287. void CBattleInterface::startAction(const BattleAction* action)
  2288. {
  2289. if(action->actionType == BattleAction::END_TACTIC_PHASE)
  2290. {
  2291. SDL_FreeSurface(menu);
  2292. menu = BitmapHandler::loadBitmap("CBAR.bmp");
  2293. graphics->blueToPlayersAdv(menu, curInt->playerID);
  2294. bDefence->block(false);
  2295. bWait->block(false);
  2296. if(active)
  2297. {
  2298. if(btactEnd && btactNext) //if the other side had tactics, there are no buttons
  2299. {
  2300. btactEnd->deactivate();
  2301. btactNext->deactivate();
  2302. bConsoleDown->activate();
  2303. bConsoleUp->activate();
  2304. }
  2305. }
  2306. redraw();
  2307. return;
  2308. }
  2309. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  2310. if(stack)
  2311. {
  2312. queue->update();
  2313. }
  2314. else
  2315. {
  2316. assert(action->actionType == BattleAction::HERO_SPELL); //only cast spell is valid action without acting stack number
  2317. }
  2318. if(action->actionType == BattleAction::WALK
  2319. || (action->actionType == BattleAction::WALK_AND_ATTACK && action->destinationTile != stack->position))
  2320. {
  2321. moveStarted = true;
  2322. if(creAnims[action->stackNumber]->framesInGroup(CCreatureAnim::MOVE_START))
  2323. {
  2324. const CStack * stack = curInt->cb->battleGetStackByID(action->stackNumber);
  2325. pendingAnims.push_back(std::make_pair(new CMovementStartAnimation(this, stack), false));
  2326. }
  2327. }
  2328. if(active)
  2329. deactivate();
  2330. char txt[400];
  2331. if (action->actionType == BattleAction::HERO_SPELL) //when hero casts spell
  2332. {
  2333. if(action->side)
  2334. defendingHero->setPhase(4);
  2335. else
  2336. attackingHero->setPhase(4);
  2337. return;
  2338. }
  2339. if(!stack)
  2340. {
  2341. tlog1<<"Something wrong with stackNumber in actionStarted. Stack number: "<<action->stackNumber<<std::endl;
  2342. return;
  2343. }
  2344. int txtid = 0;
  2345. switch(action->actionType)
  2346. {
  2347. case BattleAction::WAIT:
  2348. txtid = 136;
  2349. break;
  2350. case BattleAction::BAD_MORALE:
  2351. txtid = -34; //negative -> no separate singular/plural form
  2352. displayEffect(30,stack->position);
  2353. break;
  2354. }
  2355. if(txtid > 0 && stack->count != 1)
  2356. txtid++; //move to plural text
  2357. else if(txtid < 0)
  2358. txtid = -txtid;
  2359. if(txtid)
  2360. {
  2361. sprintf(txt, CGI->generaltexth->allTexts[txtid].c_str(), (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str(), 0);
  2362. console->addText(txt);
  2363. }
  2364. //displaying special abilities
  2365. switch (action->actionType)
  2366. {
  2367. case BattleAction::STACK_HEAL:
  2368. displayEffect(74, action->destinationTile);
  2369. CCS->soundh->playSound(soundBase::REGENER);
  2370. break;
  2371. }
  2372. }
  2373. void CBattleInterface::waitForAnims()
  2374. {
  2375. auto unlockPim = vstd::makeUnlockGuard(*LOCPLINT->pim);
  2376. animsAreDisplayed.waitWhileTrue();
  2377. }
  2378. void CBattleInterface::bEndTacticPhase()
  2379. {
  2380. activeStack = NULL;
  2381. btactEnd->block(true);
  2382. tacticsMode = false;
  2383. }
  2384. static bool immobile(const CStack *s)
  2385. {
  2386. return !s->Speed(0, true); //should bound stacks be immobile?
  2387. }
  2388. void CBattleInterface::bTacticNextStack(const CStack *current /*= NULL*/)
  2389. {
  2390. if(!current)
  2391. current = activeStack;
  2392. //no switching stacks when the current one is moving
  2393. waitForAnims();
  2394. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  2395. stacksOfMine.erase(std::remove_if(stacksOfMine.begin(), stacksOfMine.end(), &immobile), stacksOfMine.end());
  2396. TStacks::iterator it = vstd::find(stacksOfMine, current);
  2397. if(it != stacksOfMine.end() && ++it != stacksOfMine.end())
  2398. stackActivated(*it);
  2399. else
  2400. stackActivated(stacksOfMine.front());
  2401. }
  2402. CBattleInterface::PossibleActions CBattleInterface::selectionTypeByPositiveness(const CSpell & spell)
  2403. {
  2404. switch(spell.positiveness)
  2405. {
  2406. case CSpell::NEGATIVE :
  2407. return HOSTILE_CREATURE_SPELL;
  2408. case CSpell::NEUTRAL:
  2409. return ANY_CREATURE;
  2410. case CSpell::POSITIVE:
  2411. return FRIENDLY_CREATURE_SPELL;
  2412. }
  2413. assert(0);
  2414. return NO_LOCATION; //should never happen
  2415. }
  2416. std::string formatDmgRange(std::pair<ui32, ui32> dmgRange)
  2417. {
  2418. if(dmgRange.first != dmgRange.second)
  2419. return (boost::format("%d - %d") % dmgRange.first % dmgRange.second).str();
  2420. else
  2421. return (boost::format("%d") % dmgRange.first).str();
  2422. }
  2423. bool CBattleInterface::canStackMoveHere (const CStack * activeStack, BattleHex myNumber)
  2424. {
  2425. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes (activeStack, false);
  2426. int shiftedDest = myNumber + (activeStack->attackerOwned ? 1 : -1);
  2427. if (vstd::contains(acc, myNumber))
  2428. return true;
  2429. else if (activeStack->doubleWide() && vstd::contains(acc, shiftedDest))
  2430. return true;
  2431. else
  2432. return false;
  2433. }
  2434. void CBattleInterface::handleHex(BattleHex myNumber, int eventType)
  2435. {
  2436. if(!myTurn) //we are not permit to do anything
  2437. return;
  2438. // This function handles mouse move over hexes and l-clicking on them.
  2439. // First we decide what happens if player clicks on this hex and set appropriately
  2440. // consoleMsg, cursorFrame/Type and prepare lambda realizeAction.
  2441. //
  2442. // Then, depending whether it was hover/click we either call the action or set tooltip/cursor.
  2443. //used when hovering -> tooltip message and cursor to be set
  2444. std::string consoleMsg;
  2445. bool setCursor = true; //if we want to suppress setting cursor
  2446. int cursorType = ECursor::COMBAT, cursorFrame = ECursor::COMBAT_POINTER; //TODO: is this line used?
  2447. //used when l-clicking -> action to be called upon the click
  2448. std::function<void()> realizeAction;
  2449. //helper lambda that appropriately realizes action / sets cursor and tooltip
  2450. auto realizeThingsToDo = [&]()
  2451. {
  2452. if(eventType == MOVE)
  2453. {
  2454. if(setCursor)
  2455. CCS->curh->changeGraphic(cursorType, cursorFrame);
  2456. this->console->alterText(consoleMsg);
  2457. this->console->whoSetAlter = 0;
  2458. }
  2459. if(eventType == LCLICK && realizeAction)
  2460. {
  2461. //opening creature window shouldn't affect myTurn...
  2462. if(currentAction != CREATURE_INFO)
  2463. {
  2464. myTurn = false; //tends to crash with empty calls
  2465. }
  2466. realizeAction();
  2467. CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER);
  2468. this->console->alterText("");
  2469. }
  2470. };
  2471. const CStack * const sactive = activeStack;
  2472. //Get stack on the hex - first try to grab the alive one, if not found -> allow dead stacks.
  2473. const CStack *shere = curInt->cb->battleGetStackByPos(myNumber, true);
  2474. if(!shere)
  2475. shere = curInt->cb->battleGetStackByPos(myNumber, false);
  2476. if (!sactive)
  2477. return;
  2478. bool ourStack = false;
  2479. if (shere)
  2480. ourStack = shere->owner == curInt->playerID;
  2481. //TODO: handle
  2482. bool noStackIsHovered = true; //will cause removing a blue glow
  2483. localActions.clear();
  2484. illegalActions.clear();
  2485. BOOST_FOREACH (PossibleActions action, possibleActions)
  2486. {
  2487. bool legalAction = false; //this action is legal and can't be performed
  2488. bool notLegal = false; //this action is not legal and should display message
  2489. switch (action)
  2490. {
  2491. case CHOOSE_TACTICS_STACK:
  2492. if (shere && ourStack)
  2493. legalAction = true;
  2494. break;
  2495. case MOVE_TACTICS:
  2496. case MOVE_STACK:
  2497. {
  2498. if (!(shere && shere->alive())) //we can walk on dead stacks
  2499. {
  2500. if (canStackMoveHere (sactive, myNumber))
  2501. legalAction = true;
  2502. }
  2503. break;
  2504. }
  2505. case ATTACK:
  2506. case WALK_AND_ATTACK:
  2507. case ATTACK_AND_RETURN:
  2508. {
  2509. if (shere && !ourStack && shere->alive())
  2510. {
  2511. if (isTileAttackable(myNumber))
  2512. {
  2513. setBattleCursor(myNumber); // temporary - needed for following function :(
  2514. BattleHex attackFromHex = fromWhichHexAttack(myNumber);
  2515. if (attackFromHex >= 0) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  2516. legalAction = true;
  2517. }
  2518. }
  2519. }
  2520. break;
  2521. case SHOOT:
  2522. if(curInt->cb->battleCanShoot (activeStack, myNumber))
  2523. legalAction = true;
  2524. break;
  2525. case ANY_LOCATION:
  2526. if (myNumber > -1) //TODO: this should be checked for all actions
  2527. {
  2528. creatureCasting = stackCanCastSpell && !spellDestSelectMode; //as isCastingPossibleHere is not called
  2529. legalAction = true;
  2530. }
  2531. break;
  2532. case HOSTILE_CREATURE_SPELL:
  2533. if (shere && shere->alive() && !ourStack && isCastingPossibleHere (sactive, shere, myNumber))
  2534. legalAction = true;
  2535. break;
  2536. case FRIENDLY_CREATURE_SPELL:
  2537. if (shere && shere->alive() && ourStack && isCastingPossibleHere (sactive, shere, myNumber))
  2538. legalAction = true;
  2539. break;
  2540. case RISING_SPELL:
  2541. if (shere && shere->canBeHealed() && ourStack && isCastingPossibleHere (sactive, shere, myNumber)) //TODO: at least one stack has to be raised by resurrection / animate dead
  2542. legalAction = true;
  2543. break;
  2544. case RANDOM_GENIE_SPELL:
  2545. {
  2546. if (shere && ourStack && shere != sactive) //only positive spells for other allied creatures
  2547. {
  2548. int spellID = curInt->cb->battleGetRandomStackSpell(shere, CBattleInfoCallback::RANDOM_GENIE);
  2549. if (spellID > -1)
  2550. {
  2551. legalAction = true;
  2552. }
  2553. }
  2554. }
  2555. break;
  2556. case OBSTACLE:
  2557. if (isCastingPossibleHere (sactive, shere, myNumber))
  2558. legalAction = true;
  2559. break;
  2560. case TELEPORT:
  2561. {
  2562. ui8 skill = 0;
  2563. if (creatureCasting)
  2564. skill = sactive->valOfBonuses(Selector::typeSubtype(Bonus::SPELLCASTER, Spells::TELEPORT));
  2565. else
  2566. skill = getActiveHero()->getSpellSchoolLevel (CGI->spellh->spells[spellToCast->additionalInfo]);
  2567. //TODO: explicitely save power, skill
  2568. if (curInt->cb->battleCanTeleportTo(selectedStack, myNumber, skill))
  2569. legalAction = true;
  2570. else
  2571. notLegal = true;
  2572. }
  2573. break;
  2574. case SACRIFICE: //choose our living stack to sacrifice
  2575. if (shere && shere != selectedStack && ourStack && shere->alive())
  2576. legalAction = true;
  2577. else
  2578. notLegal = true;
  2579. break;
  2580. case FREE_LOCATION:
  2581. {
  2582. ui8 side = curInt->cb->battleGetMySide();
  2583. auto hero = curInt->cb->battleGetFightingHero(side);
  2584. assert(!creatureCasting); //we assume hero casts this spell
  2585. assert(hero);
  2586. legalAction = true;
  2587. bool hexesOutsideBattlefield = false;
  2588. auto tilesThatMustBeClear = sp->rangeInHexes(myNumber, hero->getSpellSchoolLevel(sp), side, &hexesOutsideBattlefield);
  2589. BOOST_FOREACH(BattleHex hex, tilesThatMustBeClear)
  2590. {
  2591. if(curInt->cb->battleGetStackByPos(hex) || !!curInt->cb->battleGetObstacleOnPos(hex, false)
  2592. || !hex.isAvailable())
  2593. {
  2594. legalAction = false;
  2595. notLegal = true;
  2596. }
  2597. }
  2598. if(hexesOutsideBattlefield)
  2599. {
  2600. legalAction = false;
  2601. notLegal = true;
  2602. }
  2603. }
  2604. break;
  2605. case CATAPULT:
  2606. if (isCatapultAttackable(myNumber))
  2607. legalAction = true;
  2608. break;
  2609. case HEAL:
  2610. if (shere && ourStack && shere->canBeHealed())
  2611. legalAction = true;
  2612. break;
  2613. case RISE_DEMONS:
  2614. if (shere && ourStack && !shere->alive())
  2615. legalAction = true;
  2616. break;
  2617. }
  2618. if (legalAction)
  2619. localActions.push_back (action);
  2620. else if (notLegal)
  2621. illegalActions.push_back (action);
  2622. }
  2623. illegalAction = INVALID; //clear it in first place
  2624. if (vstd::contains(localActions, selectedAction)) //try to use last selected action by default
  2625. currentAction = selectedAction;
  2626. else if (localActions.size()) //if not possible, select first avaliable action 9they are sorted by suggested priority)
  2627. currentAction = localActions.front();
  2628. else //no legal action possible
  2629. {
  2630. currentAction = INVALID; //don't allow to do anything
  2631. if (vstd::contains(illegalActions, selectedAction))
  2632. illegalAction = selectedAction;
  2633. else if (illegalActions.size())
  2634. illegalAction = illegalActions.front();
  2635. else if (shere && ourStack && shere->alive()) //last possibility - display info about our creature
  2636. {
  2637. currentAction = CREATURE_INFO;
  2638. }
  2639. else
  2640. illegalAction = INVALID; //we should never be here
  2641. }
  2642. bool isCastingPossible = false;
  2643. bool secondaryTarget = false;
  2644. if (currentAction > INVALID)
  2645. {
  2646. switch (currentAction) //display console message, realize selected action
  2647. {
  2648. case CHOOSE_TACTICS_STACK:
  2649. consoleMsg = (boost::format(CGI->generaltexth->allTexts[481]) % shere->getName()).str(); //Select %s
  2650. realizeAction = [=]{ stackActivated(shere); };
  2651. break;
  2652. case MOVE_TACTICS:
  2653. case MOVE_STACK:
  2654. if (activeStack->hasBonusOfType(Bonus::FLYING))
  2655. {
  2656. cursorFrame = ECursor::COMBAT_FLY;
  2657. consoleMsg = (boost::format(CGI->generaltexth->allTexts[295]) % activeStack->getName()).str(); //Fly %s here
  2658. }
  2659. else
  2660. {
  2661. cursorFrame = ECursor::COMBAT_MOVE;
  2662. consoleMsg = (boost::format(CGI->generaltexth->allTexts[294]) % activeStack->getName()).str(); //Move %s here
  2663. }
  2664. realizeAction = [=]
  2665. {
  2666. if (activeStack->doubleWide())
  2667. {
  2668. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2669. int shiftedDest = myNumber + (activeStack->attackerOwned ? 1 : -1);
  2670. if(vstd::contains(acc, myNumber))
  2671. giveCommand (BattleAction::WALK ,myNumber, activeStack->ID);
  2672. else if(vstd::contains(acc, shiftedDest))
  2673. giveCommand (BattleAction::WALK, shiftedDest, activeStack->ID);
  2674. }
  2675. else
  2676. {
  2677. giveCommand (BattleAction::WALK, myNumber, activeStack->ID);
  2678. }
  2679. };
  2680. break;
  2681. case ATTACK:
  2682. case WALK_AND_ATTACK:
  2683. case ATTACK_AND_RETURN: //TODO: allow to disable return
  2684. {
  2685. setBattleCursor(myNumber); //handle direction of cursor and attackable tile
  2686. setCursor = false; //don't overwrite settings from the call above //TODO: what does it mean?
  2687. realizeAction = [=]
  2688. {
  2689. BattleHex attackFromHex = fromWhichHexAttack(myNumber);
  2690. if (attackFromHex >= 0) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  2691. {
  2692. giveCommand(BattleAction::WALK_AND_ATTACK, attackFromHex, activeStack->ID, myNumber);
  2693. }
  2694. };
  2695. std::string estDmgText = formatDmgRange(curInt->cb->battleEstimateDamage(sactive, shere)); //calculating estimated dmg
  2696. consoleMsg = (boost::format(CGI->generaltexth->allTexts[36]) % shere->getName() % estDmgText).str(); //Attack %s (%s damage)
  2697. }
  2698. break;
  2699. case SHOOT:
  2700. {
  2701. if(curInt->cb->battleHasShootingPenalty(activeStack, myNumber))
  2702. cursorFrame = ECursor::COMBAT_SHOOT_PENALTY;
  2703. else
  2704. cursorFrame = ECursor::COMBAT_SHOOT;
  2705. realizeAction = [=] {giveCommand(BattleAction::SHOOT, myNumber, activeStack->ID);};
  2706. std::string estDmgText = formatDmgRange(curInt->cb->battleEstimateDamage(sactive, shere)); //calculating estimated dmg
  2707. //printing - Shoot %s (%d shots left, %s damage)
  2708. consoleMsg = (boost::format(CGI->generaltexth->allTexts[296]) % shere->getName() % sactive->shots % estDmgText).str();
  2709. }
  2710. break;
  2711. case HOSTILE_CREATURE_SPELL:
  2712. case FRIENDLY_CREATURE_SPELL:
  2713. case RISING_SPELL:
  2714. sp = CGI->spellh->spells[creatureCasting ? creatureSpellToCast : spellToCast->additionalInfo]; //necessary if creature has random Genie spell at same time
  2715. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[27]) % sp->name % shere->getName()); //Cast %s on %s
  2716. switch (sp->id)
  2717. {
  2718. case Spells::SACRIFICE:
  2719. case Spells::TELEPORT:
  2720. selectedStack = shere; //remember firts target
  2721. secondaryTarget = true;
  2722. break;
  2723. }
  2724. isCastingPossible = true;
  2725. break;
  2726. case ANY_LOCATION:
  2727. sp = CGI->spellh->spells[creatureCasting ? creatureSpellToCast : spellToCast->additionalInfo]; //necessary if creature has random Genie spell at same time
  2728. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
  2729. isCastingPossible = true;
  2730. break;
  2731. case RANDOM_GENIE_SPELL: //we assume that teleport / sacrifice will never be avaliable as random spell
  2732. sp = NULL;
  2733. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[301]) % shere->getName()); //Cast a spell on %
  2734. creatureCasting = true;
  2735. isCastingPossible = true;
  2736. break;
  2737. case TELEPORT:
  2738. consoleMsg = CGI->generaltexth->allTexts[25]; //Teleport Here
  2739. isCastingPossible = true;
  2740. break;
  2741. case OBSTACLE:
  2742. consoleMsg = CGI->generaltexth->allTexts[550];
  2743. isCastingPossible = true;
  2744. break;
  2745. case SACRIFICE:
  2746. cursorFrame = ECursor::COMBAT_SACRIFICE;
  2747. consoleMsg = (boost::format(CGI->generaltexth->allTexts[549]) % shere->getName()).str(); //sacrifice the %s
  2748. spellToCast->selectedStack = shere->ID; //sacrificed creature is selected
  2749. isCastingPossible = true;
  2750. break;
  2751. case FREE_LOCATION:
  2752. //cursorFrame = ECursor::SPELLBOOK;
  2753. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
  2754. isCastingPossible = true;
  2755. break;
  2756. case HEAL:
  2757. cursorFrame = ECursor::COMBAT_HEAL;
  2758. consoleMsg = (boost::format(CGI->generaltexth->allTexts[419]) % shere->getName()).str(); //Apply first aid to the %s
  2759. realizeAction = [=]{ giveCommand(BattleAction::STACK_HEAL, myNumber, activeStack->ID); }; //command healing
  2760. break;
  2761. case RISE_DEMONS:
  2762. cursorType = ECursor::SPELLBOOK;
  2763. realizeAction = [=]{ giveCommand(BattleAction::DAEMON_SUMMONING, myNumber, activeStack->ID); };
  2764. break;
  2765. case CATAPULT:
  2766. cursorFrame = ECursor::COMBAT_SHOOT_CATAPULT;
  2767. realizeAction = [=]{ giveCommand(BattleAction::CATAPULT, myNumber, activeStack->ID); };
  2768. break;
  2769. case CREATURE_INFO:
  2770. {
  2771. cursorFrame = ECursor::COMBAT_QUERY;
  2772. consoleMsg = (boost::format(CGI->generaltexth->allTexts[297]) % shere->getName()).str();
  2773. realizeAction = [=]{ GH.pushInt(createCreWindow(shere, true)); };
  2774. //setting console text
  2775. const time_t curTime = time(NULL);
  2776. CCreatureAnimation *hoveredStackAnim = creAnims[shere->ID];
  2777. if (shere->ID != mouseHoveredStack
  2778. && curTime > lastMouseHoveredStackAnimationTime + HOVER_ANIM_DELTA
  2779. && hoveredStackAnim->getType() == CCreatureAnim::HOLDING
  2780. && hoveredStackAnim->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  2781. {
  2782. hoveredStackAnim->playOnce(CCreatureAnim::MOUSEON);
  2783. lastMouseHoveredStackAnimationTime = curTime;
  2784. }
  2785. noStackIsHovered = false;
  2786. mouseHoveredStack = shere->ID;
  2787. }
  2788. break;
  2789. }
  2790. }
  2791. else //no possible valid action, display message
  2792. {
  2793. switch (illegalAction)
  2794. {
  2795. case HOSTILE_CREATURE_SPELL:
  2796. case FRIENDLY_CREATURE_SPELL:
  2797. case RISING_SPELL:
  2798. case RANDOM_GENIE_SPELL:
  2799. cursorFrame = ECursor::COMBAT_BLOCKED;
  2800. consoleMsg = CGI->generaltexth->allTexts[23];
  2801. break;
  2802. case TELEPORT:
  2803. consoleMsg = CGI->generaltexth->allTexts[24]; //Invalid Teleport Destination
  2804. break;
  2805. case SACRIFICE:
  2806. consoleMsg = CGI->generaltexth->allTexts[543]; //choose army to sacrifice
  2807. break;
  2808. case FREE_LOCATION:
  2809. cursorFrame = ECursor::COMBAT_BLOCKED;
  2810. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[181]) % sp->name); //No room to place %s here
  2811. break;
  2812. default:
  2813. if (myNumber == -1)
  2814. CCS->curh->changeGraphic(ECursor::COMBAT, ECursor::COMBAT_POINTER); //set neutral cursor over menu etc.
  2815. else
  2816. cursorFrame = ECursor::COMBAT_BLOCKED;
  2817. break;
  2818. }
  2819. }
  2820. if (isCastingPossible) //common part
  2821. {
  2822. cursorType = ECursor::SPELLBOOK;
  2823. cursorFrame = 0;
  2824. if(consoleMsg.empty() && sp)
  2825. consoleMsg = boost::str(boost::format(CGI->generaltexth->allTexts[26]) % sp->name); //Cast %s
  2826. realizeAction = [=]
  2827. {
  2828. if (secondaryTarget) //select that target now
  2829. {
  2830. possibleActions.clear();
  2831. switch (sp->id)
  2832. {
  2833. case Spells::TELEPORT: //don't cast spell yet, only select target
  2834. possibleActions.push_back (TELEPORT);
  2835. spellToCast->selectedStack = selectedStack->ID;
  2836. break;
  2837. case Spells::SACRIFICE:
  2838. possibleActions.push_back (SACRIFICE);
  2839. break;
  2840. }
  2841. }
  2842. else
  2843. {
  2844. if(creatureCasting)
  2845. {
  2846. if (sp)
  2847. {
  2848. giveCommand(BattleAction::MONSTER_SPELL, myNumber, sactive->ID, creatureSpellToCast);
  2849. }
  2850. else //unknown random spell
  2851. {
  2852. giveCommand(BattleAction::MONSTER_SPELL, myNumber, sactive->ID, curInt->cb->battleGetRandomStackSpell(shere, CBattleInfoCallback::RANDOM_GENIE));
  2853. }
  2854. }
  2855. else
  2856. {
  2857. assert (sp);
  2858. switch (sp->id)
  2859. {
  2860. case Spells::SACRIFICE:
  2861. spellToCast->destinationTile = selectedStack->position; //cast on first creature that will be resurrected
  2862. break;
  2863. default:
  2864. spellToCast->destinationTile = myNumber;
  2865. break;
  2866. }
  2867. curInt->cb->battleMakeAction(spellToCast);
  2868. endCastingSpell();
  2869. }
  2870. selectedStack = NULL;
  2871. }
  2872. };
  2873. }
  2874. realizeThingsToDo();
  2875. if(noStackIsHovered)
  2876. mouseHoveredStack = -1;
  2877. }
  2878. bool CBattleInterface::isCastingPossibleHere (const CStack * sactive, const CStack * shere, BattleHex myNumber)
  2879. {
  2880. creatureCasting = stackCanCastSpell && !spellDestSelectMode; //TODO: allow creatures to cast aimed spells
  2881. bool isCastingPossible = true;
  2882. int spellID = -1;
  2883. if (creatureCasting)
  2884. {
  2885. if (creatureSpellToCast > -1 && (shere != sactive)) //can't cast on itself
  2886. spellID = creatureSpellToCast; //TODO: merge with SpellTocast?
  2887. }
  2888. else //hero casting
  2889. spellID = spellToCast->additionalInfo;
  2890. sp = NULL;
  2891. if (spellID >= 0)
  2892. sp = CGI->spellh->spells[spellID];
  2893. if (sp)
  2894. {
  2895. if (creatureCasting)
  2896. isCastingPossible = (curInt->cb->battleCanCreatureCastThisSpell (sp, myNumber) == ESpellCastProblem::OK);
  2897. else
  2898. isCastingPossible = (curInt->cb->battleCanCastThisSpell (sp, myNumber) == ESpellCastProblem::OK);
  2899. }
  2900. if(!myNumber.isAvailable() && !shere) //empty tile outside battlefield (or in the unavailable border column)
  2901. isCastingPossible = false;
  2902. return isCastingPossible;
  2903. }
  2904. BattleHex CBattleInterface::fromWhichHexAttack(BattleHex myNumber)
  2905. {
  2906. //TODO far too much repeating code
  2907. BattleHex destHex = -1;
  2908. switch(CCS->curh->number)
  2909. {
  2910. case 12: //from bottom right
  2911. {
  2912. bool doubleWide = activeStack->doubleWide();
  2913. destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 ) +
  2914. (activeStack->attackerOwned && doubleWide ? 1 : 0);
  2915. if(vstd::contains(occupyableHexes, destHex))
  2916. return destHex;
  2917. else if(activeStack->attackerOwned) //if we are attacker
  2918. {
  2919. if(vstd::contains(occupyableHexes, destHex+1))
  2920. return destHex+1;
  2921. }
  2922. else //if we are defender
  2923. {
  2924. if(vstd::contains(occupyableHexes, destHex-1))
  2925. return destHex-1;
  2926. }
  2927. break;
  2928. }
  2929. case 7: //from bottom left
  2930. {
  2931. destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH-1 : GameConstants::BFIELD_WIDTH );
  2932. if(vstd::contains(occupyableHexes, destHex))
  2933. return destHex;
  2934. else if(activeStack->attackerOwned) //if we are attacker
  2935. {
  2936. if(vstd::contains(occupyableHexes, destHex+1))
  2937. return destHex+1;
  2938. }
  2939. else //if we are defender
  2940. {
  2941. if(vstd::contains(occupyableHexes, destHex-1))
  2942. return destHex-1;
  2943. }
  2944. break;
  2945. }
  2946. case 8: //from left
  2947. {
  2948. if(activeStack->doubleWide() && !activeStack->attackerOwned)
  2949. {
  2950. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2951. if(vstd::contains(acc, myNumber))
  2952. return myNumber - 1;
  2953. else
  2954. return myNumber - 2;
  2955. }
  2956. else
  2957. {
  2958. return myNumber - 1;
  2959. }
  2960. break;
  2961. }
  2962. case 9: //from top left
  2963. {
  2964. destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH+1 : GameConstants::BFIELD_WIDTH );
  2965. if(vstd::contains(occupyableHexes, destHex))
  2966. return destHex;
  2967. else if(activeStack->attackerOwned) //if we are attacker
  2968. {
  2969. if(vstd::contains(occupyableHexes, destHex+1))
  2970. return destHex+1;
  2971. }
  2972. else //if we are defender
  2973. {
  2974. if(vstd::contains(occupyableHexes, destHex-1))
  2975. return destHex-1;
  2976. }
  2977. break;
  2978. }
  2979. case 10: //from top right
  2980. {
  2981. bool doubleWide = activeStack->doubleWide();
  2982. destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 ) +
  2983. (activeStack->attackerOwned && doubleWide ? 1 : 0);
  2984. if(vstd::contains(occupyableHexes, destHex))
  2985. return destHex;
  2986. else if(activeStack->attackerOwned) //if we are attacker
  2987. {
  2988. if(vstd::contains(occupyableHexes, destHex+1))
  2989. return destHex+1;
  2990. }
  2991. else //if we are defender
  2992. {
  2993. if(vstd::contains(occupyableHexes, destHex-1))
  2994. return destHex-1;
  2995. }
  2996. break;
  2997. }
  2998. case 11: //from right
  2999. {
  3000. if(activeStack->doubleWide() && activeStack->attackerOwned)
  3001. {
  3002. std::vector<BattleHex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  3003. if(vstd::contains(acc, myNumber))
  3004. return myNumber + 1;
  3005. else
  3006. return myNumber + 2;
  3007. }
  3008. else
  3009. {
  3010. return myNumber + 1;
  3011. }
  3012. break;
  3013. }
  3014. case 13: //from bottom
  3015. {
  3016. destHex = myNumber + ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH+1 );
  3017. if(vstd::contains(occupyableHexes, destHex))
  3018. return destHex;
  3019. else if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor()) //if we are attacker
  3020. {
  3021. if(vstd::contains(occupyableHexes, destHex+1))
  3022. return destHex+1;
  3023. }
  3024. else //if we are defender
  3025. {
  3026. if(vstd::contains(occupyableHexes, destHex-1))
  3027. return destHex-1;
  3028. }
  3029. break;
  3030. }
  3031. case 14: //from top
  3032. {
  3033. destHex = myNumber - ( (myNumber/GameConstants::BFIELD_WIDTH)%2 ? GameConstants::BFIELD_WIDTH : GameConstants::BFIELD_WIDTH-1 );
  3034. if(vstd::contains(occupyableHexes, destHex))
  3035. return destHex;
  3036. else if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor()) //if we are attacker
  3037. {
  3038. if(vstd::contains(occupyableHexes, destHex+1))
  3039. return destHex+1;
  3040. }
  3041. else //if we are defender
  3042. {
  3043. if(vstd::contains(occupyableHexes, destHex-1))
  3044. return destHex-1;
  3045. }
  3046. break;
  3047. }
  3048. }
  3049. return -1;
  3050. }
  3051. Rect CBattleInterface::hexPosition(BattleHex hex) const
  3052. {
  3053. int x = 14 + ((hex.getY())%2==0 ? 22 : 0) + 44*hex.getX() + pos.x;
  3054. int y = 86 + 42 * hex.getY() + pos.y;
  3055. int w = cellShade->w;
  3056. int h = cellShade->h;
  3057. return Rect(x, y, w, h);
  3058. }
  3059. SDL_Surface * CBattleInterface::imageOfObstacle(const CObstacleInstance &oi) const
  3060. {
  3061. int frameIndex = (animCount+1) / (40/getAnimSpeed());
  3062. switch(oi.obstacleType)
  3063. {
  3064. case CObstacleInstance::USUAL:
  3065. return vstd::circularAt(idToObstacle.find(oi.ID)->second->ourImages, frameIndex).bitmap;
  3066. case CObstacleInstance::ABSOLUTE_OBSTACLE:
  3067. return idToAbsoluteObstacle.find(oi.ID)->second;
  3068. case CObstacleInstance::QUICKSAND:
  3069. return vstd::circularAt(quicksand->ourImages, frameIndex).bitmap;
  3070. case CObstacleInstance::LAND_MINE:
  3071. return vstd::circularAt(landMine->ourImages, frameIndex).bitmap;
  3072. case CObstacleInstance::FIRE_WALL:
  3073. return vstd::circularAt(fireWall->ourImages, frameIndex).bitmap;
  3074. case CObstacleInstance::FORCE_FIELD:
  3075. {
  3076. auto &forceField = dynamic_cast<const SpellCreatedObstacle &>(oi);
  3077. if(forceField.getAffectedTiles().size() > 2)
  3078. return vstd::circularAt(bigForceField[forceField.casterSide]->ourImages, frameIndex).bitmap;
  3079. else
  3080. return vstd::circularAt(smallForceField[forceField.casterSide]->ourImages, frameIndex).bitmap;
  3081. }
  3082. case CObstacleInstance::MOAT://moat is blitted by SiegeHelper, this shouldn't be called
  3083. default:
  3084. assert(0);
  3085. return nullptr;
  3086. }
  3087. }
  3088. void CBattleInterface::obstaclePlaced(const CObstacleInstance & oi)
  3089. {
  3090. //so when multiple obstacles are added, they show up one after another
  3091. waitForAnims();
  3092. int effectID = -1;
  3093. soundBase::soundID sound = soundBase::invalid;//FIXME: variable set but unused. Missing soundh->playSound()?
  3094. std::string defname;
  3095. switch(oi.obstacleType)
  3096. {
  3097. case CObstacleInstance::QUICKSAND:
  3098. effectID = 55;
  3099. sound = soundBase::QUIKSAND;
  3100. break;
  3101. case CObstacleInstance::LAND_MINE:
  3102. effectID = 47;
  3103. sound = soundBase::LANDMINE;
  3104. break;
  3105. case CObstacleInstance::FORCE_FIELD:
  3106. {
  3107. auto &spellObstacle = dynamic_cast<const SpellCreatedObstacle&>(oi);
  3108. if(spellObstacle.casterSide)
  3109. {
  3110. if(oi.getAffectedTiles().size() < 3)
  3111. defname = "C15SPE0.DEF"; //TODO cannot find def for 2-hex force field \ appearing
  3112. else
  3113. defname = "C15SPE6.DEF";
  3114. }
  3115. else
  3116. {
  3117. if(oi.getAffectedTiles().size() < 3)
  3118. defname = "C15SPE0.DEF";
  3119. else
  3120. defname = "C15SPE9.DEF";
  3121. }
  3122. }
  3123. sound = soundBase::FORCEFLD;
  3124. break;
  3125. case CObstacleInstance::FIRE_WALL:
  3126. if(oi.getAffectedTiles().size() < 3)
  3127. effectID = 43; //small fire wall appearing
  3128. else
  3129. effectID = 44; //and the big one
  3130. sound = soundBase::fireWall;
  3131. break;
  3132. default:
  3133. tlog1 << "I don't know how to animate appearing obstacle of type " << (int)oi.obstacleType << std::endl;
  3134. return;
  3135. }
  3136. if(graphics->battleACToDef[effectID].empty())
  3137. {
  3138. tlog1 << "Cannot find def for effect type " << effectID << std::endl;
  3139. return;
  3140. }
  3141. if(defname.empty() && effectID >= 0)
  3142. defname = graphics->battleACToDef[effectID].front();
  3143. assert(!defname.empty());
  3144. //we assume here that effect graphics have the same size as the usual obstacle image
  3145. // -> if we know how to blit obstacle, let's blit the effect in the same place
  3146. Point whereTo = whereToBlitObstacleImage(imageOfObstacle(oi), oi);
  3147. addNewAnim(new CSpellEffectAnimation(this, defname, whereTo.x, whereTo.y));
  3148. //TODO we need to wait after playing sound till it's finished, otherwise it overlaps and sounds really bad
  3149. //CCS->soundh->playSound(sound);
  3150. }
  3151. Point CBattleInterface::whereToBlitObstacleImage(SDL_Surface *image, const CObstacleInstance &obstacle) const
  3152. {
  3153. int offset = image->h % 42;
  3154. if(obstacle.obstacleType == CObstacleInstance::USUAL)
  3155. {
  3156. if(obstacle.getInfo().blockedTiles.front() < 0 || offset > 37) //second or part is for holy ground ID=62,65,63
  3157. offset -= 42;
  3158. }
  3159. else if(obstacle.obstacleType == CObstacleInstance::QUICKSAND)
  3160. {
  3161. offset -= 42;
  3162. }
  3163. Rect r = hexPosition(obstacle.pos);
  3164. r.y += 42 - image->h + offset;
  3165. return r.topLeft();
  3166. }
  3167. const CGHeroInstance * CBattleInterface::currentHero() const
  3168. {
  3169. if(attackingHeroInstance->tempOwner == curInt->playerID)
  3170. return attackingHeroInstance;
  3171. else
  3172. return defendingHeroInstance;
  3173. }
  3174. InfoAboutHero CBattleInterface::enemyHero() const
  3175. {
  3176. InfoAboutHero ret;
  3177. if(attackingHeroInstance->tempOwner == curInt->playerID)
  3178. curInt->cb->getHeroInfo(defendingHeroInstance, ret);
  3179. else
  3180. curInt->cb->getHeroInfo(attackingHeroInstance, ret);
  3181. return ret;
  3182. }
  3183. CBattleInterface::SiegeHelper::SiegeHelper(const CGTownInstance *siegeTown, const CBattleInterface * _owner)
  3184. : owner(_owner), town(siegeTown)
  3185. {
  3186. for(int g = 0; g < ARRAY_COUNT(walls); ++g)
  3187. {
  3188. walls[g] = BitmapHandler::loadBitmap( getSiegeName(g) );
  3189. }
  3190. }
  3191. CBattleInterface::SiegeHelper::~SiegeHelper()
  3192. {
  3193. for(int g = 0; g < ARRAY_COUNT(walls); ++g)
  3194. {
  3195. SDL_FreeSurface(walls[g]);
  3196. }
  3197. }
  3198. std::string CBattleInterface::SiegeHelper::getSiegeName(ui16 what, ui16 additInfo) const
  3199. {
  3200. if(what == 2 || what == 3 || what == 8)
  3201. vstd::amin(additInfo, 2);
  3202. else
  3203. vstd::amin(additInfo, 3);
  3204. std::string & prefix = town->town->clientInfo.siegePrefix;
  3205. std::string addit = boost::lexical_cast<std::string>(additInfo);
  3206. switch(what)
  3207. {
  3208. case 0: //background
  3209. return prefix + "BACK.BMP";
  3210. case 1: //background wall
  3211. {
  3212. switch(town->town->typeID)
  3213. {
  3214. case 5: case 4: case 1: case 6:
  3215. return prefix + "TPW1.BMP";
  3216. default:
  3217. return prefix + "TPWL.BMP";
  3218. }
  3219. }
  3220. case 2: //keep
  3221. return prefix + "MAN" + addit + ".BMP";
  3222. case 3: //bottom tower
  3223. return prefix + "TW1" + addit + ".BMP";
  3224. case 4: //bottom wall
  3225. return prefix + "WA1" + addit + ".BMP";
  3226. case 5: //below gate
  3227. return prefix + "WA3" + addit + ".BMP";
  3228. case 6: //over gate
  3229. return prefix + "WA4" + addit + ".BMP";
  3230. case 7: //upper wall
  3231. return prefix + "WA6" + addit + ".BMP";
  3232. case 8: //upper tower
  3233. return prefix + "TW2" + addit + ".BMP";
  3234. case 9: //gate
  3235. return prefix + "DRW" + addit + ".BMP";
  3236. case 10: //gate arch
  3237. return prefix + "ARCH.BMP";
  3238. case 11: //bottom static wall
  3239. return prefix + "WA2.BMP";
  3240. case 12: //upper static wall
  3241. return prefix + "WA5.BMP";
  3242. case 13: //moat
  3243. return prefix + "MOAT.BMP";
  3244. case 14: //mlip
  3245. return prefix + "MLIP.BMP";
  3246. case 15: //keep creature cover
  3247. return prefix + "MANC.BMP";
  3248. case 16: //bottom turret creature cover
  3249. return prefix + "TW1C.BMP";
  3250. case 17: //upper turret creature cover
  3251. return prefix + "TW2C.BMP";
  3252. default:
  3253. return "";
  3254. }
  3255. }
  3256. /// What: 1. background wall, 2. keep, 3. bottom tower, 4. bottom wall, 5. wall below gate,
  3257. /// 6. wall over gate, 7. upper wall, 8. upper tower, 9. gate, 10. gate arch, 11. bottom static wall, 12. upper static wall, 13. moat, 14. mlip,
  3258. /// 15. keep turret cover, 16. lower turret cover, 17. upper turret cover
  3259. void CBattleInterface::SiegeHelper::printPartOfWall(SDL_Surface * to, int what)
  3260. {
  3261. Point pos = Point(-1, -1);
  3262. if (what >= 1 && what <= 17)
  3263. {
  3264. pos.x = owner->siegeH->town->town->clientInfo.siegePositions[what].x + owner->pos.x;
  3265. pos.y = owner->siegeH->town->town->clientInfo.siegePositions[what].y + owner->pos.y;
  3266. }
  3267. if(pos.x != -1)
  3268. {
  3269. blitAt(walls[what], pos.x, pos.y, to);
  3270. }
  3271. }
  3272. double CatapultProjectileInfo::calculateY(double x)
  3273. {
  3274. return (facA * pow(10., -3.)) * pow(x, 2.0) + facB * x + facC;
  3275. }