CBattleInterface.cpp 114 KB

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