CBattleInterface.cpp 105 KB

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