CBattleInterface.cpp 104 KB

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