CBattleInterface.cpp 113 KB

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