CBattleInterface.cpp 112 KB

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