CBattleInterface.cpp 114 KB

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