CBattleInterface.cpp 109 KB

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