CBattleInterface.cpp 114 KB

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