CBattleInterface.cpp 118 KB

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