CBattleInterface.cpp 115 KB

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