CBattleInterface.cpp 116 KB

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