CBattleInterface.cpp 103 KB

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