CBattleInterface.cpp 107 KB

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