CBattleInterface.cpp 118 KB

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