CBattleInterface.cpp 116 KB

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