2
0

CBattleInterface.cpp 113 KB

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