CBattleInterface.cpp 114 KB

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