2
0

CBattleInterface.cpp 102 KB

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