CBattleInterface.cpp 110 KB

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