CBattleInterface.cpp 115 KB

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