CBattleInterface.cpp 118 KB

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