CBattleInterface.cpp 109 KB

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