CBattleInterface.cpp 112 KB

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