CBattleInterface.cpp 116 KB

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