CBattleInterface.cpp 109 KB

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