CBattleInterface.cpp 102 KB

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