CBattleInterface.cpp 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830
  1. #include "CBattleInterface.h"
  2. #include "CGameInfo.h"
  3. #include "../lib/CLodHandler.h"
  4. #include "SDL_Extensions.h"
  5. #include "CAdvmapInterface.h"
  6. #include "AdventureMapButton.h"
  7. #include "CAnimation.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 "CCursorHandler.h"
  15. #include "../CCallback.h"
  16. #include "../lib/BattleState.h"
  17. #include "../lib/CGeneralTextHandler.h"
  18. #include "CCreatureAnimation.h"
  19. #include "Graphics.h"
  20. #include "CSpellWindow.h"
  21. #include "CConfigHandler.h"
  22. #include <queue>
  23. #include <sstream>
  24. #include "../lib/CondSh.h"
  25. #include "../lib/NetPacks.h"
  26. #include "CPlayerInterface.h"
  27. #include "CCreatureWindow.h"
  28. #include "CVideoHandler.h"
  29. #include "../lib/CTownHandler.h"
  30. #include <boost/assign/list_of.hpp>
  31. #include <boost/foreach.hpp>
  32. #include <boost/lexical_cast.hpp>
  33. #include <boost/algorithm/string/replace.hpp>
  34. #ifndef __GNUC__
  35. const double M_PI = 3.14159265358979323846;
  36. #else
  37. #define _USE_MATH_DEFINES
  38. #include <cmath>
  39. #endif
  40. #include <boost/format.hpp>
  41. /*
  42. * CBattleInterface.cpp, part of VCMI engine
  43. *
  44. * Authors: listed in file AUTHORS in main folder
  45. *
  46. * License: GNU General Public License v2.0 or later
  47. * Full text of license available in license.txt file, in main folder
  48. *
  49. */
  50. extern SDL_Surface * screen;
  51. extern SDL_Color zwykly;
  52. CondSh<bool> CBattleInterface::animsAreDisplayed;
  53. struct CMP_stack2
  54. {
  55. inline bool operator ()(const CStack& a, const CStack& b)
  56. {
  57. return (a.Speed())>(b.Speed());
  58. }
  59. } cmpst2 ;
  60. static void transformPalette(SDL_Surface * surf, float rCor, float gCor, float bCor)
  61. {
  62. SDL_Color * colorsToChange = surf->format->palette->colors;
  63. for(int g=0; g<surf->format->palette->ncolors; ++g)
  64. {
  65. if((colorsToChange+g)->b != 132 &&
  66. (colorsToChange+g)->g != 231 &&
  67. (colorsToChange+g)->r != 255) //it's not yellow border
  68. {
  69. (colorsToChange+g)->r = (float)((colorsToChange+g)->r) * rCor;
  70. (colorsToChange+g)->g = (float)((colorsToChange+g)->g) * gCor;
  71. (colorsToChange+g)->b = (float)((colorsToChange+g)->b) * bCor;
  72. }
  73. }
  74. }
  75. ////////////////////////Battle helpers
  76. //general anim
  77. void CBattleAnimation::endAnim()
  78. {
  79. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  80. {
  81. if(it->first == this)
  82. {
  83. it->first = NULL;
  84. }
  85. }
  86. }
  87. bool CBattleAnimation::isEarliest(bool perStackConcurrency)
  88. {
  89. int lowestMoveID = owner->animIDhelper + 5;
  90. CBattleStackAnimation * thAnim = dynamic_cast<CBattleStackAnimation *>(this);
  91. CSpellEffectAnim * thSen = dynamic_cast<CSpellEffectAnim *>(this);
  92. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  93. {
  94. CBattleStackAnimation * stAnim = dynamic_cast<CBattleStackAnimation *>(it->first);
  95. CSpellEffectAnim * sen = dynamic_cast<CSpellEffectAnim *>(it->first);
  96. if(perStackConcurrency && stAnim && thAnim && stAnim->stack->ID != thAnim->stack->ID)
  97. continue;
  98. if(sen && thSen && sen != thSen && perStackConcurrency)
  99. continue;
  100. CReverseAnim * revAnim = dynamic_cast<CReverseAnim *>(stAnim);
  101. if(revAnim && thAnim && stAnim && stAnim->stack->ID == thAnim->stack->ID && revAnim->priority)
  102. return false;
  103. if(it->first)
  104. amin(lowestMoveID, it->first->ID);
  105. }
  106. return ID == lowestMoveID || lowestMoveID == (owner->animIDhelper + 5);
  107. }
  108. CBattleAnimation::CBattleAnimation(CBattleInterface * _owner)
  109. : owner(_owner), ID(_owner->animIDhelper++)
  110. {}
  111. //Dummy animation
  112. bool CDummyAnim::init()
  113. {
  114. return true;
  115. }
  116. void CDummyAnim::nextFrame()
  117. {
  118. counter++;
  119. if(counter > howMany)
  120. endAnim();
  121. }
  122. void CDummyAnim::endAnim()
  123. {
  124. CBattleAnimation::endAnim();
  125. delete this;
  126. }
  127. CDummyAnim::CDummyAnim(CBattleInterface * _owner, int howManyFrames) : CBattleAnimation(_owner), counter(0), howMany(howManyFrames)
  128. {
  129. }
  130. //effect animation
  131. bool CSpellEffectAnim::init()
  132. {
  133. if(!isEarliest(true))
  134. return false;
  135. if(effect == 12) //armageddon
  136. {
  137. if(effect == -1 || graphics->battleACToDef[effect].size() != 0)
  138. {
  139. CDefHandler * anim;
  140. if(customAnim.size())
  141. anim = CDefHandler::giveDef(customAnim);
  142. else
  143. anim = CDefHandler::giveDef(graphics->battleACToDef[effect][0]);
  144. if (Vflip)
  145. {
  146. for (int v=0; v<anim->ourImages.size(); ++v)
  147. {
  148. CSDL_Ext::VflipSurf(anim->ourImages[v].bitmap);
  149. }
  150. }
  151. for(int i=0; i * anim->width < owner->pos.w ; ++i)
  152. {
  153. for(int j=0; j * anim->height < owner->pos.h ; ++j)
  154. {
  155. SBattleEffect be;
  156. be.effectID = ID;
  157. be.anim = CDefHandler::giveDef(graphics->battleACToDef[effect][0]);
  158. if (Vflip)
  159. {
  160. for (int v=0; v<be.anim->ourImages.size(); ++v)
  161. {
  162. CSDL_Ext::VflipSurf(be.anim->ourImages[v].bitmap);
  163. }
  164. }
  165. be.frame = 0;
  166. be.maxFrame = be.anim->ourImages.size();
  167. be.x = i * anim->width + owner->pos.x;
  168. be.y = j * anim->height + owner->pos.y;
  169. owner->battleEffects.push_back(be);
  170. }
  171. }
  172. }
  173. else //there is nothing to play
  174. {
  175. endAnim();
  176. return false;
  177. }
  178. }
  179. else // Effects targeted at a specific creature/hex.
  180. {
  181. if(effect == -1 || graphics->battleACToDef[effect].size() != 0)
  182. {
  183. const CStack* destStack = owner->curInt->cb->battleGetStackByPos(destTile, false);
  184. Rect &tilePos = owner->bfield[destTile].pos;
  185. SBattleEffect be;
  186. be.effectID = ID;
  187. if(customAnim.size())
  188. be.anim = CDefHandler::giveDef(customAnim);
  189. else
  190. be.anim = CDefHandler::giveDef(graphics->battleACToDef[effect][0]);
  191. if (Vflip)
  192. {
  193. for (int v=0; v<be.anim->ourImages.size(); ++v)
  194. {
  195. CSDL_Ext::VflipSurf(be.anim->ourImages[v].bitmap);
  196. }
  197. }
  198. be.frame = 0;
  199. be.maxFrame = be.anim->ourImages.size();
  200. if(effect == 1)
  201. be.maxFrame = 3;
  202. switch (effect)
  203. {
  204. case -1:
  205. be.x = x;
  206. be.y = y;
  207. break;
  208. case 0: // Prayer and Lightning Bolt.
  209. case 1:
  210. // Position effect with it's bottom center touching the bottom center of affected tile(s).
  211. be.x = tilePos.x + tilePos.w/2 - be.anim->width/2;
  212. be.y = tilePos.y + tilePos.h - be.anim->height;
  213. break;
  214. default:
  215. // Position effect with it's center touching the top center of affected tile(s).
  216. be.x = tilePos.x + tilePos.w/2 - be.anim->width/2;
  217. be.y = tilePos.y - be.anim->height/2;
  218. break;
  219. }
  220. // Correction for 2-hex creatures.
  221. if (destStack != NULL && destStack->doubleWide())
  222. be.x += (destStack->attackerOwned ? -1 : 1)*tilePos.w/2;
  223. owner->battleEffects.push_back(be);
  224. }
  225. else //there is nothing to play
  226. {
  227. endAnim();
  228. return false;
  229. }
  230. }
  231. //battleEffects
  232. return true;
  233. }
  234. void CSpellEffectAnim::nextFrame()
  235. {
  236. //notice: there may be more than one effect in owner->battleEffects correcponding to this animation (ie. armageddon)
  237. for(std::list<SBattleEffect>::iterator it = owner->battleEffects.begin(); it != owner->battleEffects.end(); ++it)
  238. {
  239. if(it->effectID == ID)
  240. {
  241. ++(it->frame);
  242. if(it->frame == it->maxFrame)
  243. {
  244. endAnim();
  245. break;
  246. }
  247. else
  248. {
  249. it->x += dx;
  250. it->y += dy;
  251. }
  252. }
  253. }
  254. }
  255. void CSpellEffectAnim::endAnim()
  256. {
  257. CBattleAnimation::endAnim();
  258. std::vector<std::list<SBattleEffect>::iterator> toDel;
  259. for(std::list<SBattleEffect>::iterator it = owner->battleEffects.begin(); it != owner->battleEffects.end(); ++it)
  260. {
  261. if(it->effectID == ID)
  262. {
  263. toDel.push_back(it);
  264. }
  265. }
  266. for(int b=0; b<toDel.size(); ++b)
  267. {
  268. delete toDel[b]->anim;
  269. owner->battleEffects.erase(toDel[b]);
  270. }
  271. delete this;
  272. }
  273. CSpellEffectAnim::CSpellEffectAnim(CBattleInterface * _owner, ui32 _effect, THex _destTile, int _dx, int _dy, bool _Vflip)
  274. :CBattleAnimation(_owner), effect(_effect), destTile(_destTile), customAnim(""), dx(_dx), dy(_dy), Vflip(_Vflip)
  275. {
  276. }
  277. CSpellEffectAnim::CSpellEffectAnim(CBattleInterface * _owner, std::string _customAnim, int _x, int _y, int _dx, int _dy, bool _Vflip)
  278. :CBattleAnimation(_owner), effect(-1), destTile(0), customAnim(_customAnim), x(_x), y(_y), dx(_dx), dy(_dy), Vflip(_Vflip)
  279. {
  280. }
  281. //stack's aniamtion
  282. CBattleStackAnimation::CBattleStackAnimation(CBattleInterface * _owner, const CStack * _stack)
  283. : CBattleAnimation(_owner), stack(_stack)
  284. {
  285. }
  286. bool CBattleStackAnimation::isToReverseHlp(THex hexFrom, THex hexTo, bool curDir)
  287. {
  288. int fromMod = hexFrom % BFIELD_WIDTH;
  289. int fromDiv = hexFrom / BFIELD_WIDTH;
  290. int toMod = hexTo % BFIELD_WIDTH;
  291. if(curDir && fromMod < toMod)
  292. return false;
  293. else if(curDir && fromMod > toMod)
  294. return true;
  295. else if(curDir && fromMod == toMod)
  296. {
  297. return fromDiv % 2 == 0;
  298. }
  299. else if(!curDir && fromMod < toMod)
  300. return true;
  301. else if(!curDir && fromMod > toMod)
  302. return false;
  303. else if(!curDir && fromMod == toMod)
  304. {
  305. return fromDiv % 2 == 1;
  306. }
  307. tlog1 << "Catastrope in CBattleStackAnimation::isToReverse!" << std::endl;
  308. return false; //should never happen
  309. }
  310. bool CBattleStackAnimation::isToReverse(THex hexFrom, THex hexTo, bool curDir, bool toDoubleWide, bool toDir)
  311. {
  312. if(hexTo < 0) //turret
  313. return false;
  314. if(toDoubleWide)
  315. {
  316. return isToReverseHlp(hexFrom, hexTo, curDir) &&
  317. (toDir ? isToReverseHlp(hexFrom, hexTo-1, curDir) : isToReverseHlp(hexFrom, hexTo+1, curDir) );
  318. }
  319. else
  320. {
  321. return isToReverseHlp(hexFrom, hexTo, curDir);
  322. }
  323. }
  324. //revering animation
  325. bool CReverseAnim::init()
  326. {
  327. if(owner->creAnims[stack->ID] == NULL || owner->creAnims[stack->ID]->getType() == 5)
  328. {
  329. endAnim();
  330. return false; //there is no such creature
  331. }
  332. if(!priority && !isEarliest(false))
  333. return false;
  334. owner->creAnims[stack->ID]->setType(CCreatureAnim::TURN_R);
  335. return true;
  336. }
  337. void CReverseAnim::nextFrame()
  338. {
  339. if(partOfAnim == 1) //first part of animation
  340. {
  341. if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  342. {
  343. partOfAnim = 2;
  344. }
  345. }
  346. else if(partOfAnim == 2)
  347. {
  348. if(!secondPartSetup)
  349. {
  350. owner->creDir[stack->ID] = !owner->creDir[stack->ID];
  351. if(!stack)
  352. {
  353. endAnim();
  354. return;
  355. }
  356. Point coords = CBattleHex::getXYUnitAnim(hex, owner->creDir[stack->ID], stack, owner);
  357. owner->creAnims[stack->ID]->pos.x = coords.x;
  358. //creAnims[stackID]->pos.y = coords.second;
  359. if(stack->doubleWide())
  360. {
  361. if(stack->attackerOwned)
  362. {
  363. if(!owner->creDir[stack->ID])
  364. owner->creAnims[stack->ID]->pos.x -= 44;
  365. }
  366. else
  367. {
  368. if(owner->creDir[stack->ID])
  369. owner->creAnims[stack->ID]->pos.x += 44;
  370. }
  371. }
  372. owner->creAnims[stack->ID]->setType(CCreatureAnim::TURN_L);
  373. secondPartSetup = true;
  374. }
  375. if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  376. {
  377. endAnim();
  378. }
  379. }
  380. }
  381. void CReverseAnim::endAnim()
  382. {
  383. CBattleAnimation::endAnim();
  384. if( stack->alive() )//don't do that if stack is dead
  385. owner->creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  386. delete this;
  387. }
  388. CReverseAnim::CReverseAnim(CBattleInterface * _owner, const CStack * stack, THex dest, bool _priority)
  389. : CBattleStackAnimation(_owner, stack), partOfAnim(1), secondPartSetup(false), hex(dest), priority(_priority)
  390. {
  391. }
  392. //defence anim
  393. bool CDefenceAnim::init()
  394. {
  395. //checking initial conditions
  396. //if(owner->creAnims[stackID]->getType() != 2)
  397. //{
  398. // return false;
  399. //}
  400. if(attacker == NULL && owner->battleEffects.size() > 0)
  401. return false;
  402. int lowestMoveID = owner->animIDhelper + 5;
  403. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  404. {
  405. CDefenceAnim * defAnim = dynamic_cast<CDefenceAnim *>(it->first);
  406. if(defAnim && defAnim->stack->ID != stack->ID)
  407. continue;
  408. CBattleAttack * attAnim = dynamic_cast<CBattleAttack *>(it->first);
  409. if(attAnim && attAnim->stack->ID != stack->ID)
  410. continue;
  411. if(attacker != NULL)
  412. {
  413. int attackerAnimType = owner->creAnims[attacker->ID]->getType();
  414. if( attackerAnimType == 11 && attackerAnimType == 12 && attackerAnimType == 13 && owner->creAnims[attacker->ID]->getFrame() < attacker->getCreature()->attackClimaxFrame )
  415. return false;
  416. }
  417. CReverseAnim * animAsRev = dynamic_cast<CReverseAnim *>(it->first);
  418. if(animAsRev && animAsRev->priority)
  419. return false;
  420. if(it->first)
  421. amin(lowestMoveID, it->first->ID);
  422. }
  423. if(ID > lowestMoveID)
  424. return false;
  425. //reverse unit if necessary
  426. if(attacker && isToReverse(stack->position, attacker->position, owner->creDir[stack->ID], attacker->doubleWide(), owner->creDir[attacker->ID]))
  427. {
  428. owner->addNewAnim(new CReverseAnim(owner, stack, stack->position, true));
  429. return false;
  430. }
  431. //unit reversed
  432. if(byShooting) //delay hit animation
  433. {
  434. for(std::list<SProjectileInfo>::const_iterator it = owner->projectiles.begin(); it != owner->projectiles.end(); ++it)
  435. {
  436. if(it->creID == attacker->getCreature()->idNumber)
  437. {
  438. return false;
  439. }
  440. }
  441. }
  442. //initializing
  443. if(killed)
  444. {
  445. CCS->soundh->playSound(battle_sound(stack->getCreature(), killed));
  446. owner->creAnims[stack->ID]->setType(CCreatureAnim::DEATH); //death
  447. }
  448. else
  449. {
  450. // TODO: this block doesn't seems correct if the unit is defending.
  451. CCS->soundh->playSound(battle_sound(stack->getCreature(), wince));
  452. owner->creAnims[stack->ID]->setType(CCreatureAnim::HITTED); //getting hit
  453. }
  454. return true; //initialized successfuly
  455. }
  456. void CDefenceAnim::nextFrame()
  457. {
  458. if(!killed && owner->creAnims[stack->ID]->getType() != CCreatureAnim::HITTED)
  459. {
  460. owner->creAnims[stack->ID]->setType(CCreatureAnim::HITTED);
  461. }
  462. if(!owner->creAnims[stack->ID]->onLastFrameInGroup())
  463. {
  464. if( owner->creAnims[stack->ID]->getType() == CCreatureAnim::DEATH && (owner->animCount+1)%(4/owner->curInt->sysOpts.animSpeed)==0
  465. && !owner->creAnims[stack->ID]->onLastFrameInGroup() )
  466. {
  467. owner->creAnims[stack->ID]->incrementFrame();
  468. }
  469. }
  470. else
  471. {
  472. endAnim();
  473. }
  474. }
  475. void CDefenceAnim::endAnim()
  476. {
  477. //restoring animType
  478. if(owner->creAnims[stack->ID]->getType() == CCreatureAnim::HITTED)
  479. owner->creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  480. //printing info to console
  481. //if(attacker!=NULL)
  482. // owner->printConsoleAttacked(stack, dmg, amountKilled, attacker);
  483. //const CStack * attacker = owner->curInt->cb->battleGetStackByID(IDby, false);
  484. //const CStack * attacked = owner->curInt->cb->battleGetStackByID(stackID, false);
  485. CBattleAnimation::endAnim();
  486. delete this;
  487. }
  488. CDefenceAnim::CDefenceAnim(SStackAttackedInfo _attackedInfo, CBattleInterface * _owner)
  489. : CBattleStackAnimation(_owner, _attackedInfo.defender), dmg(_attackedInfo.dmg),
  490. amountKilled(_attackedInfo.amountKilled), attacker(_attackedInfo.attacker), byShooting(_attackedInfo.byShooting),
  491. killed(_attackedInfo.killed)
  492. {
  493. }
  494. ////move anim
  495. bool CBattleStackMoved::init()
  496. {
  497. if( !isEarliest(false) )
  498. return false;
  499. //a few useful variables
  500. steps = owner->creAnims[stack->ID]->framesInGroup(CCreatureAnim::MOVING)*owner->getAnimSpeedMultiplier()-1;
  501. if(steps == 0) //this creature seems to have no move animation so we can end it immediately
  502. {
  503. endAnim();
  504. return false;
  505. }
  506. whichStep = 0;
  507. int hexWbase = 44, hexHbase = 42;
  508. const CStack * movedStack = stack;
  509. if(!movedStack || owner->creAnims[stack->ID]->getType() == 5)
  510. {
  511. endAnim();
  512. return false;
  513. }
  514. //bool twoTiles = movedStack->doubleWide();
  515. Point begPosition = CBattleHex::getXYUnitAnim(curStackPos, movedStack->attackerOwned, movedStack, owner);
  516. Point endPosition = CBattleHex::getXYUnitAnim(nextHex, movedStack->attackerOwned, movedStack, owner);
  517. int mutPos = THex::mutualPosition(curStackPos, nextHex);
  518. //reverse unit if necessary
  519. if((begPosition.x > endPosition.x) && owner->creDir[stack->ID] == true)
  520. {
  521. owner->addNewAnim(new CReverseAnim(owner, stack, curStackPos, true));
  522. return false;
  523. }
  524. else if ((begPosition.x < endPosition.x) && owner->creDir[stack->ID] == false)
  525. {
  526. owner->addNewAnim(new CReverseAnim(owner, stack, curStackPos, true));
  527. return false;
  528. }
  529. if(owner->creAnims[stack->ID]->getType() != CCreatureAnim::MOVING)
  530. {
  531. owner->creAnims[stack->ID]->setType(CCreatureAnim::MOVING);
  532. }
  533. //unit reversed
  534. // if(owner->moveSh <= 0)
  535. // owner->moveSh = CCS->soundh->playSound(battle_sound(movedStack->getCreature(), move), -1);
  536. //step shift calculation
  537. posX = owner->creAnims[stack->ID]->pos.x, posY = owner->creAnims[stack->ID]->pos.y; // for precise calculations ;]
  538. if(mutPos == -1 && movedStack->hasBonusOfType(Bonus::FLYING))
  539. {
  540. steps *= distance;
  541. steps /= 2; //to make animation faster
  542. stepX = (endPosition.x - (float)begPosition.x)/steps;
  543. stepY = (endPosition.y - (float)begPosition.y)/steps;
  544. }
  545. else
  546. {
  547. switch(mutPos)
  548. {
  549. case 0:
  550. stepX = (-1.0)*((float)hexWbase)/(2.0f*steps);
  551. stepY = (-1.0)*((float)hexHbase)/((float)steps);
  552. break;
  553. case 1:
  554. stepX = ((float)hexWbase)/(2.0f*steps);
  555. stepY = (-1.0)*((float)hexHbase)/((float)steps);
  556. break;
  557. case 2:
  558. stepX = ((float)hexWbase)/((float)steps);
  559. stepY = 0.0;
  560. break;
  561. case 3:
  562. stepX = ((float)hexWbase)/(2.0f*steps);
  563. stepY = ((float)hexHbase)/((float)steps);
  564. break;
  565. case 4:
  566. stepX = (-1.0)*((float)hexWbase)/(2.0f*steps);
  567. stepY = ((float)hexHbase)/((float)steps);
  568. break;
  569. case 5:
  570. stepX = (-1.0)*((float)hexWbase)/((float)steps);
  571. stepY = 0.0;
  572. break;
  573. }
  574. }
  575. //step shifts calculated
  576. return true;
  577. }
  578. void CBattleStackMoved::nextFrame()
  579. {
  580. //moving instructions
  581. posX += stepX;
  582. owner->creAnims[stack->ID]->pos.x = posX;
  583. posY += stepY;
  584. owner->creAnims[stack->ID]->pos.y = posY;
  585. // Increments step count and check if we are finished with current animation
  586. ++whichStep;
  587. if(whichStep == steps)
  588. {
  589. // Sets the position of the creature animation sprites
  590. Point coords = CBattleHex::getXYUnitAnim(nextHex, owner->creDir[stack->ID], stack, owner);
  591. owner->creAnims[stack->ID]->pos = coords;
  592. // true if creature haven't reached the final destination hex
  593. if ((nextPos + 1) < destTiles.size())
  594. {
  595. // update the next hex field which has to be reached by the stack
  596. nextPos++;
  597. curStackPos = nextHex;
  598. nextHex = destTiles[nextPos];
  599. // update position of double wide creatures
  600. bool twoTiles = stack->doubleWide();
  601. if(twoTiles && bool(stack->attackerOwned) && (owner->creDir[stack->ID] != bool(stack->attackerOwned) )) //big attacker creature is reversed
  602. owner->creAnims[stack->ID]->pos.x -= 44;
  603. else if(twoTiles && (! bool(stack->attackerOwned) ) && (owner->creDir[stack->ID] != bool(stack->attackerOwned) )) //big defender creature is reversed
  604. owner->creAnims[stack->ID]->pos.x += 44;
  605. // re-init animation
  606. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  607. {
  608. if (it->first == this)
  609. {
  610. it->second = false;
  611. break;
  612. }
  613. }
  614. }
  615. else
  616. endAnim();
  617. }
  618. }
  619. void CBattleStackMoved::endAnim()
  620. {
  621. const CStack * movedStack = stack;
  622. CBattleAnimation::endAnim();
  623. if(movedStack)
  624. owner->addNewAnim(new CBattleMoveEnd(owner, stack, nextHex));
  625. if(owner->moveSh >= 0)
  626. {
  627. CCS->soundh->stopSound(owner->moveSh);
  628. owner->moveSh = -1;
  629. }
  630. delete this;
  631. }
  632. CBattleStackMoved::CBattleStackMoved(CBattleInterface * _owner, const CStack * _stack, std::vector<THex> _destTiles, int _distance)
  633. : CBattleStackAnimation(_owner, _stack), destTiles(_destTiles), nextPos(0), distance(_distance), stepX(0.0f), stepY(0.0f)
  634. {
  635. curStackPos = stack->position;
  636. nextHex = destTiles.front();
  637. }
  638. //move started
  639. bool CBattleMoveStart::init()
  640. {
  641. if( !isEarliest(false) )
  642. return false;
  643. if(!stack || owner->creAnims[stack->ID]->getType() == 5)
  644. {
  645. CBattleMoveStart::endAnim();
  646. return false;
  647. }
  648. CCS->soundh->playSound(battle_sound(stack->getCreature(), startMoving));
  649. owner->creAnims[stack->ID]->setType(CCreatureAnim::MOVE_START);
  650. return true;
  651. }
  652. void CBattleMoveStart::nextFrame()
  653. {
  654. if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  655. {
  656. endAnim();
  657. }
  658. else
  659. {
  660. if((owner->animCount+1)%(4/owner->curInt->sysOpts.animSpeed)==0)
  661. owner->creAnims[stack->ID]->incrementFrame();
  662. }
  663. }
  664. void CBattleMoveStart::endAnim()
  665. {
  666. CBattleAnimation::endAnim();
  667. delete this;
  668. }
  669. CBattleMoveStart::CBattleMoveStart(CBattleInterface * _owner, const CStack * _stack)
  670. : CBattleStackAnimation(_owner, _stack)
  671. {
  672. }
  673. //move finished
  674. bool CBattleMoveEnd::init()
  675. {
  676. if( !isEarliest(true) )
  677. return false;
  678. if(!stack || owner->creAnims[stack->ID]->framesInGroup(CCreatureAnim::MOVE_END) == 0 ||
  679. owner->creAnims[stack->ID]->getType() == CCreatureAnim::DEATH)
  680. {
  681. endAnim();
  682. return false;
  683. }
  684. CCS->soundh->playSound(battle_sound(stack->getCreature(), endMoving));
  685. owner->creAnims[stack->ID]->setType(CCreatureAnim::MOVE_END);
  686. return true;
  687. }
  688. void CBattleMoveEnd::nextFrame()
  689. {
  690. if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  691. {
  692. endAnim();
  693. }
  694. }
  695. void CBattleMoveEnd::endAnim()
  696. {
  697. CBattleAnimation::endAnim();
  698. if(owner->creAnims[stack->ID]->getType() != CCreatureAnim::DEATH)
  699. owner->creAnims[stack->ID]->setType(CCreatureAnim::HOLDING); //resetting to default
  700. CCS->curh->show();
  701. delete this;
  702. }
  703. CBattleMoveEnd::CBattleMoveEnd(CBattleInterface * _owner, const CStack * _stack, THex destTile)
  704. : CBattleStackAnimation(_owner, _stack), destinationTile(destTile)
  705. {
  706. }
  707. //general attack anim
  708. void CBattleAttack::nextFrame()
  709. {
  710. if(owner->creAnims[stack->ID]->getType() != group)
  711. owner->creAnims[stack->ID]->setType(group);
  712. if(owner->creAnims[stack->ID]->onFirstFrameInGroup())
  713. {
  714. if(shooting)
  715. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), shoot));
  716. else
  717. CCS->soundh->playSound(battle_sound(attackingStack->getCreature(), attack));
  718. }
  719. else if(owner->creAnims[stack->ID]->onLastFrameInGroup())
  720. {
  721. owner->creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  722. endAnim();
  723. return; //execution of endAnim deletes this !!!
  724. }
  725. }
  726. bool CBattleAttack::checkInitialConditions()
  727. {
  728. return isEarliest(false);
  729. }
  730. CBattleAttack::CBattleAttack(CBattleInterface * _owner, const CStack * attacker, THex _dest, const CStack * defender)
  731. : CBattleStackAnimation(_owner, attacker), dest(_dest), attackedStack(defender), attackingStack(attacker)
  732. {
  733. assert(attackingStack && "attackingStack is NULL in CBattleAttack::CBattleAttack !\n");
  734. if(attackingStack->getCreature()->idNumber != 145) //catapult is allowed to attack not-creature
  735. {
  736. assert(attackedStack && "attackedStack is NULL in CBattleAttack::CBattleAttack !\n");
  737. }
  738. else //catapult can attack walls only
  739. {
  740. assert(owner->curInt->cb->battleGetWallUnderHex(_dest) >= 0);
  741. }
  742. attackingStackPosBeforeReturn = attackingStack->position;
  743. }
  744. ////melee attack
  745. bool CMeleeAttack::init()
  746. {
  747. if( !CBattleAttack::checkInitialConditions() )
  748. return false;
  749. //if(owner->creAnims[stackID]->getType()!=2)
  750. //{
  751. // return false;
  752. //}
  753. if(!attackingStack || owner->creAnims[stack->ID]->getType() == 5)
  754. {
  755. endAnim();
  756. return false;
  757. }
  758. bool toReverse = isToReverse(attackingStackPosBeforeReturn, dest, owner->creDir[stack->ID], attackedStack->doubleWide(), owner->creDir[attackedStack->ID]);
  759. if(toReverse)
  760. {
  761. owner->addNewAnim(new CReverseAnim(owner, stack, attackingStackPosBeforeReturn, true));
  762. return false;
  763. }
  764. //reversed
  765. shooting = false;
  766. static const CCreatureAnim::EAnimType mutPosToGroup[] = {CCreatureAnim::ATTACK_UP, CCreatureAnim::ATTACK_UP,
  767. CCreatureAnim::ATTACK_FRONT, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_DOWN, CCreatureAnim::ATTACK_FRONT};
  768. int revShiftattacker = (attackingStack->attackerOwned ? -1 : 1);
  769. int mutPos = THex::mutualPosition(attackingStackPosBeforeReturn, dest);
  770. if(mutPos == -1 && attackingStack->doubleWide())
  771. {
  772. mutPos = THex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->position);
  773. }
  774. if (mutPos == -1 && attackedStack->doubleWide())
  775. {
  776. mutPos = THex::mutualPosition(attackingStackPosBeforeReturn, attackedStack->occupiedHex());
  777. }
  778. if (mutPos == -1 && attackedStack->doubleWide() && attackingStack->doubleWide())
  779. {
  780. mutPos = THex::mutualPosition(attackingStackPosBeforeReturn + revShiftattacker, attackedStack->occupiedHex());
  781. }
  782. switch(mutPos) //attack direction
  783. {
  784. case 0: case 1: case 2: case 3: case 4: case 5:
  785. group = mutPosToGroup[mutPos];
  786. break;
  787. default:
  788. tlog1<<"Critical Error! Wrong dest in stackAttacking! dest: "<<dest<<" attacking stack pos: "<<attackingStackPosBeforeReturn<<" mutual pos: "<<mutPos<<std::endl;
  789. group = CCreatureAnim::ATTACK_FRONT;
  790. break;
  791. }
  792. return true;
  793. }
  794. void CMeleeAttack::nextFrame()
  795. {
  796. /*for(std::list<std::pair<CBattleAnimation *, bool> >::const_iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  797. {
  798. CBattleMoveStart * anim = dynamic_cast<CBattleMoveStart *>(it->first);
  799. CReverseAnim * anim2 = dynamic_cast<CReverseAnim *>(it->first);
  800. if( (anim && anim->stackID == stackID) || (anim2 && anim2->stackID == stackID ) )
  801. return;
  802. }*/
  803. CBattleAttack::nextFrame();
  804. }
  805. void CMeleeAttack::endAnim()
  806. {
  807. CBattleAnimation::endAnim();
  808. delete this;
  809. }
  810. CMeleeAttack::CMeleeAttack(CBattleInterface * _owner, const CStack * attacker, THex _dest, const CStack * _attacked)
  811. : CBattleAttack(_owner, attacker, _dest, _attacked)
  812. {
  813. }
  814. //shooting anim
  815. bool CShootingAnim::init()
  816. {
  817. if( !CBattleAttack::checkInitialConditions() )
  818. return false;
  819. const CStack * shooter = attackingStack;
  820. if(!shooter || owner->creAnims[stack->ID]->getType() == 5)
  821. {
  822. endAnim();
  823. return false;
  824. }
  825. // Create the projectile animation
  826. float projectileAngle; //in radians; if positive, projectiles goes up
  827. float straightAngle = 0.2f; //maximal angle in radians between straight horizontal line and shooting line for which shot is considered to be straight (absoulte value)
  828. int fromHex = shooter->position;
  829. projectileAngle = atan2(float(abs(dest - fromHex) / BFIELD_WIDTH), float(abs(dest - fromHex) % BFIELD_WIDTH));
  830. if(fromHex < dest)
  831. projectileAngle = -projectileAngle;
  832. // Get further info about the shooter e.g. relative pos of projectile to unit.
  833. // If the creature id is 149 then it's a arrow tower which has no additional info so get the
  834. // actual arrow tower shooter instead.
  835. const CCreature *shooterInfo = shooter->getCreature();
  836. if (shooterInfo->idNumber == 149)
  837. {
  838. int creID = CGI->creh->factionToTurretCreature[owner->siegeH->town->town->typeID];
  839. shooterInfo = CGI->creh->creatures[creID];
  840. }
  841. SProjectileInfo spi;
  842. spi.creID = shooter->getCreature()->idNumber;
  843. spi.stackID = shooter->ID;
  844. spi.reverse = !shooter->attackerOwned;
  845. spi.step = 0;
  846. spi.frameNum = 0;
  847. if(vstd::contains(CGI->creh->idToProjectileSpin, shooterInfo->idNumber))
  848. spi.spin = CGI->creh->idToProjectileSpin[shooterInfo->idNumber];
  849. else
  850. {
  851. tlog2 << "Warning - no projectile spin for spi.creID " << shooterInfo->idNumber << std::endl;
  852. spi.spin = false;
  853. }
  854. Point xycoord = CBattleHex::getXYUnitAnim(shooter->position, true, shooter, owner);
  855. Point destcoord;
  856. // The "master" point where all projectile positions relate to.
  857. static const Point projectileOrigin(181, 252);
  858. if (attackedStack)
  859. {
  860. destcoord = CBattleHex::getXYUnitAnim(dest, false, attackedStack, owner);
  861. destcoord.x += 250; destcoord.y += 210; //TODO: find a better place to shoot
  862. // Calculate projectile start position. Offsets are read out of the CRANIM.TXT.
  863. if (projectileAngle > straightAngle)
  864. {
  865. //upper shot
  866. spi.x = xycoord.x + projectileOrigin.x + shooterInfo->upperRightMissleOffsetX;
  867. spi.y = xycoord.y + projectileOrigin.y + shooterInfo->upperRightMissleOffsetY;
  868. }
  869. else if (projectileAngle < -straightAngle)
  870. {
  871. //lower shot
  872. spi.x = xycoord.x + projectileOrigin.x + shooterInfo->lowerRightMissleOffsetX;
  873. spi.y = xycoord.y + projectileOrigin.y + shooterInfo->lowerRightMissleOffsetY;
  874. }
  875. else
  876. {
  877. //straight shot
  878. spi.x = xycoord.x + projectileOrigin.x + shooterInfo->rightMissleOffsetX;
  879. spi.y = xycoord.y + projectileOrigin.y + shooterInfo->rightMissleOffsetY;
  880. }
  881. double animSpeed = 23.0 * owner->getAnimSpeed(); // flight speed of projectile
  882. spi.lastStep = sqrt((float)((destcoord.x - spi.x)*(destcoord.x - spi.x) + (destcoord.y - spi.y) * (destcoord.y - spi.y))) / animSpeed;
  883. if(spi.lastStep == 0)
  884. spi.lastStep = 1;
  885. spi.dx = (destcoord.x - spi.x) / spi.lastStep;
  886. spi.dy = (destcoord.y - spi.y) / spi.lastStep;
  887. spi.catapultInfo = 0;
  888. }
  889. else
  890. {
  891. // Catapult attack
  892. // These are the values for equations of this kind: f(x) = ax^2 + bx + c
  893. static const std::vector<CatapultProjectileInfo*> trajectoryCurves = boost::assign::list_of<CatapultProjectileInfo*>(new CatapultProjectileInfo(4.309, -3.198, 569.2, -296, 182))
  894. (new CatapultProjectileInfo(4.710, -3.11, 558.68, -258, 175))(new CatapultProjectileInfo(5.056, -3.003, 546.9, -236, 174))
  895. (new CatapultProjectileInfo(4.760, -2.74, 526.47, -216, 215))(new CatapultProjectileInfo(4.288, -2.496, 508.98, -223, 274))
  896. (new CatapultProjectileInfo(3.683, -3.018, 558.39, -324, 176))(new CatapultProjectileInfo(2.884, -2.607, 528.95, -366, 312))
  897. (new CatapultProjectileInfo(3.783, -2.364, 501.35, -227, 318));
  898. static std::map<int, int> hexToCurve = boost::assign::map_list_of<int, int>(29, 0)(62, 1)(95, 2)(130, 3)(182, 4)(12, 5)(50, 6)(183, 7);
  899. std::map<int, int>::iterator it = hexToCurve.find(dest.hex);
  900. if (it == hexToCurve.end())
  901. {
  902. tlog1 << "For the hex position " << dest.hex << " is no curve defined.";
  903. endAnim();
  904. return false;
  905. }
  906. else
  907. {
  908. int curveID = it->second;
  909. spi.catapultInfo = trajectoryCurves[curveID];
  910. double animSpeed = 3.318 * owner->getAnimSpeed();
  911. spi.lastStep = (spi.catapultInfo->toX - spi.catapultInfo->fromX) / animSpeed;
  912. spi.dx = animSpeed;
  913. spi.dy = 0;
  914. spi.x = xycoord.x + projectileOrigin.x + shooterInfo->rightMissleOffsetX + 17.;
  915. spi.y = xycoord.y + projectileOrigin.y + shooterInfo->rightMissleOffsetY + 10.;
  916. // Add explosion anim
  917. int xEnd = spi.x + spi.lastStep * spi.dx;
  918. int yEnd = spi.catapultInfo->calculateY(xEnd);
  919. owner->addNewAnim( new CSpellEffectAnim(owner, "SGEXPL.DEF", xEnd - 126, yEnd - 105));
  920. }
  921. }
  922. // Set starting frame
  923. if(spi.spin)
  924. {
  925. spi.frameNum = 0;
  926. }
  927. else
  928. {
  929. spi.frameNum = ((M_PI/2.0f - projectileAngle) / (2.0f *M_PI) + 1/((float)(2*(owner->idToProjectile[spi.creID]->ourImages.size()-1)))) * (owner->idToProjectile[spi.creID]->ourImages.size()-1);
  930. }
  931. // Set projectile animation start delay which is specified in frames
  932. spi.animStartDelay = shooterInfo->attackClimaxFrame;
  933. owner->projectiles.push_back(spi);
  934. //attack animation
  935. shooting = true;
  936. if(projectileAngle > straightAngle) //upper shot
  937. group = CCreatureAnim::SHOOT_UP;
  938. else if(projectileAngle < -straightAngle) //lower shot
  939. group = CCreatureAnim::SHOOT_DOWN;
  940. else //straight shot
  941. group = CCreatureAnim::SHOOT_FRONT;
  942. return true;
  943. }
  944. void CShootingAnim::nextFrame()
  945. {
  946. for(std::list<std::pair<CBattleAnimation *, bool> >::const_iterator it = owner->pendingAnims.begin(); it != owner->pendingAnims.end(); ++it)
  947. {
  948. CBattleMoveStart * anim = dynamic_cast<CBattleMoveStart *>(it->first);
  949. CReverseAnim * anim2 = dynamic_cast<CReverseAnim *>(it->first);
  950. if( (anim && anim->stack->ID == stack->ID) || (anim2 && anim2->stack->ID == stack->ID && anim2->priority ) )
  951. return;
  952. }
  953. CBattleAttack::nextFrame();
  954. }
  955. void CShootingAnim::endAnim()
  956. {
  957. CBattleAnimation::endAnim();
  958. delete this;
  959. }
  960. CShootingAnim::CShootingAnim(CBattleInterface * _owner, const CStack * attacker, THex _dest, const CStack * _attacked, bool _catapult, int _catapultDmg)
  961. : CBattleAttack(_owner, attacker, _dest, _attacked), catapultDamage(_catapultDmg), catapult(_catapult)
  962. {
  963. }
  964. ////////////////////////
  965. void CBattleInterface::addNewAnim(CBattleAnimation * anim)
  966. {
  967. pendingAnims.push_back( std::make_pair(anim, false) );
  968. animsAreDisplayed.setn(true);
  969. }
  970. CBattleInterface::CBattleInterface(const CCreatureSet * army1, const CCreatureSet * army2, CGHeroInstance *hero1, CGHeroInstance *hero2, const SDL_Rect & myRect, CPlayerInterface * att, CPlayerInterface * defen)
  971. : queue(NULL), attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0),
  972. activeStack(NULL), stackToActivate(NULL), mouseHoveredStack(-1), previouslyHoveredHex(-1),
  973. currentlyHoveredHex(-1), tacticianInterface(NULL), spellDestSelectMode(false), spellToCast(NULL),
  974. siegeH(NULL), attackerInt(att), defenderInt(defen), curInt(att), animIDhelper(0), givenCommand(NULL),
  975. myTurn(false), resWindow(NULL), moveStarted(false), moveSh(-1), bresult(NULL)
  976. {
  977. ObjectConstruction h__l__p(this);
  978. if(!curInt) curInt = LOCPLINT; //may happen when we are defending during network MP game
  979. animsAreDisplayed.setn(false);
  980. pos = myRect;
  981. strongInterest = true;
  982. givenCommand = new CondSh<BattleAction *>(NULL);
  983. if(attackerInt && attackerInt->cb->battleGetTacticDist()) //hotseat -> check tactics for both players (defender may be local human)
  984. tacticianInterface = attackerInt;
  985. else if(defenderInt && defenderInt->cb->battleGetTacticDist())
  986. tacticianInterface = defenderInt;
  987. tacticsMode = tacticianInterface; //if we found interface of player with tactics, then enter tactics mode
  988. //create stack queue
  989. bool embedQueue = screen->h < 700;
  990. queue = new CStackQueue(embedQueue, this);
  991. if(!embedQueue)
  992. {
  993. if(curInt->sysOpts.showQueue)
  994. pos.y += queue->pos.h / 2; //center whole window
  995. queue->moveTo(Point(pos.x, pos.y - queue->pos.h));
  996. // queue->pos.x = pos.x;
  997. // queue->pos.y = pos.y - queue->pos.h;
  998. // pos.h += queue->pos.h;
  999. // center();
  1000. }
  1001. queue->update();
  1002. //preparing siege info
  1003. const CGTownInstance * town = curInt->cb->battleGetDefendedTown();
  1004. if(town && town->hasFort())
  1005. {
  1006. siegeH = new SiegeHelper(town, this);
  1007. }
  1008. curInt->battleInt = this;
  1009. //initializing armies
  1010. this->army1 = army1;
  1011. this->army2 = army2;
  1012. std::vector<const CStack*> stacks = curInt->cb->battleGetAllStacks();
  1013. BOOST_FOREACH(const CStack *s, stacks)
  1014. {
  1015. newStack(s);
  1016. }
  1017. //preparing menu background and terrain
  1018. if(siegeH)
  1019. {
  1020. background = BitmapHandler::loadBitmap( siegeH->getSiegeName(0), false );
  1021. ui8 siegeLevel = curInt->cb->battleGetSiegeLevel();
  1022. if(siegeLevel >= 2) //citadel or castle
  1023. {
  1024. //print moat/mlip
  1025. SDL_Surface * moat = BitmapHandler::loadBitmap( siegeH->getSiegeName(13) ),
  1026. * mlip = BitmapHandler::loadBitmap( siegeH->getSiegeName(14) );
  1027. Point moatPos = graphics->wallPositions[siegeH->town->town->typeID][12],
  1028. mlipPos = graphics->wallPositions[siegeH->town->town->typeID][13];
  1029. if(moat) //eg. tower has no moat
  1030. blitAt(moat, moatPos.x,moatPos.y, background);
  1031. if(mlip) //eg. tower has no mlip
  1032. blitAt(mlip, mlipPos.x, mlipPos.y, background);
  1033. SDL_FreeSurface(moat);
  1034. SDL_FreeSurface(mlip);
  1035. }
  1036. }
  1037. else
  1038. {
  1039. std::vector< std::string > & backref = graphics->battleBacks[ curInt->cb->battleGetBattlefieldType() ];
  1040. background = BitmapHandler::loadBitmap(backref[ rand() % backref.size()], false );
  1041. }
  1042. //preparing menu background
  1043. //graphics->blueToPlayersAdv(menu, hero1->tempOwner);
  1044. //preparing graphics for displaying amounts of creatures
  1045. amountNormal = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  1046. CSDL_Ext::alphaTransform(amountNormal);
  1047. transformPalette(amountNormal, 0.59f, 0.19f, 0.93f);
  1048. amountPositive = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  1049. CSDL_Ext::alphaTransform(amountPositive);
  1050. transformPalette(amountPositive, 0.18f, 1.00f, 0.18f);
  1051. amountNegative = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  1052. CSDL_Ext::alphaTransform(amountNegative);
  1053. transformPalette(amountNegative, 1.00f, 0.18f, 0.18f);
  1054. amountEffNeutral = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
  1055. CSDL_Ext::alphaTransform(amountEffNeutral);
  1056. transformPalette(amountEffNeutral, 1.00f, 1.00f, 0.18f);
  1057. ////blitting menu background and terrain
  1058. // blitAt(background, pos.x, pos.y);
  1059. // blitAt(menu, pos.x, 556 + pos.y);
  1060. //preparing buttons and console
  1061. bOptions = new AdventureMapButton (CGI->generaltexth->zelp[381].first, CGI->generaltexth->zelp[381].second, boost::bind(&CBattleInterface::bOptionsf,this), 3 + pos.x, 561 + pos.y, "icm003.def", SDLK_o);
  1062. bSurrender = new AdventureMapButton (CGI->generaltexth->zelp[379].first, CGI->generaltexth->zelp[379].second, boost::bind(&CBattleInterface::bSurrenderf,this), 54 + pos.x, 561 + pos.y, "icm001.def", SDLK_s);
  1063. bFlee = new AdventureMapButton (CGI->generaltexth->zelp[380].first, CGI->generaltexth->zelp[380].second, boost::bind(&CBattleInterface::bFleef,this), 105 + pos.x, 561 + pos.y, "icm002.def", SDLK_r);
  1064. bFlee->block(!curInt->cb->battleCanFlee());
  1065. bSurrender->block(curInt->cb->battleGetSurrenderCost() < 0);
  1066. bAutofight = new AdventureMapButton (CGI->generaltexth->zelp[382].first, CGI->generaltexth->zelp[382].second, boost::bind(&CBattleInterface::bAutofightf,this), 157 + pos.x, 561 + pos.y, "icm004.def", SDLK_a);
  1067. bSpell = new AdventureMapButton (CGI->generaltexth->zelp[385].first, CGI->generaltexth->zelp[385].second, boost::bind(&CBattleInterface::bSpellf,this), 645 + pos.x, 561 + pos.y, "icm005.def", SDLK_c);
  1068. bSpell->block(true);
  1069. bWait = new AdventureMapButton (CGI->generaltexth->zelp[386].first, CGI->generaltexth->zelp[386].second, boost::bind(&CBattleInterface::bWaitf,this), 696 + pos.x, 561 + pos.y, "icm006.def", SDLK_w);
  1070. bDefence = new AdventureMapButton (CGI->generaltexth->zelp[387].first, CGI->generaltexth->zelp[387].second, boost::bind(&CBattleInterface::bDefencef,this), 747 + pos.x, 561 + pos.y, "icm007.def", SDLK_d);
  1071. bDefence->assignedKeys.insert(SDLK_SPACE);
  1072. bConsoleUp = new AdventureMapButton (std::string(), std::string(), boost::bind(&CBattleInterface::bConsoleUpf,this), 624 + pos.x, 561 + pos.y, "ComSlide.def", SDLK_UP);
  1073. bConsoleDown = new AdventureMapButton (std::string(), std::string(), boost::bind(&CBattleInterface::bConsoleDownf,this), 624 + pos.x, 580 + pos.y, "ComSlide.def", SDLK_DOWN);
  1074. bConsoleDown->setOffset(2);
  1075. console = new CBattleConsole();
  1076. console->pos.x = 211 + pos.x;
  1077. console->pos.y = 560 + pos.y;
  1078. console->pos.w = 406;
  1079. console->pos.h = 38;
  1080. if(tacticsMode)
  1081. {
  1082. btactNext = new AdventureMapButton(std::string(), std::string(), boost::bind(&CBattleInterface::bTacticNextStack,this), 213 + pos.x, 560 + pos.y, "icm011.def", SDLK_SPACE);
  1083. btactEnd = new AdventureMapButton(std::string(), std::string(), boost::bind(&CBattleInterface::bEndTacticPhase,this), 419 + pos.x, 560 + pos.y, "icm012.def", SDLK_RETURN);
  1084. bDefence->block(true);
  1085. bWait->block(true);
  1086. menu = BitmapHandler::loadBitmap("COPLACBR.BMP");
  1087. }
  1088. else
  1089. {
  1090. menu = BitmapHandler::loadBitmap("CBAR.BMP");
  1091. btactEnd = btactNext = NULL;
  1092. }
  1093. graphics->blueToPlayersAdv(menu, curInt->playerID);
  1094. //loading hero animations
  1095. if(hero1) // attacking hero
  1096. {
  1097. int type = hero1->type->heroType;
  1098. if ( type % 2 ) type--;
  1099. if ( hero1->sex ) type++;
  1100. attackingHero = new CBattleHero(graphics->battleHeroes[type], 0, 0, false, hero1->tempOwner, hero1->tempOwner == curInt->playerID ? hero1 : NULL, this);
  1101. attackingHero->pos = genRect(attackingHero->dh->ourImages[0].bitmap->h, attackingHero->dh->ourImages[0].bitmap->w, pos.x - 43, pos.y - 19);
  1102. }
  1103. else
  1104. {
  1105. attackingHero = NULL;
  1106. }
  1107. if(hero2) // defending hero
  1108. {
  1109. int type = hero2->type->heroType;
  1110. if ( type % 2 ) type--;
  1111. if ( hero2->sex ) type++;
  1112. defendingHero = new CBattleHero(graphics->battleHeroes[type ], 0, 0, true, hero2->tempOwner, hero2->tempOwner == curInt->playerID ? hero2 : NULL, this);
  1113. defendingHero->pos = genRect(defendingHero->dh->ourImages[0].bitmap->h, defendingHero->dh->ourImages[0].bitmap->w, pos.x + 693, pos.y - 19);
  1114. }
  1115. else
  1116. {
  1117. defendingHero = NULL;
  1118. }
  1119. //preparing cells and hexes
  1120. cellBorder = BitmapHandler::loadBitmap("CCELLGRD.BMP");
  1121. CSDL_Ext::alphaTransform(cellBorder);
  1122. cellShade = BitmapHandler::loadBitmap("CCELLSHD.BMP");
  1123. CSDL_Ext::alphaTransform(cellShade);
  1124. for(int h=0; h<BFIELD_SIZE; ++h)
  1125. {
  1126. bfield[h].myNumber = h;
  1127. int x = 14 + ((h/BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(h%BFIELD_WIDTH);
  1128. int y = 86 + 42 * (h/BFIELD_WIDTH);
  1129. bfield[h].pos = genRect(cellShade->h, cellShade->w, x + pos.x, y + pos.y);
  1130. bfield[h].accessible = true;
  1131. bfield[h].myInterface = this;
  1132. }
  1133. //locking occupied positions on batlefield
  1134. BOOST_FOREACH(const CStack *s, stacks) //stacks gained at top of this function
  1135. if(s->position >= 0) //turrets have position < 0
  1136. bfield[s->position].accessible = false;
  1137. //loading projectiles for units
  1138. BOOST_FOREACH(const CStack *s, stacks)
  1139. {
  1140. int creID = (s->getCreature()->idNumber == 149) ? CGI->creh->factionToTurretCreature[siegeH->town->town->typeID] : s->getCreature()->idNumber; //id of creature whose shots should be loaded
  1141. if(s->getCreature()->isShooting() && vstd::contains(CGI->creh->idToProjectile, creID))
  1142. {
  1143. CDefHandler *&projectile = idToProjectile[s->getCreature()->idNumber];
  1144. projectile = CDefHandler::giveDef(CGI->creh->idToProjectile[creID]);
  1145. if(projectile->ourImages.size() > 2) //add symmetric images
  1146. {
  1147. for(int k = projectile->ourImages.size()-2; k > 1; --k)
  1148. {
  1149. Cimage ci;
  1150. ci.bitmap = CSDL_Ext::rotate01(projectile->ourImages[k].bitmap);
  1151. ci.groupNumber = 0;
  1152. ci.imName = std::string();
  1153. projectile->ourImages.push_back(ci);
  1154. }
  1155. }
  1156. for(int s=0; s<projectile->ourImages.size(); ++s) //alpha transforming
  1157. {
  1158. CSDL_Ext::alphaTransform(projectile->ourImages[s].bitmap);
  1159. }
  1160. }
  1161. }
  1162. //preparing graphic with cell borders
  1163. cellBorders = CSDL_Ext::newSurface(background->w, background->h, cellBorder);
  1164. //copying palette
  1165. for(int g=0; g<cellBorder->format->palette->ncolors; ++g) //we assume that cellBorders->format->palette->ncolors == 256
  1166. {
  1167. cellBorders->format->palette->colors[g] = cellBorder->format->palette->colors[g];
  1168. }
  1169. //palette copied
  1170. for(int i=0; i<BFIELD_HEIGHT; ++i) //rows
  1171. {
  1172. for(int j=0; j<BFIELD_WIDTH-2; ++j) //columns
  1173. {
  1174. int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
  1175. int y = 86 + 42 * i;
  1176. for(int cellX = 0; cellX < cellBorder->w; ++cellX)
  1177. {
  1178. for(int cellY = 0; cellY < cellBorder->h; ++cellY)
  1179. {
  1180. if(y+cellY < cellBorders->h && x+cellX < cellBorders->w)
  1181. * ((Uint8*)cellBorders->pixels + (y+cellY) * cellBorders->pitch + (x+cellX)) |= * ((Uint8*)cellBorder->pixels + cellY * cellBorder->pitch + cellX);
  1182. }
  1183. }
  1184. }
  1185. }
  1186. backgroundWithHexes = CSDL_Ext::newSurface(background->w, background->h, screen);
  1187. //preparing obstacle defs
  1188. std::vector<CObstacleInstance> obst = curInt->cb->battleGetAllObstacles();
  1189. for(int t=0; t<obst.size(); ++t)
  1190. {
  1191. idToObstacle[obst[t].ID] = CDefHandler::giveDef(CGI->heroh->obstacles.find(obst[t].ID)->second.defName);
  1192. for(int n=0; n<idToObstacle[obst[t].ID]->ourImages.size(); ++n)
  1193. {
  1194. SDL_SetColorKey(idToObstacle[obst[t].ID]->ourImages[n].bitmap, SDL_SRCCOLORKEY, SDL_MapRGB(idToObstacle[obst[t].ID]->ourImages[n].bitmap->format,0,255,255));
  1195. }
  1196. }
  1197. for (int i = 0; i < ARRAY_COUNT(bfield); i++)
  1198. {
  1199. children.push_back(&bfield[i]);
  1200. }
  1201. if(tacticsMode)
  1202. {
  1203. active = 1;
  1204. bTacticNextStack();
  1205. active = 0;
  1206. }
  1207. }
  1208. CBattleInterface::~CBattleInterface()
  1209. {
  1210. if (active) //dirty fix for #485
  1211. {
  1212. deactivate();
  1213. }
  1214. SDL_FreeSurface(background);
  1215. SDL_FreeSurface(menu);
  1216. SDL_FreeSurface(amountNormal);
  1217. SDL_FreeSurface(amountNegative);
  1218. SDL_FreeSurface(amountPositive);
  1219. SDL_FreeSurface(amountEffNeutral);
  1220. SDL_FreeSurface(cellBorders);
  1221. SDL_FreeSurface(backgroundWithHexes);
  1222. delete bOptions;
  1223. delete bSurrender;
  1224. delete bFlee;
  1225. delete bAutofight;
  1226. delete bSpell;
  1227. delete bWait;
  1228. delete bDefence;
  1229. delete bConsoleUp;
  1230. delete bConsoleDown;
  1231. delete console;
  1232. delete givenCommand;
  1233. delete attackingHero;
  1234. delete defendingHero;
  1235. delete queue;
  1236. SDL_FreeSurface(cellBorder);
  1237. SDL_FreeSurface(cellShade);
  1238. for(std::map< int, CCreatureAnimation * >::iterator g=creAnims.begin(); g!=creAnims.end(); ++g)
  1239. delete g->second;
  1240. for(std::map< int, CDefHandler * >::iterator g=idToProjectile.begin(); g!=idToProjectile.end(); ++g)
  1241. delete g->second;
  1242. for(std::map< int, CDefHandler * >::iterator g=idToObstacle.begin(); g!=idToObstacle.end(); ++g)
  1243. delete g->second;
  1244. delete siegeH;
  1245. curInt->battleInt = NULL;
  1246. }
  1247. void CBattleInterface::setPrintCellBorders(bool set)
  1248. {
  1249. curInt->sysOpts.printCellBorders = set;
  1250. curInt->sysOpts.settingsChanged();
  1251. redrawBackgroundWithHexes(activeStack);
  1252. GH.totalRedraw();
  1253. }
  1254. void CBattleInterface::setPrintStackRange(bool set)
  1255. {
  1256. curInt->sysOpts.printStackRange = set;
  1257. curInt->sysOpts.settingsChanged();
  1258. redrawBackgroundWithHexes(activeStack);
  1259. GH.totalRedraw();
  1260. }
  1261. void CBattleInterface::setPrintMouseShadow(bool set)
  1262. {
  1263. curInt->sysOpts.printMouseShadow = set;
  1264. curInt->sysOpts.settingsChanged();
  1265. }
  1266. void CBattleInterface::activate()
  1267. {
  1268. activateKeys();
  1269. activateMouseMove();
  1270. activateRClick();
  1271. bOptions->activate();
  1272. bSurrender->activate();
  1273. bFlee->activate();
  1274. bAutofight->activate();
  1275. bSpell->activate();
  1276. bWait->activate();
  1277. bDefence->activate();
  1278. for(int b=0; b<BFIELD_SIZE; ++b)
  1279. {
  1280. bfield[b].activate();
  1281. }
  1282. if(attackingHero)
  1283. attackingHero->activate();
  1284. if(defendingHero)
  1285. defendingHero->activate();
  1286. if(curInt->sysOpts.showQueue)
  1287. queue->activate();
  1288. if(tacticsMode)
  1289. {
  1290. btactNext->activate();
  1291. btactEnd->activate();
  1292. }
  1293. else
  1294. {
  1295. bConsoleUp->activate();
  1296. bConsoleDown->activate();
  1297. }
  1298. LOCPLINT->cingconsole->activate();
  1299. }
  1300. void CBattleInterface::deactivate()
  1301. {
  1302. deactivateKeys();
  1303. deactivateMouseMove();
  1304. deactivateRClick();
  1305. bOptions->deactivate();
  1306. bSurrender->deactivate();
  1307. bFlee->deactivate();
  1308. bAutofight->deactivate();
  1309. bSpell->deactivate();
  1310. bWait->deactivate();
  1311. bDefence->deactivate();
  1312. for(int b=0; b<BFIELD_SIZE; ++b)
  1313. {
  1314. bfield[b].deactivate();
  1315. }
  1316. if(attackingHero)
  1317. attackingHero->deactivate();
  1318. if(defendingHero)
  1319. defendingHero->deactivate();
  1320. if(curInt->sysOpts.showQueue)
  1321. queue->deactivate();
  1322. if(tacticsMode)
  1323. {
  1324. btactNext->deactivate();
  1325. btactEnd->deactivate();
  1326. }
  1327. else
  1328. {
  1329. bConsoleUp->deactivate();
  1330. bConsoleDown->deactivate();
  1331. }
  1332. LOCPLINT->cingconsole->deactivate();
  1333. }
  1334. void CBattleInterface::show(SDL_Surface * to)
  1335. {
  1336. std::vector<const CStack*> stacks = curInt->cb->battleGetAllStacks(); //used in a few places
  1337. ++animCount;
  1338. if(!to) //"evaluating" to
  1339. to = screen;
  1340. SDL_Rect buf;
  1341. SDL_GetClipRect(to, &buf);
  1342. SDL_SetClipRect(to, &pos);
  1343. //printing background and hexes
  1344. if(activeStack != NULL && creAnims[activeStack->ID]->getType() != 0) //show everything with range
  1345. {
  1346. blitAt(backgroundWithHexes, pos.x, pos.y, to);
  1347. }
  1348. else
  1349. {
  1350. //showing background
  1351. blitAt(background, pos.x, pos.y, to);
  1352. if(curInt->sysOpts.printCellBorders)
  1353. {
  1354. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, NULL, to, &pos);
  1355. }
  1356. }
  1357. //printing hovered cell
  1358. for(int b=0; b<BFIELD_SIZE; ++b)
  1359. {
  1360. if(bfield[b].strictHovered && bfield[b].hovered)
  1361. {
  1362. if(previouslyHoveredHex == -1) previouslyHoveredHex = b; //something to start with
  1363. if(currentlyHoveredHex == -1) currentlyHoveredHex = b; //something to start with
  1364. if(currentlyHoveredHex != b) //repair hover info
  1365. {
  1366. previouslyHoveredHex = currentlyHoveredHex;
  1367. currentlyHoveredHex = b;
  1368. }
  1369. //print shade
  1370. if(spellToCast) //when casting spell
  1371. {
  1372. //calculating spell school level
  1373. const CSpell & spToCast = *CGI->spellh->spells[spellToCast->additionalInfo];
  1374. ui8 schoolLevel = 0;
  1375. if( activeStack->attackerOwned )
  1376. {
  1377. if(attackingHeroInstance)
  1378. schoolLevel = attackingHeroInstance->getSpellSchoolLevel(&spToCast);
  1379. }
  1380. else
  1381. {
  1382. if(defendingHeroInstance)
  1383. schoolLevel = defendingHeroInstance->getSpellSchoolLevel(&spToCast);
  1384. }
  1385. //obtaining range and printing it
  1386. std::set<ui16> shaded = spToCast.rangeInHexes(b, schoolLevel);
  1387. for(std::set<ui16>::iterator it = shaded.begin(); it != shaded.end(); ++it) //for spells with range greater then one hex
  1388. {
  1389. if(curInt->sysOpts.printMouseShadow && (*it % BFIELD_WIDTH != 0) && (*it % BFIELD_WIDTH != 16))
  1390. {
  1391. int x = 14 + ((*it/BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(*it%BFIELD_WIDTH) + pos.x;
  1392. int y = 86 + 42 * (*it/BFIELD_WIDTH) + pos.y;
  1393. SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
  1394. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, to, &temp_rect);
  1395. }
  1396. }
  1397. }
  1398. else if(curInt->sysOpts.printMouseShadow) //when not casting spell
  1399. {
  1400. int x = 14 + ((b/BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(b%BFIELD_WIDTH) + pos.x;
  1401. int y = 86 + 42 * (b/BFIELD_WIDTH) + pos.y;
  1402. SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
  1403. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, to, &temp_rect);
  1404. }
  1405. }
  1406. }
  1407. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  1408. //prevents blitting outside this window
  1409. SDL_GetClipRect(to, &buf);
  1410. SDL_SetClipRect(to, &pos);
  1411. //preparing obstacles to be shown
  1412. std::vector<CObstacleInstance> obstacles = curInt->cb->battleGetAllObstacles();
  1413. std::multimap<THex, int> hexToObstacle;
  1414. for(int b=0; b<obstacles.size(); ++b)
  1415. {
  1416. THex position = CGI->heroh->obstacles.find(obstacles[b].ID)->second.getMaxBlocked(obstacles[b].pos);
  1417. hexToObstacle.insert(std::make_pair(position, b));
  1418. }
  1419. ////showing units //a lot of work...
  1420. std::vector<const CStack *> stackAliveByHex[BFIELD_SIZE];
  1421. //double loop because dead stacks should be printed first
  1422. for (int i = 0; i < stacks.size(); i++)
  1423. {
  1424. const CStack *s = stacks[i];
  1425. if(creAnims.find(s->ID) == creAnims.end()) //e.g. for summoned but not yet handled stacks
  1426. continue;
  1427. if(creAnims[s->ID]->getType() != 5 && s->position >= 0) //don't show turrets here
  1428. stackAliveByHex[s->position].push_back(s);
  1429. }
  1430. std::vector<const CStack *> stackDeadByHex[BFIELD_SIZE];
  1431. for (int i = 0; i < stacks.size(); i++)
  1432. {
  1433. const CStack *s = stacks[i];
  1434. if(creAnims.find(s->ID) == creAnims.end()) //e.g. for summoned but not yet handled stacks
  1435. continue;
  1436. if(creAnims[s->ID]->getType() == 5)
  1437. stackDeadByHex[s->position].push_back(s);
  1438. }
  1439. //handle animations
  1440. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
  1441. {
  1442. if(!it->first) //this animation should be deleted
  1443. continue;
  1444. if(!it->second)
  1445. {
  1446. it->second = it->first->init();
  1447. }
  1448. if(it->second && it->first)
  1449. it->first->nextFrame();
  1450. }
  1451. //delete anims
  1452. int preSize = pendingAnims.size();
  1453. for(std::list<std::pair<CBattleAnimation *, bool> >::iterator it = pendingAnims.begin(); it != pendingAnims.end(); ++it)
  1454. {
  1455. if(it->first == NULL)
  1456. {
  1457. pendingAnims.erase(it);
  1458. it = pendingAnims.begin();
  1459. break;
  1460. }
  1461. }
  1462. if(preSize > 0 && pendingAnims.size() == 0)
  1463. {
  1464. //action finished, restore the interface
  1465. if(!active)
  1466. activate();
  1467. //activation of next stack
  1468. if(pendingAnims.size() == 0 && stackToActivate != NULL)
  1469. {
  1470. activateStack();
  1471. }
  1472. //anims ended
  1473. animsAreDisplayed.setn(false);
  1474. }
  1475. for(int b=0; b<BFIELD_SIZE; ++b) //showing dead stacks
  1476. {
  1477. for(size_t v=0; v<stackDeadByHex[b].size(); ++v)
  1478. {
  1479. creAnims[stackDeadByHex[b][v]->ID]->nextFrame(to, creAnims[stackDeadByHex[b][v]->ID]->pos.x, creAnims[stackDeadByHex[b][v]->ID]->pos.y, creDir[stackDeadByHex[b][v]->ID], animCount, false); //increment always when moving, never if stack died
  1480. }
  1481. }
  1482. std::vector<const CStack *> flyingStacks; //flying stacks should be displayed later, over other stacks and obstacles
  1483. if (!siegeH)
  1484. {
  1485. for(int b = 0; b < BFIELD_SIZE; ++b) //showing alive stacks
  1486. {
  1487. showAliveStacks(stackAliveByHex, b, &flyingStacks, to);
  1488. showObstacles(&hexToObstacle, obstacles, b, to);
  1489. showPieceOfWall(to, b, stacks);
  1490. }
  1491. }
  1492. // Siege drawing
  1493. else
  1494. {
  1495. for (int i = 0; i < 4; i++)
  1496. {
  1497. // xMin, xMax => go from hex x pos to hex x pos
  1498. // yMin, yMax => go from hex y pos to hex y pos
  1499. // xMove => 0: left side, 1: right side
  1500. // xMoveDir => 0: decrement, 1: increment, alters every second hex line either xMin or xMax depending on xMove
  1501. int xMin, xMax, yMin, yMax, xMove, xMoveDir = 0;
  1502. switch (i)
  1503. {
  1504. // display units shown at the upper left side
  1505. case 0:
  1506. xMin = 0;
  1507. yMin = 0;
  1508. xMax = 11;
  1509. yMax = 4;
  1510. xMove = 1;
  1511. break;
  1512. // display wall/units shown at the upper wall area/right upper side
  1513. case 1:
  1514. xMin = 12;
  1515. yMin = 0;
  1516. xMax = 16;
  1517. yMax = 4;
  1518. xMove = 0;
  1519. break;
  1520. // display units shown at the lower wall area/right lower side
  1521. case 2:
  1522. xMin = 10;
  1523. yMin = 5;
  1524. xMax = 16;
  1525. yMax = 10;
  1526. xMove = 0;
  1527. xMoveDir = 1;
  1528. break;
  1529. // display units shown at the left lower side
  1530. case 3:
  1531. xMin = 0;
  1532. yMin = 5;
  1533. xMax = 9;
  1534. yMax = 10;
  1535. xMove = 1;
  1536. xMoveDir = 1;
  1537. break;
  1538. }
  1539. int runNum = 0;
  1540. for (int j = yMin; j <= yMax; j++)
  1541. {
  1542. if (runNum > 0)
  1543. {
  1544. if (xMin == xMax)
  1545. xMax = xMin = ((runNum % 2) == 0) ? (xMin + (xMoveDir == 0 ? -1 : 1)) : xMin;
  1546. else if (xMove == 1)
  1547. xMax = ((runNum % 2) == 0) ? (xMax + (xMoveDir == 0 ? -1 : 1)) : xMax;
  1548. else if (xMove == 0)
  1549. xMin = ((runNum % 2) == 0) ? (xMin + (xMoveDir == 0 ? -1 : 1)) : xMin;
  1550. }
  1551. for (int k = xMin; k <= xMax; k++)
  1552. {
  1553. int hex = j * 17 + k;
  1554. showAliveStacks(stackAliveByHex, hex, &flyingStacks, to);
  1555. showObstacles(&hexToObstacle, obstacles, hex, to);
  1556. showPieceOfWall(to, hex, stacks);
  1557. }
  1558. ++runNum;
  1559. }
  1560. }
  1561. }
  1562. for(int b=0; b<flyingStacks.size(); ++b) //showing flying stacks
  1563. showAliveStack(flyingStacks[b], to);
  1564. //units shown
  1565. // Show projectiles
  1566. projectileShowHelper(to);
  1567. //showing spell effects
  1568. if(battleEffects.size())
  1569. {
  1570. for(std::list<SBattleEffect>::iterator it = battleEffects.begin(); it!=battleEffects.end(); ++it)
  1571. {
  1572. SDL_Surface * bitmapToBlit = it->anim->ourImages[(it->frame)%it->anim->ourImages.size()].bitmap;
  1573. SDL_Rect temp_rect = genRect(bitmapToBlit->h, bitmapToBlit->w, it->x, it->y);
  1574. SDL_BlitSurface(bitmapToBlit, NULL, to, &temp_rect);
  1575. }
  1576. }
  1577. SDL_SetClipRect(to, &buf); //restoring previous clip_rect
  1578. //showing menu background and console
  1579. blitAt(menu, pos.x, 556 + pos.y, to);
  1580. if(tacticsMode)
  1581. {
  1582. btactNext->showAll(to);
  1583. btactEnd->showAll(to);
  1584. }
  1585. else
  1586. {
  1587. console->showAll(to);
  1588. bConsoleUp->showAll(to);
  1589. bConsoleDown->showAll(to);
  1590. }
  1591. //showing buttons
  1592. bOptions->showAll(to);
  1593. bSurrender->showAll(to);
  1594. bFlee->showAll(to);
  1595. bAutofight->showAll(to);
  1596. bSpell->showAll(to);
  1597. bWait->showAll(to);
  1598. bDefence->showAll(to);
  1599. //showing window with result of battle
  1600. if(resWindow)
  1601. {
  1602. resWindow->show(to);
  1603. }
  1604. //showing in-game console
  1605. LOCPLINT->cingconsole->show(to);
  1606. Rect posWithQueue = Rect(pos.x, pos.y, 800, 600);
  1607. if(curInt->sysOpts.showQueue)
  1608. {
  1609. if(!queue->embedded)
  1610. {
  1611. posWithQueue.y -= queue->pos.h;
  1612. posWithQueue.h += queue->pos.h;
  1613. }
  1614. //showing queue
  1615. if(!bresult)
  1616. queue->showAll(to);
  1617. else
  1618. queue->blitBg(to); //blit only background, stacks are deleted
  1619. }
  1620. //printing border around interface
  1621. if(screen->w != 800 || screen->h !=600)
  1622. {
  1623. CMessage::drawBorder(curInt->playerID,to,posWithQueue.w + 28, posWithQueue.h + 28, posWithQueue.x-14, posWithQueue.y-15);
  1624. }
  1625. }
  1626. void CBattleInterface::showAliveStacks(std::vector<const CStack *> *aliveStacks, int hex, std::vector<const CStack *> *flyingStacks, SDL_Surface *to)
  1627. {
  1628. //showing hero animations
  1629. if (hex == 0)
  1630. if(attackingHero)
  1631. attackingHero->show(to);
  1632. if (hex == 16)
  1633. if(defendingHero)
  1634. defendingHero->show(to);
  1635. for(int v = 0; v < aliveStacks[hex].size(); ++v)
  1636. {
  1637. const CStack *s = aliveStacks[hex][v];
  1638. if(!s->hasBonusOfType(Bonus::FLYING) || creAnims[s->ID]->getType() != 0)
  1639. showAliveStack(s, to);
  1640. else
  1641. flyingStacks->push_back(s);
  1642. }
  1643. }
  1644. void CBattleInterface::showObstacles(std::multimap<THex, int> *hexToObstacle, std::vector<CObstacleInstance> &obstacles, int hex, SDL_Surface *to)
  1645. {
  1646. std::pair<std::multimap<THex, int>::const_iterator, std::multimap<THex, int>::const_iterator> obstRange =
  1647. hexToObstacle->equal_range(hex);
  1648. for(std::multimap<THex, int>::const_iterator it = obstRange.first; it != obstRange.second; ++it)
  1649. {
  1650. CObstacleInstance & curOb = obstacles[it->second];
  1651. std::pair<si16, si16> shift = CGI->heroh->obstacles.find(curOb.ID)->second.posShift;
  1652. int x = ((curOb.pos/BFIELD_WIDTH)%2==0 ? 22 : 0) + 44*(curOb.pos%BFIELD_WIDTH) + pos.x + shift.first;
  1653. int y = 86 + 42 * (curOb.pos/BFIELD_WIDTH) + pos.y + shift.second;
  1654. std::vector<Cimage> &images = idToObstacle[curOb.ID]->ourImages; //reference to animation of obstacle
  1655. blitAt(images[((animCount+1)/(4/curInt->sysOpts.animSpeed))%images.size()].bitmap, x, y, to);
  1656. }
  1657. }
  1658. void CBattleInterface::keyPressed(const SDL_KeyboardEvent & key)
  1659. {
  1660. if(key.keysym.sym == SDLK_q && key.state == SDL_PRESSED)
  1661. {
  1662. if(curInt->sysOpts.showQueue) //hide queue
  1663. hideQueue();
  1664. else
  1665. showQueue();
  1666. curInt->sysOpts.settingsChanged();
  1667. }
  1668. else if(key.keysym.sym == SDLK_ESCAPE && spellDestSelectMode)
  1669. {
  1670. endCastingSpell();
  1671. }
  1672. }
  1673. void CBattleInterface::mouseMoved(const SDL_MouseMotionEvent &sEvent)
  1674. {
  1675. if(activeStack!= NULL && !spellDestSelectMode)
  1676. {
  1677. mouseHoveredStack = -1;
  1678. int myNumber = -1; //number of hovered tile
  1679. for(int g = 0; g < BFIELD_SIZE; ++g)
  1680. {
  1681. if(bfield[g].hovered && bfield[g].strictHovered)
  1682. {
  1683. myNumber = g;
  1684. break;
  1685. }
  1686. }
  1687. if(myNumber == -1)
  1688. {
  1689. CCS->curh->changeGraphic(1, 6);
  1690. if(console->whoSetAlter == 0)
  1691. {
  1692. console->alterTxt = "";
  1693. }
  1694. }
  1695. else
  1696. {
  1697. if(std::find(occupyableHexes.begin(),occupyableHexes.end(),myNumber) == occupyableHexes.end())
  1698. {
  1699. const CStack *shere = curInt->cb->battleGetStackByPos(myNumber);
  1700. const CStack *sactive = activeStack;
  1701. if(shere)
  1702. {
  1703. if(shere->owner == curInt->playerID) //our stack
  1704. {
  1705. if(sactive->hasBonusOfType(Bonus::HEALER))
  1706. {
  1707. //display the possibility to heal this creature
  1708. CCS->curh->changeGraphic(1,17);
  1709. }
  1710. else
  1711. {
  1712. //info about creature
  1713. CCS->curh->changeGraphic(1,5);
  1714. }
  1715. //setting console text
  1716. char buf[500];
  1717. sprintf(buf, CGI->generaltexth->allTexts[297].c_str(), shere->count == 1 ? shere->getCreature()->nameSing.c_str() : shere->getCreature()->namePl.c_str());
  1718. console->alterTxt = buf;
  1719. console->whoSetAlter = 0;
  1720. mouseHoveredStack = shere->ID;
  1721. if(creAnims[shere->ID]->getType() == CCreatureAnim::HOLDING && creAnims[shere->ID]->framesInGroup(CCreatureAnim::MOUSEON) > 0)
  1722. {
  1723. creAnims[shere->ID]->playOnce(CCreatureAnim::MOUSEON);
  1724. }
  1725. }
  1726. else if(curInt->cb->battleCanShoot(activeStack,myNumber)) //we can shoot enemy
  1727. {
  1728. if(curInt->cb->battleHasDistancePenalty(activeStack, myNumber) ||
  1729. curInt->cb->battleHasWallPenalty(activeStack, myNumber))
  1730. {
  1731. CCS->curh->changeGraphic(1,15);
  1732. }
  1733. else
  1734. {
  1735. CCS->curh->changeGraphic(1,3);
  1736. }
  1737. //setting console text
  1738. char buf[500];
  1739. //calculating estimated dmg
  1740. std::pair<ui32, ui32> estimatedDmg = curInt->cb->battleEstimateDamage(sactive, shere);
  1741. std::ostringstream estDmg;
  1742. estDmg << estimatedDmg.first << " - " << estimatedDmg.second;
  1743. //printing
  1744. sprintf(buf, CGI->generaltexth->allTexts[296].c_str(), shere->count == 1 ? shere->getCreature()->nameSing.c_str() : shere->getCreature()->namePl.c_str(), sactive->shots, estDmg.str().c_str());
  1745. console->alterTxt = buf;
  1746. console->whoSetAlter = 0;
  1747. }
  1748. else if(isTileAttackable(myNumber)) //available enemy (melee attackable)
  1749. {
  1750. CCursorHandler *cursor = CCS->curh;
  1751. const CBattleHex &hoveredHex = bfield[myNumber];
  1752. const double subdividingAngle = 2.0*M_PI/6.0; // Divide a hex into six sectors.
  1753. const double hexMidX = hoveredHex.pos.x + hoveredHex.pos.w/2;
  1754. const double hexMidY = hoveredHex.pos.y + hoveredHex.pos.h/2;
  1755. const double cursorHexAngle = M_PI - atan2(hexMidY - cursor->ypos, cursor->xpos - hexMidX) + subdividingAngle/2;
  1756. const double sector = fmod(cursorHexAngle/subdividingAngle, 6.0);
  1757. const int zigzagCorrection = !((myNumber/BFIELD_WIDTH)%2); // Off-by-one correction needed to deal with the odd battlefield rows.
  1758. std::vector<int> sectorCursor; // From left to bottom left.
  1759. sectorCursor.push_back(8);
  1760. sectorCursor.push_back(9);
  1761. sectorCursor.push_back(10);
  1762. sectorCursor.push_back(11);
  1763. sectorCursor.push_back(12);
  1764. sectorCursor.push_back(7);
  1765. const bool doubleWide = activeStack->doubleWide();
  1766. bool aboveAttackable = true, belowAttackable = true;
  1767. // Exclude directions which cannot be attacked from.
  1768. // Check to the left.
  1769. if (myNumber%BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - 1))
  1770. {
  1771. sectorCursor[0] = -1;
  1772. }
  1773. // Check top left, top right as well as above for 2-hex creatures.
  1774. if (myNumber/BFIELD_WIDTH == 0)
  1775. {
  1776. sectorCursor[1] = -1;
  1777. sectorCursor[2] = -1;
  1778. aboveAttackable = false;
  1779. }
  1780. else
  1781. {
  1782. if (doubleWide)
  1783. {
  1784. bool attackRow[4] = {true, true, true, true};
  1785. if (myNumber%BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber - BFIELD_WIDTH - 2 + zigzagCorrection))
  1786. attackRow[0] = false;
  1787. if (!vstd::contains(occupyableHexes, myNumber - BFIELD_WIDTH - 1 + zigzagCorrection))
  1788. attackRow[1] = false;
  1789. if (!vstd::contains(occupyableHexes, myNumber - BFIELD_WIDTH + zigzagCorrection))
  1790. attackRow[2] = false;
  1791. if (myNumber%BFIELD_WIDTH >= BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber - BFIELD_WIDTH + 1 + zigzagCorrection))
  1792. attackRow[3] = false;
  1793. if (!(attackRow[0] && attackRow[1]))
  1794. sectorCursor[1] = -1;
  1795. if (!(attackRow[1] && attackRow[2]))
  1796. aboveAttackable = false;
  1797. if (!(attackRow[2] && attackRow[3]))
  1798. sectorCursor[2] = -1;
  1799. }
  1800. else
  1801. {
  1802. if (!vstd::contains(occupyableHexes, myNumber - BFIELD_WIDTH - 1 + zigzagCorrection))
  1803. sectorCursor[1] = -1;
  1804. if (!vstd::contains(occupyableHexes, myNumber - BFIELD_WIDTH + zigzagCorrection))
  1805. sectorCursor[2] = -1;
  1806. }
  1807. }
  1808. // Check to the right.
  1809. if (myNumber%BFIELD_WIDTH >= BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + 1))
  1810. {
  1811. sectorCursor[3] = -1;
  1812. }
  1813. // Check bottom right, bottom left as well as below for 2-hex creatures.
  1814. if (myNumber/BFIELD_WIDTH == BFIELD_HEIGHT - 1)
  1815. {
  1816. sectorCursor[4] = -1;
  1817. sectorCursor[5] = -1;
  1818. belowAttackable = false;
  1819. }
  1820. else
  1821. {
  1822. if (doubleWide)
  1823. {
  1824. bool attackRow[4] = {true, true, true, true};
  1825. if (myNumber%BFIELD_WIDTH <= 1 || !vstd::contains(occupyableHexes, myNumber + BFIELD_WIDTH - 2 + zigzagCorrection))
  1826. attackRow[0] = false;
  1827. if (!vstd::contains(occupyableHexes, myNumber + BFIELD_WIDTH - 1 + zigzagCorrection))
  1828. attackRow[1] = false;
  1829. if (!vstd::contains(occupyableHexes, myNumber + BFIELD_WIDTH + zigzagCorrection))
  1830. attackRow[2] = false;
  1831. if (myNumber%BFIELD_WIDTH >= BFIELD_WIDTH - 2 || !vstd::contains(occupyableHexes, myNumber + BFIELD_WIDTH + 1 + zigzagCorrection))
  1832. attackRow[3] = false;
  1833. if (!(attackRow[0] && attackRow[1]))
  1834. sectorCursor[5] = -1;
  1835. if (!(attackRow[1] && attackRow[2]))
  1836. belowAttackable = false;
  1837. if (!(attackRow[2] && attackRow[3]))
  1838. sectorCursor[4] = -1;
  1839. }
  1840. else
  1841. {
  1842. if (!vstd::contains(occupyableHexes, myNumber + BFIELD_WIDTH + zigzagCorrection))
  1843. sectorCursor[4] = -1;
  1844. if (!vstd::contains(occupyableHexes, myNumber + BFIELD_WIDTH - 1 + zigzagCorrection))
  1845. sectorCursor[5] = -1;
  1846. }
  1847. }
  1848. // Determine index from sector.
  1849. int cursorIndex;
  1850. if (doubleWide)
  1851. {
  1852. sectorCursor.insert(sectorCursor.begin() + 5, belowAttackable ? 13 : -1);
  1853. sectorCursor.insert(sectorCursor.begin() + 2, aboveAttackable ? 14 : -1);
  1854. if (sector < 1.5)
  1855. cursorIndex = sector;
  1856. else if (sector >= 1.5 && sector < 2.5)
  1857. cursorIndex = 2;
  1858. else if (sector >= 2.5 && sector < 4.5)
  1859. cursorIndex = (int) sector + 1;
  1860. else if (sector >= 4.5 && sector < 5.5)
  1861. cursorIndex = 6;
  1862. else
  1863. cursorIndex = (int) sector + 2;
  1864. }
  1865. else
  1866. {
  1867. cursorIndex = sector;
  1868. }
  1869. // Find the closest direction attackable, starting with the right one.
  1870. // FIXME: Is this really how the original H3 client does it?
  1871. int i = 0;
  1872. while (sectorCursor[(cursorIndex + i)%sectorCursor.size()] == -1)
  1873. i = i <= 0 ? 1 - i : -i; // 0, 1, -1, 2, -2, 3, -3 etc..
  1874. cursor->changeGraphic(1, sectorCursor[(cursorIndex + i)%sectorCursor.size()]);
  1875. //setting console info
  1876. char buf[500];
  1877. //calculating estimated dmg
  1878. std::pair<ui32, ui32> estimatedDmg = curInt->cb->battleEstimateDamage(sactive, shere);
  1879. std::ostringstream estDmg;
  1880. estDmg << estimatedDmg.first << " - " << estimatedDmg.second;
  1881. //printing
  1882. sprintf(buf, CGI->generaltexth->allTexts[36].c_str(), shere->count == 1 ? shere->getCreature()->nameSing.c_str() : shere->getCreature()->namePl.c_str(), estDmg.str().c_str());
  1883. console->alterTxt = buf;
  1884. console->whoSetAlter = 0;
  1885. }
  1886. else //unavailable enemy
  1887. {
  1888. CCS->curh->changeGraphic(1,0);
  1889. console->alterTxt = "";
  1890. console->whoSetAlter = 0;
  1891. }
  1892. }
  1893. else if( sactive && sactive->hasBonusOfType(Bonus::CATAPULT) && isCatapultAttackable(myNumber) ) //catapulting
  1894. {
  1895. CCS->curh->changeGraphic(1,16);
  1896. console->alterTxt = "";
  1897. console->whoSetAlter = 0;
  1898. }
  1899. else //empty unavailable tile
  1900. {
  1901. CCS->curh->changeGraphic(1,0);
  1902. console->alterTxt = "";
  1903. console->whoSetAlter = 0;
  1904. }
  1905. }
  1906. else //available tile
  1907. {
  1908. //setting console text and cursor
  1909. const CStack *sactive = activeStack;
  1910. if(sactive) //there can be a moment when stack is dead ut next is not yet activated
  1911. {
  1912. char buf[500];
  1913. if(sactive->hasBonusOfType(Bonus::FLYING))
  1914. {
  1915. CCS->curh->changeGraphic(1,2);
  1916. sprintf(buf, CGI->generaltexth->allTexts[295].c_str(), sactive->count == 1 ? sactive->getCreature()->nameSing.c_str() : sactive->getCreature()->namePl.c_str());
  1917. }
  1918. else
  1919. {
  1920. CCS->curh->changeGraphic(1,1);
  1921. sprintf(buf, CGI->generaltexth->allTexts[294].c_str(), sactive->count == 1 ? sactive->getCreature()->nameSing.c_str() : sactive->getCreature()->namePl.c_str());
  1922. }
  1923. console->alterTxt = buf;
  1924. console->whoSetAlter = 0;
  1925. }
  1926. }
  1927. }
  1928. }
  1929. else if(spellDestSelectMode)
  1930. {
  1931. int myNumber = -1; //number of hovered tile
  1932. for(int g=0; g<BFIELD_SIZE; ++g)
  1933. {
  1934. if(bfield[g].hovered && bfield[g].strictHovered)
  1935. {
  1936. myNumber = g;
  1937. break;
  1938. }
  1939. }
  1940. if(myNumber == -1)
  1941. {
  1942. CCS->curh->changeGraphic(1, 0);
  1943. //setting console text
  1944. console->alterTxt = CGI->generaltexth->allTexts[23];
  1945. console->whoSetAlter = 0;
  1946. }
  1947. else
  1948. {
  1949. //get dead stack if we cast resurrection or animate dead
  1950. const CStack * stackUnder = curInt->cb->battleGetStackByPos(myNumber, spellToCast->additionalInfo != 38 && spellToCast->additionalInfo != 39);
  1951. if(stackUnder && spellToCast->additionalInfo == 39 && !stackUnder->hasBonusOfType(Bonus::UNDEAD)) //animate dead can be cast only on undead creatures
  1952. stackUnder = NULL;
  1953. bool whichCase; //for cases 1, 2 and 3
  1954. switch(spellSelMode)
  1955. {
  1956. case 1:
  1957. whichCase = stackUnder && curInt->playerID == stackUnder->owner;
  1958. break;
  1959. case 2:
  1960. whichCase = stackUnder && curInt->playerID != stackUnder->owner;
  1961. break;
  1962. case 3:
  1963. whichCase = stackUnder;
  1964. break;
  1965. }
  1966. switch(spellSelMode)
  1967. {
  1968. case 0:
  1969. CCS->curh->changeGraphic(3, 0);
  1970. //setting console text
  1971. char buf[500];
  1972. sprintf(buf, CGI->generaltexth->allTexts[26].c_str(), CGI->spellh->spells[spellToCast->additionalInfo]->name.c_str());
  1973. console->alterTxt = buf;
  1974. console->whoSetAlter = 0;
  1975. break;
  1976. case 1: case 2: case 3:
  1977. if( whichCase )
  1978. {
  1979. CCS->curh->changeGraphic(3, 0);
  1980. //setting console text
  1981. char buf[500];
  1982. std::string creName = stackUnder->count > 1 ? stackUnder->getCreature()->namePl : stackUnder->getCreature()->nameSing;
  1983. sprintf(buf, CGI->generaltexth->allTexts[27].c_str(), CGI->spellh->spells[spellToCast->additionalInfo]->name.c_str(), creName.c_str());
  1984. console->alterTxt = buf;
  1985. console->whoSetAlter = 0;
  1986. break;
  1987. }
  1988. else
  1989. {
  1990. CCS->curh->changeGraphic(1, 0);
  1991. //setting console text
  1992. console->alterTxt = CGI->generaltexth->allTexts[23];
  1993. console->whoSetAlter = 0;
  1994. }
  1995. break;
  1996. case 4: //TODO: implement this case
  1997. if( blockedByObstacle(myNumber) )
  1998. {
  1999. CCS->curh->changeGraphic(3, 0);
  2000. }
  2001. else
  2002. {
  2003. CCS->curh->changeGraphic(1, 0);
  2004. }
  2005. break;
  2006. }
  2007. }
  2008. }
  2009. }
  2010. void CBattleInterface::clickRight(tribool down, bool previousState)
  2011. {
  2012. if(!down && spellDestSelectMode)
  2013. {
  2014. endCastingSpell();
  2015. }
  2016. }
  2017. void CBattleInterface::bOptionsf()
  2018. {
  2019. if(spellDestSelectMode) //we are casting a spell
  2020. return;
  2021. CCS->curh->changeGraphic(0,0);
  2022. SDL_Rect temp_rect = genRect(431, 481, 160, 84);
  2023. CBattleOptionsWindow * optionsWin = new CBattleOptionsWindow(temp_rect, this);
  2024. GH.pushInt(optionsWin);
  2025. }
  2026. void CBattleInterface::bSurrenderf()
  2027. {
  2028. if(spellDestSelectMode) //we are casting a spell
  2029. return;
  2030. int cost = curInt->cb->battleGetSurrenderCost();
  2031. if(cost >= 0)
  2032. {
  2033. const CGHeroInstance *opponent = curInt->cb->battleGetFightingHero(1);
  2034. std::string enemyHeroName = opponent ? opponent->name : "#ENEMY#"; //TODO: should surrendering without enemy hero be enabled?
  2035. 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."
  2036. curInt->showYesNoDialog(surrenderMessage, std::vector<SComponent*>(), boost::bind(&CBattleInterface::reallySurrender,this), 0, false);
  2037. }
  2038. }
  2039. void CBattleInterface::bFleef()
  2040. {
  2041. if(spellDestSelectMode) //we are casting a spell
  2042. return;
  2043. if( curInt->cb->battleCanFlee() )
  2044. {
  2045. CFunctionList<void()> ony = boost::bind(&CBattleInterface::reallyFlee,this);
  2046. curInt->showYesNoDialog(CGI->generaltexth->allTexts[28],std::vector<SComponent*>(), ony, 0, false); //Are you sure you want to retreat?
  2047. }
  2048. else
  2049. {
  2050. std::vector<SComponent*> comps;
  2051. std::string heroName;
  2052. //calculating fleeing hero's name
  2053. if(attackingHeroInstance)
  2054. if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor())
  2055. heroName = attackingHeroInstance->name;
  2056. if(defendingHeroInstance)
  2057. if(defendingHeroInstance->tempOwner == curInt->cb->getMyColor())
  2058. heroName = defendingHeroInstance->name;
  2059. //calculating text
  2060. char buffer[1000];
  2061. sprintf(buffer, CGI->generaltexth->allTexts[340].c_str(), heroName.c_str()); //The Shackles of War are present. %s can not retreat!
  2062. //printing message
  2063. curInt->showInfoDialog(std::string(buffer), comps);
  2064. }
  2065. }
  2066. void CBattleInterface::reallyFlee()
  2067. {
  2068. giveCommand(BattleAction::RETREAT,0,0);
  2069. CCS->curh->changeGraphic(0, 0);
  2070. }
  2071. void CBattleInterface::reallySurrender()
  2072. {
  2073. if(curInt->cb->getResourceAmount(Res::GOLD) < curInt->cb->battleGetSurrenderCost())
  2074. {
  2075. curInt->showInfoDialog(CGI->generaltexth->allTexts[29]); //You don't have enough gold!
  2076. }
  2077. else
  2078. {
  2079. giveCommand(BattleAction::SURRENDER,0,0);
  2080. CCS->curh->changeGraphic(0, 0);
  2081. }
  2082. }
  2083. void CBattleInterface::bAutofightf()
  2084. {
  2085. if(spellDestSelectMode) //we are casting a spell
  2086. return;
  2087. }
  2088. void CBattleInterface::bSpellf()
  2089. {
  2090. if(spellDestSelectMode) //we are casting a spell
  2091. return;
  2092. CCS->curh->changeGraphic(0,0);
  2093. const CGHeroInstance * chi = NULL;
  2094. if(attackingHeroInstance->tempOwner == curInt->playerID)
  2095. chi = attackingHeroInstance;
  2096. else
  2097. chi = defendingHeroInstance;
  2098. CSpellWindow * spellWindow = new CSpellWindow(genRect(595, 620, (conf.cc.resx - 620)/2, (conf.cc.resy - 595)/2), chi, curInt);
  2099. GH.pushInt(spellWindow);
  2100. }
  2101. void CBattleInterface::bWaitf()
  2102. {
  2103. if(spellDestSelectMode) //we are casting a spell
  2104. return;
  2105. if(activeStack != NULL)
  2106. giveCommand(8,0,activeStack->ID);
  2107. }
  2108. void CBattleInterface::bDefencef()
  2109. {
  2110. if(spellDestSelectMode) //we are casting a spell
  2111. return;
  2112. if(activeStack != NULL)
  2113. giveCommand(3,0,activeStack->ID);
  2114. }
  2115. void CBattleInterface::bConsoleUpf()
  2116. {
  2117. if(spellDestSelectMode) //we are casting a spell
  2118. return;
  2119. console->scrollUp();
  2120. }
  2121. void CBattleInterface::bConsoleDownf()
  2122. {
  2123. if(spellDestSelectMode) //we are casting a spell
  2124. return;
  2125. console->scrollDown();
  2126. }
  2127. void CBattleInterface::newStack(const CStack * stack)
  2128. {
  2129. Point coords = CBattleHex::getXYUnitAnim(stack->position, stack->owner == attackingHeroInstance->tempOwner, stack, this);;
  2130. if(stack->position < 0) //turret
  2131. {
  2132. const CCreature & turretCreature = *CGI->creh->creatures[ CGI->creh->factionToTurretCreature[siegeH->town->town->typeID] ];
  2133. creAnims[stack->ID] = new CCreatureAnimation(turretCreature.animDefName);
  2134. // Turret positions are read out of the /config/wall_pos.txt
  2135. int posID = 0;
  2136. switch (stack->position)
  2137. {
  2138. case -2: // keep creature
  2139. posID = 18;
  2140. break;
  2141. case -3: // bottom creature
  2142. posID = 19;
  2143. break;
  2144. case -4: // upper creature
  2145. posID = 20;
  2146. break;
  2147. }
  2148. if (posID != 0)
  2149. {
  2150. coords.x = graphics->wallPositions[siegeH->town->town->typeID][posID - 1].x + this->pos.x;
  2151. coords.y = graphics->wallPositions[siegeH->town->town->typeID][posID - 1].y + this->pos.y;
  2152. }
  2153. }
  2154. else
  2155. {
  2156. creAnims[stack->ID] = new CCreatureAnimation(stack->getCreature()->animDefName);
  2157. }
  2158. creAnims[stack->ID]->setType(CCreatureAnim::HOLDING);
  2159. creAnims[stack->ID]->pos = Rect(coords.x, coords.y, creAnims[stack->ID]->fullWidth, creAnims[stack->ID]->fullHeight);
  2160. creDir[stack->ID] = stack->attackerOwned;
  2161. }
  2162. void CBattleInterface::stackRemoved(int stackID)
  2163. {
  2164. delete creAnims[stackID];
  2165. creAnims.erase(stackID);
  2166. creDir.erase(stackID);
  2167. }
  2168. void CBattleInterface::stackActivated(const CStack * stack) //TODO: check it all before game state is changed due to abilities
  2169. {
  2170. //don't show animation when no HP is regenerated
  2171. if (stack->firstHPleft != stack->MaxHealth())
  2172. {
  2173. if( stack->hasBonusOfType(Bonus::HP_REGENERATION) || stack->hasBonusOfType(Bonus::FULL_HP_REGENERATION, 1))
  2174. {
  2175. displayEffect(74, stack->position);
  2176. CCS->soundh->playSound(soundBase::REGENER);
  2177. }
  2178. if( stack->hasBonusOfType(Bonus::FULL_HP_REGENERATION, 0))
  2179. {
  2180. displayEffect(74, stack->position);
  2181. CCS->soundh->playSound(soundBase::REGENER);
  2182. }
  2183. }
  2184. if(stack->hasBonusOfType(Bonus::MANA_DRAIN))
  2185. {
  2186. CGHeroInstance * enemy = NULL; //probably could be smarter and not duplicated
  2187. if (defendingHero)
  2188. if (defendingHero->myHero->tempOwner != stack->owner)
  2189. enemy = const_cast<CGHeroInstance *>(defendingHero->myHero);
  2190. if (attackingHero)
  2191. if (attackingHero->myHero->tempOwner != stack->owner)
  2192. enemy = const_cast<CGHeroInstance *>(attackingHero->myHero);
  2193. if (enemy)
  2194. {
  2195. ui32 manaDrained = stack->valOfBonuses(Bonus::MANA_DRAIN);
  2196. amin (manaDrained, enemy->mana);
  2197. if (manaDrained)
  2198. {
  2199. displayEffect(77, stack->position);
  2200. CCS->soundh->playSound(soundBase::MANADRAI);
  2201. }
  2202. }
  2203. }
  2204. if(stack->hasBonusOfType(Bonus::POISON))
  2205. {
  2206. displayEffect(67, stack->position);
  2207. CCS->soundh->playSound(soundBase::POISON);
  2208. }
  2209. //givenCommand = NULL;
  2210. stackToActivate = stack;
  2211. if(pendingAnims.size() == 0)
  2212. activateStack();
  2213. }
  2214. void CBattleInterface::stackMoved(const CStack * stack, std::vector<THex> destHex, int distance)
  2215. {
  2216. addNewAnim(new CBattleStackMoved(this, stack, destHex, distance));
  2217. waitForAnims();
  2218. }
  2219. void CBattleInterface::stacksAreAttacked(std::vector<SStackAttackedInfo> attackedInfos)
  2220. {
  2221. for(int h = 0; h < attackedInfos.size(); ++h)
  2222. {
  2223. addNewAnim(new CDefenceAnim(attackedInfos[h], this));
  2224. if (attackedInfos[h].rebirth)
  2225. {
  2226. displayEffect(50, attackedInfos[h].defender->position); //TODO: play reverse death animation
  2227. CCS->soundh->playSound(soundBase::RESURECT);
  2228. }
  2229. }
  2230. waitForAnims();
  2231. int targets = 0, killed = 0, damage = 0;
  2232. for(int h = 0; h < attackedInfos.size(); ++h)
  2233. {
  2234. ++targets;
  2235. killed += attackedInfos[h].killed;
  2236. damage += attackedInfos[h].dmg;
  2237. }
  2238. if (targets > 1)
  2239. printConsoleAttacked(attackedInfos.front().defender, damage, killed, attackedInfos.front().attacker, true); //creatures perish
  2240. else
  2241. printConsoleAttacked(attackedInfos.front().defender, damage, killed, attackedInfos.front().attacker, false);
  2242. for(int h = 0; h < attackedInfos.size(); ++h)
  2243. {
  2244. if (attackedInfos[h].rebirth)
  2245. creAnims[attackedInfos[h].defender->ID]->setType(CCreatureAnim::HOLDING);
  2246. }
  2247. }
  2248. void CBattleInterface::stackAttacking( const CStack * attacker, THex dest, const CStack * attacked, bool shooting )
  2249. {
  2250. if (shooting)
  2251. {
  2252. addNewAnim(new CShootingAnim(this, attacker, dest, attacked));
  2253. }
  2254. else
  2255. {
  2256. addNewAnim(new CMeleeAttack(this, attacker, dest, attacked));
  2257. }
  2258. waitForAnims();
  2259. }
  2260. void CBattleInterface::newRoundFirst( int round )
  2261. {
  2262. //handle regeneration
  2263. std::vector<const CStack*> stacks = curInt->cb->battleGetStacks(); //gets only alive stacks
  2264. // BOOST_FOREACH(const CStack *s, stacks)
  2265. // {
  2266. // }
  2267. waitForAnims();
  2268. }
  2269. void CBattleInterface::newRound(int number)
  2270. {
  2271. console->addText(CGI->generaltexth->allTexts[412]);
  2272. //unlock spellbook
  2273. //bSpell->block(!curInt->cb->battleCanCastSpell());
  2274. //don't unlock spellbook - this should be done when we have axctive creature
  2275. }
  2276. void CBattleInterface::giveCommand(ui8 action, THex tile, ui32 stack, si32 additional)
  2277. {
  2278. if(!curInt->cb->battleGetStackByID(stack) && action != 1 && action != 4 && action != 5)
  2279. {
  2280. return;
  2281. }
  2282. BattleAction * ba = new BattleAction(); //is deleted in CPlayerInterface::activeStack()
  2283. ba->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
  2284. ba->actionType = action;
  2285. ba->destinationTile = tile;
  2286. ba->stackNumber = stack;
  2287. ba->additionalInfo = additional;
  2288. //some basic validations
  2289. switch(action)
  2290. {
  2291. case 6:
  2292. assert(curInt->cb->battleGetStackByPos(additional)); //stack to attack must exist
  2293. case 2: case 7: case 9:
  2294. assert(tile < BFIELD_SIZE);
  2295. break;
  2296. }
  2297. if(!tacticsMode)
  2298. {
  2299. myTurn = false;
  2300. activeStack = NULL;
  2301. givenCommand->setn(ba);
  2302. }
  2303. else
  2304. {
  2305. curInt->cb->battleMakeTacticAction(ba);
  2306. delNull(ba);
  2307. bTacticNextStack();
  2308. }
  2309. }
  2310. bool CBattleInterface::isTileAttackable(const THex & number) const
  2311. {
  2312. for(size_t b=0; b<occupyableHexes.size(); ++b)
  2313. {
  2314. if(THex::mutualPosition(occupyableHexes[b], number) != -1 || occupyableHexes[b] == number)
  2315. return true;
  2316. }
  2317. return false;
  2318. }
  2319. bool CBattleInterface::blockedByObstacle(THex hex) const
  2320. {
  2321. std::vector<CObstacleInstance> obstacles = curInt->cb->battleGetAllObstacles();
  2322. std::set<THex> coveredHexes;
  2323. for(int b = 0; b < obstacles.size(); ++b)
  2324. {
  2325. std::vector<THex> blocked = CGI->heroh->obstacles.find(obstacles[b].ID)->second.getBlocked(obstacles[b].pos);
  2326. for(int w = 0; w < blocked.size(); ++w)
  2327. coveredHexes.insert(blocked[w]);
  2328. }
  2329. return vstd::contains(coveredHexes, hex);
  2330. }
  2331. bool CBattleInterface::isCatapultAttackable(THex hex) const
  2332. {
  2333. if(!siegeH)
  2334. return false;
  2335. int wallUnder = curInt->cb->battleGetWallUnderHex(hex);
  2336. if(wallUnder == -1)
  2337. return false;
  2338. return curInt->cb->battleGetWallState(wallUnder) < 3;
  2339. }
  2340. const CGHeroInstance * CBattleInterface::getActiveHero()
  2341. {
  2342. const CStack * attacker = activeStack;
  2343. if (!attacker)
  2344. {
  2345. return NULL;
  2346. }
  2347. if (attacker->attackerOwned)
  2348. {
  2349. return attackingHeroInstance;
  2350. }
  2351. return defendingHeroInstance;
  2352. }
  2353. void CBattleInterface::hexLclicked(int whichOne)
  2354. {
  2355. const CStack * actSt = activeStack;
  2356. const CStack* dest = curInt->cb->battleGetStackByPos(whichOne); //creature at destination tile; -1 if there is no one
  2357. if(!actSt)
  2358. {
  2359. tlog3 << "Hex l-clicked when no active stack!\n";
  2360. return;
  2361. }
  2362. if( ((whichOne%BFIELD_WIDTH)!=0 && (whichOne%BFIELD_WIDTH)!=(BFIELD_WIDTH-1)) //if player is trying to attack enemey unit or move creature stack
  2363. || (actSt->hasBonusOfType(Bonus::CATAPULT) && !spellDestSelectMode || dest ) //enemy's first aid tent can stand there and we want to shoot it
  2364. )
  2365. {
  2366. if(!myTurn)
  2367. return; //we are not permit to do anything
  2368. if(spellDestSelectMode)
  2369. {
  2370. //checking destination
  2371. bool allowCasting = true;
  2372. bool onlyAlive = spellToCast->additionalInfo != 38 && spellToCast->additionalInfo != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2373. switch(spellSelMode)
  2374. {
  2375. case 1:
  2376. if(!curInt->cb->battleGetStackByPos(whichOne, onlyAlive) || curInt->playerID != curInt->cb->battleGetStackByPos(whichOne, onlyAlive)->owner )
  2377. allowCasting = false;
  2378. break;
  2379. case 2:
  2380. if(!curInt->cb->battleGetStackByPos(whichOne, onlyAlive) || curInt->playerID == curInt->cb->battleGetStackByPos(whichOne, onlyAlive)->owner )
  2381. allowCasting = false;
  2382. break;
  2383. case 3:
  2384. if(!curInt->cb->battleGetStackByPos(whichOne, onlyAlive))
  2385. allowCasting = false;
  2386. break;
  2387. case 4:
  2388. if(!blockedByObstacle(whichOne))
  2389. allowCasting = false;
  2390. case 5: //teleport
  2391. const CSpell *s = CGI->spellh->spells[spellToCast->additionalInfo];
  2392. ui8 skill = getActiveHero()->getSpellSchoolLevel(s); //skill level
  2393. if (!curInt->cb->battleCanTeleportTo(activeStack, whichOne, skill))
  2394. {
  2395. allowCasting = false;
  2396. }
  2397. break;
  2398. }
  2399. //destination checked
  2400. if(allowCasting)
  2401. {
  2402. spellToCast->destinationTile = whichOne;
  2403. curInt->cb->battleMakeAction(spellToCast);
  2404. endCastingSpell();
  2405. }
  2406. }
  2407. else //we don't cast any spell
  2408. {
  2409. if(!dest || !dest->alive()) //no creature at that tile
  2410. {
  2411. if(std::find(occupyableHexes.begin(),occupyableHexes.end(),whichOne)!=occupyableHexes.end())// and it's in our range
  2412. {
  2413. CCS->curh->changeGraphic(1, 6); //cursor should be changed
  2414. if(activeStack->doubleWide())
  2415. {
  2416. std::vector<THex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2417. int shiftedDest = whichOne + (activeStack->attackerOwned ? 1 : -1);
  2418. if(vstd::contains(acc, whichOne))
  2419. giveCommand(2,whichOne,activeStack->ID);
  2420. else if(vstd::contains(acc, shiftedDest))
  2421. giveCommand(2,shiftedDest,activeStack->ID);
  2422. }
  2423. else
  2424. {
  2425. giveCommand(2,whichOne,activeStack->ID);
  2426. }
  2427. }
  2428. else if(actSt->hasBonusOfType(Bonus::CATAPULT) && isCatapultAttackable(whichOne)) //attacking (catapult)
  2429. {
  2430. giveCommand(9,whichOne,activeStack->ID);
  2431. }
  2432. }
  2433. else if(dest->owner != actSt->owner
  2434. && curInt->cb->battleCanShoot(activeStack, whichOne) ) //shooting
  2435. {
  2436. CCS->curh->changeGraphic(1, 6); //cursor should be changed
  2437. giveCommand(7,whichOne,activeStack->ID);
  2438. }
  2439. else if(dest->owner != actSt->owner) //attacking
  2440. {
  2441. const CStack * actStack = activeStack;
  2442. int attackFromHex = -1; //hex from which we will attack chosen stack
  2443. switch(CCS->curh->number)
  2444. {
  2445. case 12: //from bottom right
  2446. {
  2447. bool doubleWide = actStack->doubleWide();
  2448. int destHex = whichOne + ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH : BFIELD_WIDTH+1 ) +
  2449. (actStack->attackerOwned && doubleWide ? 1 : 0);
  2450. if(vstd::contains(occupyableHexes, destHex))
  2451. attackFromHex = destHex;
  2452. else if(actStack->attackerOwned) //if we are attacker
  2453. {
  2454. if(vstd::contains(occupyableHexes, destHex+1))
  2455. attackFromHex = destHex+1;
  2456. }
  2457. else //if we are defender
  2458. {
  2459. if(vstd::contains(occupyableHexes, destHex-1))
  2460. attackFromHex = destHex-1;
  2461. }
  2462. break;
  2463. }
  2464. case 7: //from bottom left
  2465. {
  2466. int destHex = whichOne + ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH-1 : BFIELD_WIDTH );
  2467. if(vstd::contains(occupyableHexes, destHex))
  2468. attackFromHex = destHex;
  2469. else if(actStack->attackerOwned) //if we are attacker
  2470. {
  2471. if(vstd::contains(occupyableHexes, destHex+1))
  2472. attackFromHex = destHex+1;
  2473. }
  2474. else //if we are defender
  2475. {
  2476. if(vstd::contains(occupyableHexes, destHex-1))
  2477. attackFromHex = destHex-1;
  2478. }
  2479. break;
  2480. }
  2481. case 8: //from left
  2482. {
  2483. if(actStack->doubleWide() && !actStack->attackerOwned)
  2484. {
  2485. std::vector<THex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2486. if(vstd::contains(acc, whichOne))
  2487. attackFromHex = whichOne - 1;
  2488. else
  2489. attackFromHex = whichOne - 2;
  2490. }
  2491. else
  2492. {
  2493. attackFromHex = whichOne - 1;
  2494. }
  2495. break;
  2496. }
  2497. case 9: //from top left
  2498. {
  2499. int destHex = whichOne - ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH+1 : BFIELD_WIDTH );
  2500. if(vstd::contains(occupyableHexes, destHex))
  2501. attackFromHex = destHex;
  2502. else if(actStack->attackerOwned) //if we are attacker
  2503. {
  2504. if(vstd::contains(occupyableHexes, destHex+1))
  2505. attackFromHex = destHex+1;
  2506. }
  2507. else //if we are defender
  2508. {
  2509. if(vstd::contains(occupyableHexes, destHex-1))
  2510. attackFromHex = destHex-1;
  2511. }
  2512. break;
  2513. }
  2514. case 10: //from top right
  2515. {
  2516. bool doubleWide = actStack->doubleWide();
  2517. int destHex = whichOne - ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH : BFIELD_WIDTH-1 ) +
  2518. (actStack->attackerOwned && doubleWide ? 1 : 0);
  2519. if(vstd::contains(occupyableHexes, destHex))
  2520. attackFromHex = destHex;
  2521. else if(actStack->attackerOwned) //if we are attacker
  2522. {
  2523. if(vstd::contains(occupyableHexes, destHex+1))
  2524. attackFromHex = destHex+1;
  2525. }
  2526. else //if we are defender
  2527. {
  2528. if(vstd::contains(occupyableHexes, destHex-1))
  2529. attackFromHex = destHex-1;
  2530. }
  2531. break;
  2532. }
  2533. case 11: //from right
  2534. {
  2535. if(actStack->doubleWide() && actStack->attackerOwned)
  2536. {
  2537. std::vector<THex> acc = curInt->cb->battleGetAvailableHexes(activeStack, false);
  2538. if(vstd::contains(acc, whichOne))
  2539. attackFromHex = whichOne + 1;
  2540. else
  2541. attackFromHex = whichOne + 2;
  2542. }
  2543. else
  2544. {
  2545. attackFromHex = whichOne + 1;
  2546. }
  2547. break;
  2548. }
  2549. case 13: //from bottom
  2550. {
  2551. int destHex = whichOne + ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH : BFIELD_WIDTH+1 );
  2552. if(vstd::contains(occupyableHexes, destHex))
  2553. attackFromHex = destHex;
  2554. else if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor()) //if we are attacker
  2555. {
  2556. if(vstd::contains(occupyableHexes, destHex+1))
  2557. attackFromHex = destHex+1;
  2558. }
  2559. else //if we are defender
  2560. {
  2561. if(vstd::contains(occupyableHexes, destHex-1))
  2562. attackFromHex = destHex-1;
  2563. }
  2564. break;
  2565. }
  2566. case 14: //from top
  2567. {
  2568. int destHex = whichOne - ( (whichOne/BFIELD_WIDTH)%2 ? BFIELD_WIDTH : BFIELD_WIDTH-1 );
  2569. if(vstd::contains(occupyableHexes, destHex))
  2570. attackFromHex = destHex;
  2571. else if(attackingHeroInstance->tempOwner == curInt->cb->getMyColor()) //if we are attacker
  2572. {
  2573. if(vstd::contains(occupyableHexes, destHex+1))
  2574. attackFromHex = destHex+1;
  2575. }
  2576. else //if we are defender
  2577. {
  2578. if(vstd::contains(occupyableHexes, destHex-1))
  2579. attackFromHex = destHex-1;
  2580. }
  2581. break;
  2582. }
  2583. }
  2584. if(attackFromHex >= 0) //we can be in this line when unreachable creature is L - clicked (as of revision 1308)
  2585. {
  2586. giveCommand(6, attackFromHex, activeStack->ID, whichOne);
  2587. CCS->curh->changeGraphic(1, 6); //cursor should be changed
  2588. }
  2589. }
  2590. else if (actSt->hasBonusOfType(Bonus::HEALER) && actSt->owner == dest->owner) //friendly creature we can heal
  2591. {
  2592. giveCommand(12, whichOne, activeStack->ID); //command healing
  2593. CCS->curh->changeGraphic(1, 6); //cursor should be changed
  2594. }
  2595. }
  2596. }
  2597. }
  2598. void CBattleInterface::stackIsCatapulting(const CatapultAttack & ca)
  2599. {
  2600. for(std::set< std::pair< std::pair< ui8, si16 >, ui8> >::const_iterator it = ca.attackedParts.begin(); it != ca.attackedParts.end(); ++it)
  2601. {
  2602. const CStack * stack = curInt->cb->battleGetStackByID(ca.attacker);
  2603. addNewAnim(new CShootingAnim(this, stack, it->first.second, NULL, true, it->second));
  2604. SDL_FreeSurface(siegeH->walls[it->first.first + 2]);
  2605. siegeH->walls[it->first.first + 2] = BitmapHandler::loadBitmap(
  2606. siegeH->getSiegeName(it->first.first + 2, curInt->cb->battleGetWallState(it->first.first)) );
  2607. }
  2608. waitForAnims();
  2609. }
  2610. void CBattleInterface::battleFinished(const BattleResult& br)
  2611. {
  2612. bresult = &br;
  2613. LOCPLINT->pim->unlock();
  2614. animsAreDisplayed.waitUntil(false);
  2615. LOCPLINT->pim->lock();
  2616. displayBattleFinished();
  2617. }
  2618. void CBattleInterface::displayBattleFinished()
  2619. {
  2620. CCS->curh->changeGraphic(0,0);
  2621. SDL_Rect temp_rect = genRect(561, 470, (screen->w - 800)/2 + 165, (screen->h - 600)/2 + 19);
  2622. CCS->musich->stopMusic();
  2623. resWindow = new CBattleResultWindow(*bresult, temp_rect, this);
  2624. GH.pushInt(resWindow);
  2625. }
  2626. void CBattleInterface::spellCast( const BattleSpellCast * sc )
  2627. {
  2628. const CSpell &spell = *CGI->spellh->spells[sc->id];
  2629. //spell opening battle is cast when no stack is active
  2630. if(sc->castedByHero && ( activeStack == NULL || sc->side == !activeStack->attackerOwned) )
  2631. bSpell->block(true);
  2632. std::vector< std::string > anims; //for magic arrow and ice bolt
  2633. if (vstd::contains(CCS->soundh->spellSounds, &spell))
  2634. CCS->soundh->playSound(CCS->soundh->spellSounds[&spell]);
  2635. switch(sc->id)
  2636. {
  2637. case 15: //magic arrow
  2638. {
  2639. //initialization of anims
  2640. 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");
  2641. }
  2642. case 16: //ice bolt
  2643. {
  2644. if(anims.size() == 0) //initialization of anims
  2645. {
  2646. 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");
  2647. }
  2648. } //end of ice bolt only part
  2649. { //common ice bolt and magic arrow part
  2650. //initial variables
  2651. std::string animToDisplay;
  2652. Point srccoord = (sc->side ? Point(770, 60) : Point(30, 60)) + pos;
  2653. Point destcoord = CBattleHex::getXYUnitAnim(sc->tile, !sc->side, curInt->cb->battleGetStackByPos(sc->tile), this); //position attacked by arrow
  2654. destcoord.x += 250; destcoord.y += 240;
  2655. //animation angle
  2656. float angle = atan2(float(destcoord.x - srccoord.x), float(destcoord.y - srccoord.y));
  2657. bool Vflip = false;
  2658. if (angle < 0)
  2659. {
  2660. Vflip = true;
  2661. angle = -angle;
  2662. }
  2663. //choosing animation by angle
  2664. if(angle > 1.50)
  2665. animToDisplay = anims[0];
  2666. else if(angle > 1.20)
  2667. animToDisplay = anims[1];
  2668. else if(angle > 0.90)
  2669. animToDisplay = anims[2];
  2670. else if(angle > 0.60)
  2671. animToDisplay = anims[3];
  2672. else
  2673. animToDisplay = anims[4];
  2674. //displaying animation
  2675. CDefEssential * animDef = CDefHandler::giveDefEss(animToDisplay);
  2676. int steps = sqrt((float)((destcoord.x - srccoord.x)*(destcoord.x - srccoord.x) + (destcoord.y - srccoord.y) * (destcoord.y - srccoord.y))) / 40;
  2677. if(steps <= 0)
  2678. steps = 1;
  2679. int dx = (destcoord.x - srccoord.x - animDef->ourImages[0].bitmap->w)/steps, dy = (destcoord.y - srccoord.y - animDef->ourImages[0].bitmap->h)/steps;
  2680. delete animDef;
  2681. addNewAnim(new CSpellEffectAnim(this, animToDisplay, srccoord.x, srccoord.y, dx, dy, Vflip));
  2682. break; //for 15 and 16 cases
  2683. }
  2684. case 17: //lightning bolt
  2685. case 57: //Titan's Thunder
  2686. case 77: //thunderbolt
  2687. displayEffect(1, sc->tile);
  2688. displayEffect(spell.mainEffectAnim, sc->tile);
  2689. break;
  2690. case 35: //dispel
  2691. case 37: //cure
  2692. case 38: //resurrection
  2693. case 39: //animate dead
  2694. for(std::set<ui32>::const_iterator it = sc->affectedCres.begin(); it != sc->affectedCres.end(); ++it)
  2695. {
  2696. displayEffect(spell.mainEffectAnim, curInt->cb->battleGetStackByID(*it, false)->position);
  2697. }
  2698. break;
  2699. case 66: case 67: case 68: case 69: //summon elemental
  2700. addNewAnim(new CDummyAnim(this, 2));
  2701. break;
  2702. } //switch(sc->id)
  2703. //support for resistance
  2704. for(int j=0; j<sc->resisted.size(); ++j)
  2705. {
  2706. int tile = curInt->cb->battleGetStackByID(sc->resisted[j])->position;
  2707. displayEffect(78, tile);
  2708. }
  2709. //displaying message in console
  2710. bool customSpell = false;
  2711. bool plural = false; //add singular / plural form of creature text if this is true
  2712. int textID = 0;
  2713. if(sc->affectedCres.size() == 1)
  2714. {
  2715. std::string text = CGI->generaltexth->allTexts[195];
  2716. if(sc->castedByHero)
  2717. {
  2718. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetFightingHero(sc->side)->name);
  2719. boost::algorithm::replace_first(text, "%s", CGI->spellh->spells[sc->id]->name); //spell name
  2720. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin(), false)->getCreature()->namePl ); //target
  2721. }
  2722. else
  2723. {
  2724. switch(sc->id)
  2725. {
  2726. case 70: //Stone Gaze
  2727. customSpell = true;
  2728. plural = true;
  2729. textID = 558;
  2730. break;
  2731. case 71: //Poison
  2732. customSpell = true;
  2733. plural = true;
  2734. textID = 561;
  2735. break;
  2736. case 72: //Bind
  2737. customSpell = true;
  2738. text = CGI->generaltexth->allTexts[560];
  2739. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin(), false)->getCreature()->namePl );
  2740. break; //Roots and vines bind the %s to the ground!
  2741. case 73: //Disease
  2742. customSpell = true;
  2743. plural = true;
  2744. textID = 553;
  2745. break;
  2746. case 74: //Paralyze
  2747. customSpell = true;
  2748. plural = true;
  2749. textID = 563;
  2750. break;
  2751. case 75: // Aging
  2752. {
  2753. customSpell = true;
  2754. if (curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->count > 1)
  2755. {
  2756. text = CGI->generaltexth->allTexts[552];
  2757. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->namePl);
  2758. }
  2759. else
  2760. {
  2761. text = CGI->generaltexth->allTexts[551];
  2762. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->nameSing);
  2763. }
  2764. //The %s shrivel with age, and lose %d hit points."
  2765. boost::shared_ptr<BonusList> bl = curInt->cb->battleGetStackByID(*sc->affectedCres.begin(), false)->getBonuses(Selector::type(Bonus::STACK_HEALTH));
  2766. bl->remove_if(Selector::source(Bonus::SPELL_EFFECT, 75));
  2767. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(bl->totalValue()/2));
  2768. }
  2769. break;
  2770. case 77: //Thunderbolt
  2771. text = CGI->generaltexth->allTexts[367];
  2772. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->namePl);
  2773. console->addText(text);
  2774. text = CGI->generaltexth->allTexts[343].substr(1, CGI->generaltexth->allTexts[343].size() - 1); //Does %d points of damage.
  2775. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(sc->dmgToDisplay)); //no more text afterwards
  2776. console->addText(text);
  2777. customSpell = true;
  2778. text = ""; //yeah, it's a terrible mess
  2779. break;
  2780. case 78: //Dispell helpful spells
  2781. text = CGI->generaltexth->allTexts[555];
  2782. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->namePl);
  2783. customSpell = true;
  2784. break;
  2785. case 79: // Death Stare
  2786. customSpell = true;
  2787. if (sc->dmgToDisplay)
  2788. {
  2789. if (sc->dmgToDisplay > 1)
  2790. {
  2791. text = CGI->generaltexth->allTexts[119]; //%d %s die under the terrible gaze of the %s.
  2792. boost::algorithm::replace_first(text, "%d", boost::lexical_cast<std::string>(sc->dmgToDisplay));
  2793. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin(), false)->getCreature()->namePl );
  2794. }
  2795. else
  2796. {
  2797. text = CGI->generaltexth->allTexts[118]; //One %s dies under the terrible gaze of the %s.
  2798. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->nameSing);
  2799. }
  2800. boost::algorithm::replace_first(text, "%s", CGI->creh->creatures[sc->attackerType]->namePl); //casting stack
  2801. }
  2802. else
  2803. text = "";
  2804. break;
  2805. default:
  2806. text = CGI->generaltexth->allTexts[565]; //The %s casts %s
  2807. boost::algorithm::replace_first(text, "%s", CGI->creh->creatures[sc->attackerType]->namePl); //casting stack
  2808. }
  2809. if (plural)
  2810. {
  2811. if (curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->count > 1)
  2812. {
  2813. text = CGI->generaltexth->allTexts[textID + 1];
  2814. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->namePl);
  2815. }
  2816. else
  2817. {
  2818. text = CGI->generaltexth->allTexts[textID];
  2819. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetStackByID(*sc->affectedCres.begin())->type->nameSing);
  2820. }
  2821. }
  2822. }
  2823. if (!customSpell && !sc->dmgToDisplay)
  2824. boost::algorithm::replace_first(text, "%s", CGI->spellh->spells[sc->id]->name); //simple spell name
  2825. if (text.size())
  2826. console->addText(text);
  2827. }
  2828. else
  2829. {
  2830. std::string text = CGI->generaltexth->allTexts[196];
  2831. if(sc->castedByHero)
  2832. {
  2833. boost::algorithm::replace_first(text, "%s", curInt->cb->battleGetFightingHero(sc->side)->name);
  2834. }
  2835. else if(sc->attackerType < CGI->creh->creatures.size())
  2836. {
  2837. boost::algorithm::replace_first(text, "%s", CGI->creh->creatures[sc->attackerType]->namePl); //creature caster
  2838. }
  2839. else
  2840. {
  2841. //TODO artifacts that cast spell; scripts some day
  2842. boost::algorithm::replace_first(text, "Something", CGI->creh->creatures[sc->attackerType]->namePl); //creature caster
  2843. }
  2844. boost::algorithm::replace_first(text, "%s", CGI->spellh->spells[sc->id]->name);
  2845. console->addText(text);
  2846. }
  2847. if(sc->dmgToDisplay && !customSpell)
  2848. {
  2849. std::string dmgInfo = CGI->generaltexth->allTexts[376];
  2850. boost::algorithm::replace_first(dmgInfo, "%s", CGI->spellh->spells[sc->id]->name); //simple spell name
  2851. boost::algorithm::replace_first(dmgInfo, "%d", boost::lexical_cast<std::string>(sc->dmgToDisplay));
  2852. console->addText(dmgInfo); //todo: casualties (?)
  2853. }
  2854. waitForAnims();
  2855. }
  2856. void CBattleInterface::battleStacksEffectsSet(const SetStackEffect & sse)
  2857. {
  2858. int effID = sse.effect.back().sid;
  2859. if(effID != -1) //can be -1 for defensive stance effect
  2860. {
  2861. for(std::vector<ui32>::const_iterator ci = sse.stacks.begin(); ci!=sse.stacks.end(); ++ci)
  2862. {
  2863. displayEffect(CGI->spellh->spells[effID]->mainEffectAnim, curInt->cb->battleGetStackByID(*ci)->position);
  2864. }
  2865. }
  2866. else if (sse.stacks.size() == 1 && sse.effect.size() == 2)
  2867. {
  2868. const Bonus & bns = sse.effect.front();
  2869. if (bns.source == Bonus::OTHER && bns.type == Bonus::PRIMARY_SKILL)
  2870. {
  2871. //defensive stance
  2872. const CStack * stack = LOCPLINT->cb->battleGetStackByID(*sse.stacks.begin());
  2873. int txtid = 120;
  2874. if(stack->count != 1)
  2875. txtid++; //move to plural text
  2876. char txt[4000];
  2877. BonusList defenseBonuses = *(stack->getBonuses(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE)));
  2878. defenseBonuses.remove_if(Selector::durationType(Bonus::STACK_GETS_TURN)); //remove bonuses gained from defensive stance
  2879. int val = stack->Defense() - defenseBonuses.totalValue();
  2880. sprintf(txt, CGI->generaltexth->allTexts[txtid].c_str(), (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str(), val);
  2881. console->addText(txt);
  2882. }
  2883. }
  2884. if (activeStack != NULL) //it can be -1 when a creature casts effect
  2885. {
  2886. redrawBackgroundWithHexes(activeStack);
  2887. }
  2888. }
  2889. void CBattleInterface::castThisSpell(int spellID)
  2890. {
  2891. BattleAction * ba = new BattleAction;
  2892. ba->actionType = BattleAction::HERO_SPELL;
  2893. ba->additionalInfo = spellID; //spell number
  2894. ba->destinationTile = -1;
  2895. ba->stackNumber = (attackingHeroInstance->tempOwner == curInt->playerID) ? -1 : -2;
  2896. ba->side = defendingHeroInstance ? (curInt->playerID == defendingHeroInstance->tempOwner) : false;
  2897. spellToCast = ba;
  2898. spellDestSelectMode = true;
  2899. //choosing possible tragets
  2900. const CGHeroInstance * castingHero = (attackingHeroInstance->tempOwner == curInt->playerID) ? attackingHeroInstance : defendingHeroInstance;
  2901. const CSpell & spell = *CGI->spellh->spells[spellID];
  2902. spellSelMode = 0;
  2903. if(spell.getTargetType() == CSpell::CREATURE)
  2904. {
  2905. switch(spell.positiveness)
  2906. {
  2907. case -1 :
  2908. spellSelMode = 2;
  2909. break;
  2910. case 0:
  2911. spellSelMode = 3;
  2912. break;
  2913. case 1:
  2914. spellSelMode = 1;
  2915. break;
  2916. }
  2917. }
  2918. if(spell.getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  2919. {
  2920. if(castingHero && castingHero->getSpellSchoolLevel(&spell) < 3)
  2921. {
  2922. switch(spell.positiveness)
  2923. {
  2924. case -1 :
  2925. spellSelMode = 2;
  2926. break;
  2927. case 0:
  2928. spellSelMode = 3;
  2929. break;
  2930. case 1:
  2931. spellSelMode = 1;
  2932. break;
  2933. }
  2934. }
  2935. else
  2936. {
  2937. spellSelMode = -1;
  2938. }
  2939. }
  2940. if(spell.getTargetType() == CSpell::OBSTACLE)
  2941. {
  2942. spellSelMode = 4;
  2943. }
  2944. if(spell.range[ castingHero->getSpellSchoolLevel(&spell) ] == "X") //spell has no range
  2945. {
  2946. spellSelMode = -1;
  2947. }
  2948. if(spell.id == 63) //teleport
  2949. {
  2950. spellSelMode = 5;
  2951. }
  2952. if(spell.range[ castingHero->getSpellSchoolLevel(&spell) ].size() > 1) //spell has many-hex range
  2953. {
  2954. spellSelMode = 0;
  2955. }
  2956. if(spellSelMode == -1) //user does not have to select location
  2957. {
  2958. spellToCast->destinationTile = -1;
  2959. curInt->cb->battleMakeAction(spellToCast);
  2960. endCastingSpell();
  2961. }
  2962. else
  2963. {
  2964. CCS->curh->changeGraphic(3, 0);
  2965. }
  2966. }
  2967. void CBattleInterface::displayEffect(ui32 effect, int destTile)
  2968. {
  2969. addNewAnim(new CSpellEffectAnim(this, effect, destTile));
  2970. }
  2971. void CBattleInterface::setAnimSpeed(int set)
  2972. {
  2973. curInt->sysOpts.animSpeed = set;
  2974. curInt->sysOpts.settingsChanged();
  2975. }
  2976. int CBattleInterface::getAnimSpeed() const
  2977. {
  2978. return curInt->sysOpts.animSpeed;
  2979. }
  2980. void CBattleInterface::activateStack()
  2981. {
  2982. activeStack = stackToActivate;
  2983. stackToActivate = NULL;
  2984. const CStack *s = activeStack;
  2985. myTurn = true;
  2986. if(attackerInt && defenderInt) //hotseat -> need to pick which interface "takes over" as active
  2987. curInt = attackerInt->playerID == s->owner ? attackerInt : defenderInt;
  2988. queue->update();
  2989. redrawBackgroundWithHexes(activeStack);
  2990. bWait->block(vstd::contains(s->state, WAITING)); //block waiting button if stack has been already waiting
  2991. //block cast spell button if hero doesn't have a spellbook
  2992. bSpell->block(!curInt->cb->battleCanCastSpell());
  2993. bSurrender->block((curInt == attackerInt ? defendingHeroInstance : attackingHeroInstance) == NULL);
  2994. bFlee->block(!curInt->cb->battleCanFlee());
  2995. bSurrender->block(curInt->cb->battleGetSurrenderCost() < 0);
  2996. GH.fakeMouseMove();
  2997. if(!pendingAnims.size() && !active)
  2998. activate();
  2999. }
  3000. float CBattleInterface::getAnimSpeedMultiplier() const
  3001. {
  3002. switch(curInt->sysOpts.animSpeed)
  3003. {
  3004. case 1:
  3005. return 3.5f;
  3006. case 2:
  3007. return 2.2f;
  3008. case 4:
  3009. return 1.0f;
  3010. default:
  3011. return 0.0f;
  3012. }
  3013. }
  3014. void CBattleInterface::endCastingSpell()
  3015. {
  3016. assert(spellDestSelectMode);
  3017. delete spellToCast;
  3018. spellToCast = NULL;
  3019. spellDestSelectMode = false;
  3020. CCS->curh->changeGraphic(1, 6);
  3021. }
  3022. void CBattleInterface::showAliveStack(const CStack *stack, SDL_Surface * to)
  3023. {
  3024. int ID = stack->ID;
  3025. if(creAnims.find(ID) == creAnims.end()) //eg. for summoned but not yet handled stacks
  3026. return;
  3027. const CCreature *creature = stack->getCreature();
  3028. SDL_Rect unitRect = {creAnims[ID]->pos.x, creAnims[ID]->pos.y, creAnims[ID]->fullWidth, creAnims[ID]->fullHeight};
  3029. int animType = creAnims[ID]->getType();
  3030. int affectingSpeed = curInt->sysOpts.animSpeed;
  3031. if(animType == 1 || animType == 2) //standing stacks should not stand faster :)
  3032. affectingSpeed = 2;
  3033. bool incrementFrame = (animCount%(4/affectingSpeed)==0) && animType!=5 && animType!=20 && animType!=2;
  3034. if (creature->idNumber == 149)
  3035. {
  3036. // a turret creature has a limited height, so cut it at a certain position; turret creature has no standing anim
  3037. unitRect.h = graphics->wallPositions[siegeH->town->town->typeID][20].y;
  3038. }
  3039. else
  3040. {
  3041. // standing animation
  3042. if(animType == 2)
  3043. {
  3044. if(standingFrame.find(ID)!=standingFrame.end())
  3045. {
  3046. incrementFrame = (animCount%(8/affectingSpeed)==0);
  3047. if(incrementFrame)
  3048. {
  3049. ++standingFrame[ID];
  3050. if(standingFrame[ID] == creAnims[ID]->framesInGroup(CCreatureAnim::HOLDING))
  3051. {
  3052. standingFrame.erase(standingFrame.find(ID));
  3053. }
  3054. }
  3055. }
  3056. else
  3057. {
  3058. if((rand()%50) == 0)
  3059. {
  3060. standingFrame.insert(std::make_pair(ID, 0));
  3061. }
  3062. }
  3063. }
  3064. }
  3065. // As long as the projectile of the shooter-stack is flying incrementFrame should be false
  3066. bool shootingFinished = true;
  3067. for (std::list<SProjectileInfo>::iterator it = projectiles.begin(); it != projectiles.end(); ++it)
  3068. {
  3069. if (it->stackID == ID)
  3070. {
  3071. shootingFinished = false;
  3072. if (it->animStartDelay == 0)
  3073. incrementFrame = false;
  3074. }
  3075. }
  3076. // Increment always when moving, never if stack died
  3077. creAnims[ID]->nextFrame(to, unitRect.x, unitRect.y, creDir[ID], animCount, incrementFrame, activeStack && ID==activeStack->ID, ID==mouseHoveredStack, &unitRect);
  3078. //printing amount
  3079. if(stack->count > 0 //don't print if stack is not alive
  3080. && (!curInt->curAction
  3081. || (curInt->curAction->stackNumber != ID //don't print if stack is currently taking an action
  3082. && (curInt->curAction->actionType != BattleAction::WALK_AND_ATTACK || stack->position != curInt->curAction->additionalInfo) //nor if it's an object of attack
  3083. && (curInt->curAction->destinationTile != stack->position) //nor if it's on destination tile for current action
  3084. )
  3085. )
  3086. && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON) //and not a war machine...
  3087. )
  3088. {
  3089. int xAdd = stack->attackerOwned ? 220 : 202;
  3090. //blitting amount background box
  3091. SDL_Surface *amountBG = NULL;
  3092. boost::shared_ptr<BonusList> spellEffects = stack->getSpellBonuses();
  3093. if(!spellEffects->size())
  3094. {
  3095. amountBG = amountNormal;
  3096. }
  3097. else
  3098. {
  3099. int pos=0; //determining total positiveness of effects
  3100. std::vector<si32> spellIds = stack->activeSpells();
  3101. for(std::vector<si32>::const_iterator it = spellIds.begin(); it != spellIds.end(); it++)
  3102. {
  3103. pos += CGI->spellh->spells[ *it ]->positiveness;
  3104. }
  3105. if(pos > 0)
  3106. {
  3107. amountBG = amountPositive;
  3108. }
  3109. else if(pos < 0)
  3110. {
  3111. amountBG = amountNegative;
  3112. }
  3113. else
  3114. {
  3115. amountBG = amountEffNeutral;
  3116. }
  3117. }
  3118. SDL_Rect temp_rect = genRect(amountNormal->h, amountNormal->w, creAnims[ID]->pos.x + xAdd, creAnims[ID]->pos.y + 260);
  3119. SDL_BlitSurface(amountBG, NULL, to, &temp_rect);
  3120. //blitting amount
  3121. CSDL_Ext::printAtMiddle(
  3122. makeNumberShort(stack->count),
  3123. creAnims[ID]->pos.x + xAdd + 15,
  3124. creAnims[ID]->pos.y + 260 + 5,
  3125. FONT_TINY,
  3126. zwykly,
  3127. to
  3128. );
  3129. }
  3130. }
  3131. void CBattleInterface::showPieceOfWall(SDL_Surface * to, int hex, const std::vector<const CStack*> & stacks)
  3132. {
  3133. if(!siegeH)
  3134. return;
  3135. using namespace boost::assign;
  3136. static const std::map<int, std::list<int> > hexToPart = map_list_of<int, std::list<int> >(12, list_of<int>(8)(1)(7))(45, list_of<int>(12)(6))
  3137. /*gate (78, list_of<int>(9))*/(101, list_of<int>(10))(118, list_of<int>(2))(165, list_of<int>(11))(186, list_of<int>(3));
  3138. std::map<int, std::list<int> >::const_iterator it = hexToPart.find(hex);
  3139. if(it != hexToPart.end())
  3140. {
  3141. BOOST_FOREACH(int wallNum, it->second)
  3142. {
  3143. siegeH->printPartOfWall(to, wallNum);
  3144. //print creature in turret
  3145. int posToSeek = -1;
  3146. switch(wallNum)
  3147. {
  3148. case 3: //bottom turret
  3149. posToSeek = -3;
  3150. break;
  3151. case 8: //upper turret
  3152. posToSeek = -4;
  3153. break;
  3154. case 2: //keep
  3155. posToSeek = -2;
  3156. break;
  3157. }
  3158. if(posToSeek != -1)
  3159. {
  3160. const CStack *turret = NULL;
  3161. BOOST_FOREACH(const CStack *s, stacks)
  3162. {
  3163. if(s->position == posToSeek)
  3164. {
  3165. turret = s;
  3166. break;
  3167. }
  3168. }
  3169. if(turret)
  3170. {
  3171. showAliveStack(turret, to);
  3172. //blitting creature cover
  3173. switch(posToSeek)
  3174. {
  3175. case -3: //bottom turret
  3176. siegeH->printPartOfWall(to, 16);
  3177. break;
  3178. case -4: //upper turret
  3179. siegeH->printPartOfWall(to, 17);
  3180. break;
  3181. case -2: //keep
  3182. siegeH->printPartOfWall(to, 15);
  3183. break;
  3184. }
  3185. }
  3186. }
  3187. }
  3188. }
  3189. // Damaged wall below gate have to be drawn earlier than a non-damaged wall below gate.
  3190. if ((hex == 112 && curInt->cb->battleGetWallState(3) == 3) || (hex == 147 && curInt->cb->battleGetWallState(3) != 3))
  3191. siegeH->printPartOfWall(to, 5);
  3192. // Damaged bottom wall have to be drawn earlier than a non-damaged bottom wall.
  3193. if ((hex == 165 && curInt->cb->battleGetWallState(4) == 3) || (hex == 185 && curInt->cb->battleGetWallState(4) != 3))
  3194. siegeH->printPartOfWall(to, 4);
  3195. }
  3196. void CBattleInterface::redrawBackgroundWithHexes(const CStack * activeStack)
  3197. {
  3198. attackableHexes.clear();
  3199. if (activeStack)
  3200. occupyableHexes = curInt->cb->battleGetAvailableHexes(activeStack, true, &attackableHexes);
  3201. //preparating background graphic with hexes and shaded hexes
  3202. blitAt(background, 0, 0, backgroundWithHexes);
  3203. if(curInt->sysOpts.printCellBorders)
  3204. CSDL_Ext::blit8bppAlphaTo24bpp(cellBorders, NULL, backgroundWithHexes, NULL);
  3205. if(curInt->sysOpts.printStackRange)
  3206. {
  3207. std::vector<THex> hexesToShade = occupyableHexes;
  3208. hexesToShade.insert(hexesToShade.end(), attackableHexes.begin(), attackableHexes.end());
  3209. BOOST_FOREACH(THex hex, hexesToShade)
  3210. {
  3211. int i = hex.getY(); //row
  3212. int j = hex.getX()-1; //column
  3213. int x = 58 + (i%2==0 ? 22 : 0) + 44*j;
  3214. int y = 86 + 42 * i;
  3215. SDL_Rect temp_rect = genRect(cellShade->h, cellShade->w, x, y);
  3216. CSDL_Ext::blit8bppAlphaTo24bpp(cellShade, NULL, backgroundWithHexes, &temp_rect);
  3217. }
  3218. }
  3219. }
  3220. void CBattleInterface::printConsoleAttacked( const CStack * defender, int dmg, int killed, const CStack * attacker, bool multiple )
  3221. {
  3222. char tabh[200];
  3223. int end = 0;
  3224. if (attacker) //ignore if stacks were killed by spell
  3225. {
  3226. end = sprintf(tabh, CGI->generaltexth->allTexts[attacker->count > 1 ? 377 : 376].c_str(),
  3227. (attacker->count > 1 ? attacker->getCreature()->namePl.c_str() : attacker->getCreature()->nameSing.c_str()), dmg);
  3228. }
  3229. if(killed > 0)
  3230. {
  3231. if(killed > 1)
  3232. {
  3233. sprintf(tabh + end, CGI->generaltexth->allTexts[379].c_str(), killed,
  3234. multiple ? CGI->generaltexth->allTexts[43].c_str() : defender->getCreature()->namePl.c_str()); // creatures perish
  3235. }
  3236. else //killed == 1
  3237. {
  3238. sprintf(tabh + end, CGI->generaltexth->allTexts[378].c_str(),
  3239. multiple ? CGI->generaltexth->allTexts[42].c_str() : defender->getCreature()->nameSing.c_str()); // creature perishes
  3240. }
  3241. }
  3242. console->addText(std::string(tabh));
  3243. }
  3244. void CBattleInterface::projectileShowHelper(SDL_Surface * to)
  3245. {
  3246. if(to == NULL)
  3247. to = screen;
  3248. std::list< std::list<SProjectileInfo>::iterator > toBeDeleted;
  3249. for(std::list<SProjectileInfo>::iterator it=projectiles.begin(); it!=projectiles.end(); ++it)
  3250. {
  3251. // Creature have to be in a shooting anim and the anim start delay must be over.
  3252. // Otherwise abort to start moving the projectile.
  3253. if (it->animStartDelay > 0)
  3254. {
  3255. if(it->animStartDelay == creAnims[it->stackID]->getAnimationFrame() + 1
  3256. && creAnims[it->stackID]->getType() >= 14 && creAnims[it->stackID]->getType() <= 16)
  3257. it->animStartDelay = 0;
  3258. else
  3259. continue;
  3260. }
  3261. SDL_Rect dst;
  3262. dst.h = idToProjectile[it->creID]->ourImages[it->frameNum].bitmap->h;
  3263. dst.w = idToProjectile[it->creID]->ourImages[it->frameNum].bitmap->w;
  3264. dst.x = it->x;
  3265. dst.y = it->y;
  3266. // The equation below calculates the center pos of the canon, but we need the top left pos
  3267. // of it for drawing
  3268. if (it->catapultInfo)
  3269. {
  3270. dst.x -= 17.;
  3271. dst.y -= 10.;
  3272. }
  3273. if(it->reverse)
  3274. {
  3275. SDL_Surface * rev = CSDL_Ext::rotate01(idToProjectile[it->creID]->ourImages[it->frameNum].bitmap);
  3276. CSDL_Ext::blit8bppAlphaTo24bpp(rev, NULL, to, &dst);
  3277. SDL_FreeSurface(rev);
  3278. }
  3279. else
  3280. {
  3281. CSDL_Ext::blit8bppAlphaTo24bpp(idToProjectile[it->creID]->ourImages[it->frameNum].bitmap, NULL, to, &dst);
  3282. }
  3283. // Update projectile
  3284. ++it->step;
  3285. if(it->step == it->lastStep)
  3286. {
  3287. toBeDeleted.insert(toBeDeleted.end(), it);
  3288. }
  3289. else
  3290. {
  3291. if (it->catapultInfo)
  3292. {
  3293. // Parabolic shot of the trajectory, as follows: f(x) = ax^2 + bx + c
  3294. it->x += it->dx;
  3295. it->y = it->catapultInfo->calculateY(it->x - this->pos.x) + this->pos.y;
  3296. }
  3297. else
  3298. {
  3299. // Normal projectile, just add the calculated "deltas" to the x and y positions.
  3300. it->x += it->dx;
  3301. it->y += it->dy;
  3302. }
  3303. if(it->spin)
  3304. {
  3305. ++(it->frameNum);
  3306. it->frameNum %= idToProjectile[it->creID]->ourImages.size();
  3307. }
  3308. }
  3309. }
  3310. for(std::list< std::list<SProjectileInfo>::iterator >::iterator it = toBeDeleted.begin(); it!= toBeDeleted.end(); ++it)
  3311. {
  3312. projectiles.erase(*it);
  3313. }
  3314. }
  3315. void CBattleInterface::endAction(const BattleAction* action)
  3316. {
  3317. //if((action->actionType==2 || (action->actionType==6 && action->destinationTile!=cb->battleGetPos(action->stackNumber)))) //activating interface when move is finished
  3318. // {
  3319. // activate();
  3320. // }
  3321. if(action->actionType == BattleAction::HERO_SPELL)
  3322. {
  3323. if(action->side)
  3324. defendingHero->setPhase(0);
  3325. else
  3326. attackingHero->setPhase(0);
  3327. }
  3328. if(action->actionType == BattleAction::WALK && creAnims[action->stackNumber]->getType() != 2) //walk or walk & attack
  3329. {
  3330. const CStack * stack = curInt->cb->battleGetStackByID(action->stackNumber);
  3331. pendingAnims.push_back(std::make_pair(new CBattleMoveEnd(this, stack, action->destinationTile), false));
  3332. }
  3333. if(action->actionType == BattleAction::CATAPULT) //catapult
  3334. {
  3335. }
  3336. //check if we should reverse stacks
  3337. //for some strange reason, it's not enough
  3338. // std::set<const CStack *> stacks;
  3339. // stacks.insert(LOCPLINT->cb->battleGetStackByID(action->stackNumber));
  3340. // stacks.insert(LOCPLINT->cb->battleGetStackByPos(action->destinationTile));
  3341. TStacks stacks = curInt->cb->battleGetStacks(CBattleCallback::MINE_AND_ENEMY);
  3342. BOOST_FOREACH(const CStack *s, stacks)
  3343. {
  3344. if(s && creDir[s->ID] != bool(s->attackerOwned) && s->alive())
  3345. {
  3346. addNewAnim(new CReverseAnim(this, s, s->position, false));
  3347. }
  3348. }
  3349. queue->update();
  3350. if(tacticsMode) //we have activated next stack after sending request that has been just realized -> blockmap due to movement has changed
  3351. redrawBackgroundWithHexes(activeStack);
  3352. }
  3353. void CBattleInterface::hideQueue()
  3354. {
  3355. curInt->sysOpts.showQueue = false;
  3356. queue->deactivate();
  3357. if(!queue->embedded)
  3358. {
  3359. moveBy(Point(0, -queue->pos.h / 2));
  3360. GH.totalRedraw();
  3361. }
  3362. }
  3363. void CBattleInterface::showQueue()
  3364. {
  3365. curInt->sysOpts.showQueue = true;
  3366. queue->activate();
  3367. if(!queue->embedded)
  3368. {
  3369. moveBy(Point(0, +queue->pos.h / 2));
  3370. GH.totalRedraw();
  3371. }
  3372. }
  3373. void CBattleInterface::startAction(const BattleAction* action)
  3374. {
  3375. if(action->actionType == BattleAction::END_TACTIC_PHASE)
  3376. {
  3377. menu = BitmapHandler::loadBitmap("CBAR.bmp");
  3378. graphics->blueToPlayersAdv(menu, curInt->playerID);
  3379. if(active)
  3380. {
  3381. tacticsMode = false;
  3382. if(btactEnd && btactNext) //if the other side had tactics, there are no buttons
  3383. {
  3384. btactEnd->deactivate();
  3385. btactNext->deactivate();
  3386. bConsoleDown->activate();
  3387. bConsoleUp->activate();
  3388. }
  3389. }
  3390. redraw();
  3391. return;
  3392. }
  3393. const CStack *stack = curInt->cb->battleGetStackByID(action->stackNumber);
  3394. if(stack)
  3395. {
  3396. queue->update();
  3397. }
  3398. else
  3399. {
  3400. assert(action->actionType == BattleAction::HERO_SPELL); //only cast spell is valid action without acting stack number
  3401. }
  3402. if(action->actionType == BattleAction::WALK
  3403. || (action->actionType == BattleAction::WALK_AND_ATTACK && action->destinationTile != stack->position))
  3404. {
  3405. moveStarted = true;
  3406. if(creAnims[action->stackNumber]->framesInGroup(CCreatureAnim::MOVE_START))
  3407. {
  3408. const CStack * stack = curInt->cb->battleGetStackByID(action->stackNumber);
  3409. pendingAnims.push_back(std::make_pair(new CBattleMoveStart(this, stack), false));
  3410. }
  3411. }
  3412. if(active)
  3413. deactivate();
  3414. char txt[400];
  3415. if(action->actionType == BattleAction::HERO_SPELL) //when hero casts spell
  3416. {
  3417. if(action->side)
  3418. defendingHero->setPhase(4);
  3419. else
  3420. attackingHero->setPhase(4);
  3421. return;
  3422. }
  3423. if(!stack)
  3424. {
  3425. tlog1<<"Something wrong with stackNumber in actionStarted. Stack number: "<<action->stackNumber<<std::endl;
  3426. return;
  3427. }
  3428. int txtid = 0;
  3429. switch(action->actionType)
  3430. {
  3431. case BattleAction::WAIT:
  3432. txtid = 136;
  3433. break;
  3434. case BattleAction::BAD_MORALE:
  3435. txtid = -34; //negative -> no separate singular/plural form
  3436. displayEffect(30,stack->position);
  3437. break;
  3438. }
  3439. if(txtid > 0 && stack->count != 1)
  3440. txtid++; //move to plural text
  3441. else if(txtid < 0)
  3442. txtid = -txtid;
  3443. if(txtid)
  3444. {
  3445. sprintf(txt, CGI->generaltexth->allTexts[txtid].c_str(), (stack->count != 1) ? stack->getCreature()->namePl.c_str() : stack->getCreature()->nameSing.c_str(), 0);
  3446. console->addText(txt);
  3447. }
  3448. //displaying special abilities
  3449. switch (action->actionType)
  3450. {
  3451. case BattleAction::STACK_HEAL:
  3452. displayEffect(74, action->destinationTile);
  3453. CCS->soundh->playSound(soundBase::REGENER);
  3454. break;
  3455. }
  3456. }
  3457. void CBattleInterface::waitForAnims()
  3458. {
  3459. LOCPLINT->pim->unlock();
  3460. animsAreDisplayed.waitWhileTrue();
  3461. LOCPLINT->pim->lock();
  3462. }
  3463. void CBattleInterface::bEndTacticPhase()
  3464. {
  3465. btactEnd->block(true);
  3466. bDefence->block(false);
  3467. bWait->block(false);
  3468. BattleAction endt = BattleAction::makeEndOFTacticPhase(curInt->cb->battleGetMySide());
  3469. curInt->cb->battleMakeTacticAction(&endt);
  3470. }
  3471. static bool immobile(const CStack *s)
  3472. {
  3473. return !s->Speed();
  3474. }
  3475. void CBattleInterface::bTacticNextStack()
  3476. {
  3477. TStacks stacksOfMine = tacticianInterface->cb->battleGetStacks(CBattleCallback::ONLY_MINE);
  3478. stacksOfMine.erase(std::remove_if(stacksOfMine.begin(), stacksOfMine.end(), &immobile), stacksOfMine.end());
  3479. TStacks::iterator it = vstd::find(stacksOfMine, activeStack);
  3480. if(it != stacksOfMine.end() && ++it != stacksOfMine.end())
  3481. stackActivated(*it);
  3482. else
  3483. stackActivated(stacksOfMine.front());
  3484. }
  3485. void CBattleHero::show(SDL_Surface *to)
  3486. {
  3487. //animation of flag
  3488. if(flip)
  3489. {
  3490. SDL_Rect temp_rect = genRect(
  3491. flag->ourImages[flagAnim].bitmap->h,
  3492. flag->ourImages[flagAnim].bitmap->w,
  3493. pos.x + 61,
  3494. pos.y + 39);
  3495. CSDL_Ext::blit8bppAlphaTo24bpp(
  3496. flag->ourImages[flagAnim].bitmap,
  3497. NULL,
  3498. screen,
  3499. &temp_rect);
  3500. }
  3501. else
  3502. {
  3503. SDL_Rect temp_rect = genRect(
  3504. flag->ourImages[flagAnim].bitmap->h,
  3505. flag->ourImages[flagAnim].bitmap->w,
  3506. pos.x + 72,
  3507. pos.y + 39);
  3508. CSDL_Ext::blit8bppAlphaTo24bpp(
  3509. flag->ourImages[flagAnim].bitmap,
  3510. NULL,
  3511. screen,
  3512. &temp_rect);
  3513. }
  3514. ++flagAnimCount;
  3515. if(flagAnimCount%4==0)
  3516. {
  3517. ++flagAnim;
  3518. flagAnim %= flag->ourImages.size();
  3519. }
  3520. //animation of hero
  3521. int tick=-1;
  3522. for(int i=0; i<dh->ourImages.size(); ++i)
  3523. {
  3524. if(dh->ourImages[i].groupNumber==phase)
  3525. ++tick;
  3526. if(tick==image)
  3527. {
  3528. SDL_Rect posb = pos;
  3529. CSDL_Ext::blit8bppAlphaTo24bpp(dh->ourImages[i].bitmap, NULL, to, &posb);
  3530. if(phase != 4 || nextPhase != -1 || image < 4)
  3531. {
  3532. if(flagAnimCount%2==0)
  3533. {
  3534. ++image;
  3535. }
  3536. if(dh->ourImages[(i+1)%dh->ourImages.size()].groupNumber!=phase) //back to appropriate frame
  3537. {
  3538. image = 0;
  3539. }
  3540. }
  3541. if(phase == 4 && nextPhase != -1 && image == 7)
  3542. {
  3543. phase = nextPhase;
  3544. nextPhase = -1;
  3545. image = 0;
  3546. }
  3547. break;
  3548. }
  3549. }
  3550. }
  3551. void CBattleHero::activate()
  3552. {
  3553. activateLClick();
  3554. }
  3555. void CBattleHero::deactivate()
  3556. {
  3557. deactivateLClick();
  3558. }
  3559. void CBattleHero::setPhase(int newPhase)
  3560. {
  3561. if(phase != 4)
  3562. {
  3563. phase = newPhase;
  3564. image = 0;
  3565. }
  3566. else
  3567. {
  3568. nextPhase = newPhase;
  3569. }
  3570. }
  3571. void CBattleHero::clickLeft(tribool down, bool previousState)
  3572. {
  3573. if(myOwner->spellDestSelectMode) //we are casting a spell
  3574. return;
  3575. if(!down && myHero && myOwner->curInt->cb->battleCanCastSpell()) //check conditions
  3576. {
  3577. for(int it=0; it<BFIELD_SIZE; ++it) //do nothing when any hex is hovered - hero's animation overlaps battlefield
  3578. {
  3579. if(myOwner->bfield[it].hovered && myOwner->bfield[it].strictHovered)
  3580. return;
  3581. }
  3582. CCS->curh->changeGraphic(0,0);
  3583. CSpellWindow * spellWindow = new CSpellWindow(genRect(595, 620, (conf.cc.resx - 620)/2, (conf.cc.resy - 595)/2), myHero, myOwner->curInt);
  3584. GH.pushInt(spellWindow);
  3585. }
  3586. }
  3587. CBattleHero::CBattleHero(const std::string & defName, int phaseG, int imageG, bool flipG, unsigned char player, const CGHeroInstance * hero, const CBattleInterface * owner): flip(flipG), myHero(hero), myOwner(owner), phase(phaseG), nextPhase(-1), image(imageG), flagAnim(0), flagAnimCount(0)
  3588. {
  3589. dh = CDefHandler::giveDef( defName );
  3590. for(int i=0; i<dh->ourImages.size(); ++i) //transforming images
  3591. {
  3592. if(flip)
  3593. {
  3594. SDL_Surface * hlp = CSDL_Ext::rotate01(dh->ourImages[i].bitmap);
  3595. SDL_FreeSurface(dh->ourImages[i].bitmap);
  3596. dh->ourImages[i].bitmap = hlp;
  3597. }
  3598. CSDL_Ext::alphaTransform(dh->ourImages[i].bitmap);
  3599. }
  3600. if(flip)
  3601. flag = CDefHandler::giveDef("CMFLAGR.DEF");
  3602. else
  3603. flag = CDefHandler::giveDef("CMFLAGL.DEF");
  3604. //coloring flag and adding transparency
  3605. for(int i=0; i<flag->ourImages.size(); ++i)
  3606. {
  3607. CSDL_Ext::alphaTransform(flag->ourImages[i].bitmap);
  3608. graphics->blueToPlayersAdv(flag->ourImages[i].bitmap, player);
  3609. }
  3610. }
  3611. CBattleHero::~CBattleHero()
  3612. {
  3613. delete dh;
  3614. delete flag;
  3615. }
  3616. Point CBattleHex::getXYUnitAnim(const int & hexNum, const bool & attacker, const CStack * stack, const CBattleInterface * cbi)
  3617. {
  3618. Point ret(-500, -500); //returned value
  3619. if(stack && stack->position < 0) //creatures in turrets
  3620. {
  3621. switch(stack->position)
  3622. {
  3623. case -2: //keep
  3624. ret = graphics->wallPositions[cbi->siegeH->town->town->typeID][17];
  3625. break;
  3626. case -3: //lower turret
  3627. ret = graphics->wallPositions[cbi->siegeH->town->town->typeID][18];
  3628. break;
  3629. case -4: //upper turret
  3630. ret = graphics->wallPositions[cbi->siegeH->town->town->typeID][19];
  3631. break;
  3632. }
  3633. }
  3634. else
  3635. {
  3636. ret.y = -139 + 42 * (hexNum/BFIELD_WIDTH); //counting y
  3637. //counting x
  3638. if(attacker)
  3639. {
  3640. ret.x = -160 + 22 * ( ((hexNum/BFIELD_WIDTH) + 1)%2 ) + 44 * (hexNum % BFIELD_WIDTH);
  3641. }
  3642. else
  3643. {
  3644. ret.x = -219 + 22 * ( ((hexNum/BFIELD_WIDTH) + 1)%2 ) + 44 * (hexNum % BFIELD_WIDTH);
  3645. }
  3646. //shifting position for double - hex creatures
  3647. if(stack && stack->doubleWide())
  3648. {
  3649. if(attacker)
  3650. {
  3651. ret.x -= 44;
  3652. }
  3653. else
  3654. {
  3655. ret.x += 45;
  3656. }
  3657. }
  3658. }
  3659. //returning
  3660. return ret +CPlayerInterface::battleInt->pos;
  3661. }
  3662. void CBattleHex::activate()
  3663. {
  3664. activateHover();
  3665. activateMouseMove();
  3666. activateLClick();
  3667. activateRClick();
  3668. }
  3669. void CBattleHex::deactivate()
  3670. {
  3671. deactivateHover();
  3672. deactivateMouseMove();
  3673. deactivateLClick();
  3674. deactivateRClick();
  3675. }
  3676. void CBattleHex::hover(bool on)
  3677. {
  3678. hovered = on;
  3679. //Hoverable::hover(on);
  3680. if(!on && setAlterText)
  3681. {
  3682. myInterface->console->alterTxt = std::string();
  3683. setAlterText = false;
  3684. }
  3685. }
  3686. CBattleHex::CBattleHex() : setAlterText(false), myNumber(-1), accessible(true), hovered(false), strictHovered(false), myInterface(NULL)
  3687. {
  3688. }
  3689. void CBattleHex::mouseMoved(const SDL_MouseMotionEvent &sEvent)
  3690. {
  3691. if(myInterface->cellShade)
  3692. {
  3693. if(CSDL_Ext::SDL_GetPixel(myInterface->cellShade, sEvent.x-pos.x, sEvent.y-pos.y) == 0) //hovered pixel is outside hex
  3694. {
  3695. strictHovered = false;
  3696. }
  3697. else //hovered pixel is inside hex
  3698. {
  3699. strictHovered = true;
  3700. }
  3701. }
  3702. if(hovered && strictHovered) //print attacked creature to console
  3703. {
  3704. const CStack * attackedStack = myInterface->curInt->cb->battleGetStackByPos(myNumber);
  3705. if(myInterface->console->alterTxt.size() == 0 &&attackedStack != NULL &&
  3706. attackedStack->owner != myInterface->curInt->playerID &&
  3707. attackedStack->alive())
  3708. {
  3709. char tabh[160];
  3710. const std::string & attackedName = attackedStack->count == 1 ? attackedStack->getCreature()->nameSing : attackedStack->getCreature()->namePl;
  3711. sprintf(tabh, CGI->generaltexth->allTexts[220].c_str(), attackedName.c_str());
  3712. myInterface->console->alterTxt = std::string(tabh);
  3713. setAlterText = true;
  3714. }
  3715. }
  3716. else if(setAlterText)
  3717. {
  3718. myInterface->console->alterTxt = std::string();
  3719. setAlterText = false;
  3720. }
  3721. }
  3722. void CBattleHex::clickLeft(tribool down, bool previousState)
  3723. {
  3724. if(!down && hovered && strictHovered) //we've been really clicked!
  3725. {
  3726. myInterface->hexLclicked(myNumber);
  3727. }
  3728. }
  3729. void CBattleHex::clickRight(tribool down, bool previousState)
  3730. {
  3731. const CStack * myst = myInterface->curInt->cb->battleGetStackByPos(myNumber); //stack info
  3732. if(hovered && strictHovered && myst!=NULL)
  3733. {
  3734. if(!myst->alive()) return;
  3735. if(down)
  3736. {
  3737. GH.pushInt(createCreWindow(myst));
  3738. }
  3739. }
  3740. }
  3741. CBattleConsole::CBattleConsole() : lastShown(-1), alterTxt(""), whoSetAlter(0)
  3742. {
  3743. }
  3744. CBattleConsole::~CBattleConsole()
  3745. {
  3746. texts.clear();
  3747. }
  3748. void CBattleConsole::show(SDL_Surface * to)
  3749. {
  3750. if(ingcAlter.size())
  3751. {
  3752. CSDL_Ext::printAtMiddleWB(ingcAlter, pos.x + pos.w/2, pos.y + 11, FONT_SMALL, 80, zwykly, to);
  3753. }
  3754. else if(alterTxt.size())
  3755. {
  3756. CSDL_Ext::printAtMiddleWB(alterTxt, pos.x + pos.w/2, pos.y + 11, FONT_SMALL, 80, zwykly, to);
  3757. }
  3758. else if(texts.size())
  3759. {
  3760. if(texts.size()==1)
  3761. {
  3762. CSDL_Ext::printAtMiddleWB(texts[0], pos.x + pos.w/2, pos.y + 11, FONT_SMALL, 80, zwykly, to);
  3763. }
  3764. else
  3765. {
  3766. CSDL_Ext::printAtMiddleWB(texts[lastShown-1], pos.x + pos.w/2, pos.y + 11, FONT_SMALL, 80, zwykly, to);
  3767. CSDL_Ext::printAtMiddleWB(texts[lastShown], pos.x + pos.w/2, pos.y + 27, FONT_SMALL, 80, zwykly, to);
  3768. }
  3769. }
  3770. }
  3771. bool CBattleConsole::addText(const std::string & text)
  3772. {
  3773. if(text.size()>70)
  3774. return false; //text too long!
  3775. int firstInToken = 0;
  3776. for(int i=0; i<text.size(); ++i) //tokenize
  3777. {
  3778. if(text[i] == 10)
  3779. {
  3780. texts.push_back( text.substr(firstInToken, i-firstInToken) );
  3781. firstInToken = i+1;
  3782. }
  3783. }
  3784. texts.push_back( text.substr(firstInToken, text.size()) );
  3785. lastShown = texts.size()-1;
  3786. return true;
  3787. }
  3788. void CBattleConsole::eraseText(unsigned int pos)
  3789. {
  3790. if(pos < texts.size())
  3791. {
  3792. texts.erase(texts.begin() + pos);
  3793. if(lastShown == texts.size())
  3794. --lastShown;
  3795. }
  3796. }
  3797. void CBattleConsole::changeTextAt(const std::string & text, unsigned int pos)
  3798. {
  3799. if(pos >= texts.size()) //no such pos
  3800. return;
  3801. texts[pos] = text;
  3802. }
  3803. void CBattleConsole::scrollUp(unsigned int by)
  3804. {
  3805. if(lastShown > by)
  3806. lastShown -= by;
  3807. }
  3808. void CBattleConsole::scrollDown(unsigned int by)
  3809. {
  3810. if(lastShown + by < texts.size())
  3811. lastShown += by;
  3812. }
  3813. CBattleResultWindow::CBattleResultWindow(const BattleResult &br, const SDL_Rect & pos, CBattleInterface * _owner)
  3814. : owner(_owner)
  3815. {
  3816. this->pos = pos;
  3817. background = BitmapHandler::loadBitmap("CPRESULT.BMP", true);
  3818. graphics->blueToPlayersAdv(background, owner->curInt->playerID);
  3819. SDL_Surface * pom = SDL_ConvertSurface(background, screen->format, screen->flags);
  3820. SDL_FreeSurface(background);
  3821. background = pom;
  3822. exit = new AdventureMapButton (std::string(), std::string(), boost::bind(&CBattleResultWindow::bExitf,this), 384 + pos.x, 505 + pos.y, "iok6432.def", SDLK_RETURN);
  3823. exit->borderColor = Colors::MetallicGold;
  3824. exit->borderEnabled = true;
  3825. if(br.winner==0) //attacker won
  3826. {
  3827. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[410], 59, 124, FONT_SMALL, zwykly, background);
  3828. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[411], 408, 124, FONT_SMALL, zwykly, background);
  3829. }
  3830. else //if(br.winner==1)
  3831. {
  3832. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[411], 59, 124, FONT_SMALL, zwykly, background);
  3833. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[410], 412, 124, FONT_SMALL, zwykly, background);
  3834. }
  3835. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[407], 232, 302, FONT_BIG, tytulowy, background);
  3836. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[408], 232, 332, FONT_BIG, zwykly, background);
  3837. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[409], 237, 428, FONT_BIG, zwykly, background);
  3838. std::string attackerName, defenderName;
  3839. if(owner->attackingHeroInstance) //a hero attacked
  3840. {
  3841. SDL_Rect temp_rect = genRect(64, 58, 21, 38);
  3842. SDL_BlitSurface(graphics->portraitLarge[owner->attackingHeroInstance->portrait], NULL, background, &temp_rect);
  3843. //setting attackerName
  3844. attackerName = owner->attackingHeroInstance->name;
  3845. }
  3846. else //a monster attacked
  3847. {
  3848. int bestMonsterID = -1;
  3849. int bestPower = 0;
  3850. for(TSlots::const_iterator it = owner->army1->Slots().begin(); it!=owner->army1->Slots().end(); ++it)
  3851. {
  3852. if( it->second->type->AIValue > bestPower)
  3853. {
  3854. bestPower = it->second->type->AIValue;
  3855. bestMonsterID = it->second->type->idNumber;
  3856. }
  3857. }
  3858. SDL_Rect temp_rect = genRect(64, 58, 21, 38);
  3859. SDL_BlitSurface(graphics->bigImgs[bestMonsterID], NULL, background, &temp_rect);
  3860. //setting attackerName
  3861. attackerName = CGI->creh->creatures[bestMonsterID]->namePl;
  3862. }
  3863. if(owner->defendingHeroInstance) //a hero defended
  3864. {
  3865. SDL_Rect temp_rect = genRect(64, 58, 392, 38);
  3866. SDL_BlitSurface(graphics->portraitLarge[owner->defendingHeroInstance->portrait], NULL, background, &temp_rect);
  3867. //setting defenderName
  3868. defenderName = owner->defendingHeroInstance->name;
  3869. }
  3870. else //a monster defended
  3871. {
  3872. int bestMonsterID = -1;
  3873. int bestPower = 0;
  3874. for(TSlots::const_iterator it = owner->army2->Slots().begin(); it!=owner->army2->Slots().end(); ++it)
  3875. {
  3876. if( it->second->type->AIValue > bestPower)
  3877. {
  3878. bestPower = it->second->type->AIValue;
  3879. bestMonsterID = it->second->type->idNumber;
  3880. }
  3881. }
  3882. SDL_Rect temp_rect = genRect(64, 58, 392, 38);
  3883. SDL_BlitSurface(graphics->bigImgs[bestMonsterID], NULL, background, &temp_rect);
  3884. //setting defenderName
  3885. defenderName = CGI->creh->creatures[bestMonsterID]->namePl;
  3886. }
  3887. //printing attacker and defender's names
  3888. CSDL_Ext::printAt(attackerName, 89, 37, FONT_SMALL, zwykly, background);
  3889. CSDL_Ext::printTo(defenderName, 381, 53, FONT_SMALL, zwykly, background);
  3890. //printing casualities
  3891. for(int step = 0; step < 2; ++step)
  3892. {
  3893. if(br.casualties[step].size()==0)
  3894. {
  3895. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[523], 235, 360 + 97*step, FONT_SMALL, zwykly, background);
  3896. }
  3897. else
  3898. {
  3899. int xPos = 235 - (br.casualties[step].size()*32 + (br.casualties[step].size() - 1)*10)/2; //increment by 42 with each picture
  3900. int yPos = 344 + step*97;
  3901. for(std::map<ui32,si32>::const_iterator it=br.casualties[step].begin(); it!=br.casualties[step].end(); ++it)
  3902. {
  3903. blitAt(graphics->smallImgs[it->first], xPos, yPos, background);
  3904. std::ostringstream amount;
  3905. amount<<it->second;
  3906. CSDL_Ext::printAtMiddle(amount.str(), xPos+16, yPos + 42, FONT_SMALL, zwykly, background);
  3907. xPos += 42;
  3908. }
  3909. }
  3910. }
  3911. //printing result description
  3912. bool weAreAttacker = (owner->curInt->playerID == owner->attackingHeroInstance->tempOwner);
  3913. if((br.winner == 0 && weAreAttacker) || (br.winner == 1 && !weAreAttacker)) //we've won
  3914. {
  3915. int text=-1;
  3916. switch(br.result)
  3917. {
  3918. case 0: text = 304; break;
  3919. case 1: text = 303; break;
  3920. case 2: text = 302; break;
  3921. }
  3922. CCS->musich->playMusic(musicBase::winBattle);
  3923. CCS->videoh->open(VIDEO_WIN);
  3924. std::string str = CGI->generaltexth->allTexts[text];
  3925. const CGHeroInstance * ourHero = weAreAttacker? owner->attackingHeroInstance : owner->defendingHeroInstance;
  3926. if (ourHero)
  3927. {
  3928. str += CGI->generaltexth->allTexts[305];
  3929. boost::algorithm::replace_first(str,"%s",ourHero->name);
  3930. boost::algorithm::replace_first(str,"%d",boost::lexical_cast<std::string>(br.exp[weAreAttacker?0:1]));
  3931. }
  3932. CSDL_Ext::printAtMiddleWB(str, 235, 235, FONT_SMALL, 55, zwykly, background);
  3933. }
  3934. else // we lose
  3935. {
  3936. switch(br.result)
  3937. {
  3938. case 0: //normal victory
  3939. {
  3940. CCS->musich->playMusic(musicBase::loseCombat);
  3941. CCS->videoh->open(VIDEO_LOSE_BATTLE_START);
  3942. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[311], 235, 235, FONT_SMALL, zwykly, background);
  3943. break;
  3944. }
  3945. case 1: //flee
  3946. {
  3947. CCS->musich->playMusic(musicBase::retreatBattle);
  3948. CCS->videoh->open(VIDEO_RETREAT_START);
  3949. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[310], 235, 235, FONT_SMALL, zwykly, background);
  3950. break;
  3951. }
  3952. case 2: //surrender
  3953. {
  3954. CCS->musich->playMusic(musicBase::surrenderBattle);
  3955. CCS->videoh->open(VIDEO_SURRENDER);
  3956. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[309], 235, 220, FONT_SMALL, zwykly, background);
  3957. break;
  3958. }
  3959. }
  3960. }
  3961. }
  3962. CBattleResultWindow::~CBattleResultWindow()
  3963. {
  3964. SDL_FreeSurface(background);
  3965. }
  3966. void CBattleResultWindow::activate()
  3967. {
  3968. owner->curInt->showingDialog->set(true);
  3969. exit->activate();
  3970. }
  3971. void CBattleResultWindow::deactivate()
  3972. {
  3973. exit->deactivate();
  3974. }
  3975. void CBattleResultWindow::show(SDL_Surface *to)
  3976. {
  3977. //evaluating to
  3978. if(!to)
  3979. to = screen;
  3980. CCS->videoh->update(107, 70, background, false, true);
  3981. SDL_BlitSurface(background, NULL, to, &pos);
  3982. exit->showAll(to);
  3983. }
  3984. void CBattleResultWindow::bExitf()
  3985. {
  3986. if(LOCPLINT->cb->getStartInfo()->mode == StartInfo::DUEL)
  3987. {
  3988. std::exit(0);
  3989. }
  3990. CPlayerInterface * intTmp = owner->curInt;
  3991. GH.popInts(2); //first - we; second - battle interface
  3992. intTmp->showingDialog->setn(false);
  3993. CCS->videoh->close();
  3994. }
  3995. CBattleOptionsWindow::CBattleOptionsWindow(const SDL_Rect & position, CBattleInterface *owner): myInt(owner)
  3996. {
  3997. pos = position;
  3998. SDL_Surface *hhlp = BitmapHandler::loadBitmap("comopbck.bmp", true);
  3999. graphics->blueToPlayersAdv(hhlp, owner->curInt->playerID);
  4000. background = SDL_ConvertSurface(hhlp, screen->format, 0);
  4001. SDL_SetColorKey(background, SDL_SRCCOLORKEY, SDL_MapRGB(background->format,0,255,255));
  4002. SDL_FreeSurface(hhlp);
  4003. viewGrid = new CHighlightableButton(boost::bind(&CBattleInterface::setPrintCellBorders, owner, true), boost::bind(&CBattleInterface::setPrintCellBorders, owner, false), boost::assign::map_list_of(0,CGI->generaltexth->zelp[427].first)(3,CGI->generaltexth->zelp[427].first), CGI->generaltexth->zelp[427].second, false, "sysopchk.def", NULL, 185, 140, false);
  4004. viewGrid->select(owner->curInt->sysOpts.printCellBorders);
  4005. movementShadow = new CHighlightableButton(boost::bind(&CBattleInterface::setPrintStackRange, owner, true), boost::bind(&CBattleInterface::setPrintStackRange, owner, false), boost::assign::map_list_of(0,CGI->generaltexth->zelp[428].first)(3,CGI->generaltexth->zelp[428].first), CGI->generaltexth->zelp[428].second, false, "sysopchk.def", NULL, 185, 173, false);
  4006. movementShadow->select(owner->curInt->sysOpts.printStackRange);
  4007. mouseShadow = new CHighlightableButton(boost::bind(&CBattleInterface::setPrintMouseShadow, owner, true), boost::bind(&CBattleInterface::setPrintMouseShadow, owner, false), boost::assign::map_list_of(0,CGI->generaltexth->zelp[429].first)(3,CGI->generaltexth->zelp[429].first), CGI->generaltexth->zelp[429].second, false, "sysopchk.def", NULL, 185, 207, false);
  4008. mouseShadow->select(owner->curInt->sysOpts.printMouseShadow);
  4009. animSpeeds = new CHighlightableButtonsGroup(0);
  4010. animSpeeds->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[422].first),CGI->generaltexth->zelp[422].second, "sysopb9.def",188, 309, 1);
  4011. animSpeeds->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[423].first),CGI->generaltexth->zelp[423].second, "sysob10.def",252, 309, 2);
  4012. animSpeeds->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[424].first),CGI->generaltexth->zelp[424].second, "sysob11.def",315, 309, 4);
  4013. animSpeeds->select(owner->getAnimSpeed(), 1);
  4014. animSpeeds->onChange = boost::bind(&CBattleInterface::setAnimSpeed, owner, _1);
  4015. setToDefault = new AdventureMapButton (CGI->generaltexth->zelp[393], boost::bind(&CBattleOptionsWindow::bDefaultf,this), 405, 443, "codefaul.def");
  4016. setToDefault->swappedImages = true;
  4017. setToDefault->update();
  4018. exit = new AdventureMapButton (CGI->generaltexth->zelp[392], boost::bind(&CBattleOptionsWindow::bExitf,this), 516, 443, "soretrn.def",SDLK_RETURN);
  4019. exit->swappedImages = true;
  4020. exit->update();
  4021. //printing texts to background
  4022. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[392], 242, 32, FONT_BIG, tytulowy, background); //window title
  4023. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[393], 122, 214, FONT_MEDIUM, tytulowy, background); //animation speed
  4024. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[394], 122, 293, FONT_MEDIUM, tytulowy, background); //music volume
  4025. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[395], 122, 359, FONT_MEDIUM, tytulowy, background); //effects' volume
  4026. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[396], 353, 66, FONT_MEDIUM, tytulowy, background); //auto - combat options
  4027. CSDL_Ext::printAtMiddle(CGI->generaltexth->allTexts[397], 353, 265, FONT_MEDIUM, tytulowy, background); //creature info
  4028. //auto - combat options
  4029. CSDL_Ext::printAt(CGI->generaltexth->allTexts[398], 283, 86, FONT_MEDIUM, zwykly, background); //creatures
  4030. CSDL_Ext::printAt(CGI->generaltexth->allTexts[399], 283, 116, FONT_MEDIUM, zwykly, background); //spells
  4031. CSDL_Ext::printAt(CGI->generaltexth->allTexts[400], 283, 146, FONT_MEDIUM, zwykly, background); //catapult
  4032. CSDL_Ext::printAt(CGI->generaltexth->allTexts[151], 283, 176, FONT_MEDIUM, zwykly, background); //ballista
  4033. CSDL_Ext::printAt(CGI->generaltexth->allTexts[401], 283, 206, FONT_MEDIUM, zwykly, background); //first aid tent
  4034. //creature info
  4035. CSDL_Ext::printAt(CGI->generaltexth->allTexts[402], 283, 285, FONT_MEDIUM, zwykly, background); //all stats
  4036. CSDL_Ext::printAt(CGI->generaltexth->allTexts[403], 283, 315, FONT_MEDIUM, zwykly, background); //spells only
  4037. //general options
  4038. CSDL_Ext::printAt(CGI->generaltexth->allTexts[404], 61, 57, FONT_MEDIUM, zwykly, background); //hex grid
  4039. CSDL_Ext::printAt(CGI->generaltexth->allTexts[405], 61, 90, FONT_MEDIUM, zwykly, background); //movement shadow
  4040. CSDL_Ext::printAt(CGI->generaltexth->allTexts[406], 61, 124, FONT_MEDIUM, zwykly, background); //cursor shadow
  4041. CSDL_Ext::printAt(CGI->generaltexth->allTexts[577], 61, 156, FONT_MEDIUM, zwykly, background); //spellbook animation
  4042. //texts printed
  4043. }
  4044. CBattleOptionsWindow::~CBattleOptionsWindow()
  4045. {
  4046. SDL_FreeSurface(background);
  4047. delete setToDefault;
  4048. delete exit;
  4049. delete viewGrid;
  4050. delete movementShadow;
  4051. delete animSpeeds;
  4052. delete mouseShadow;
  4053. }
  4054. void CBattleOptionsWindow::activate()
  4055. {
  4056. setToDefault->activate();
  4057. exit->activate();
  4058. viewGrid->activate();
  4059. movementShadow->activate();
  4060. animSpeeds->activate();
  4061. mouseShadow->activate();
  4062. }
  4063. void CBattleOptionsWindow::deactivate()
  4064. {
  4065. setToDefault->deactivate();
  4066. exit->deactivate();
  4067. viewGrid->deactivate();
  4068. movementShadow->deactivate();
  4069. animSpeeds->deactivate();
  4070. mouseShadow->deactivate();
  4071. }
  4072. void CBattleOptionsWindow::show(SDL_Surface *to)
  4073. {
  4074. if(!to) //"evaluating" to
  4075. to = screen;
  4076. SDL_BlitSurface(background, NULL, to, &pos);
  4077. setToDefault->showAll(to);
  4078. exit->showAll(to);
  4079. viewGrid->showAll(to);
  4080. movementShadow->showAll(to);
  4081. animSpeeds->showAll(to);
  4082. mouseShadow->showAll(to);
  4083. }
  4084. void CBattleOptionsWindow::bDefaultf()
  4085. {
  4086. }
  4087. void CBattleOptionsWindow::bExitf()
  4088. {
  4089. GH.popIntTotally(this);
  4090. }
  4091. std::string CBattleInterface::SiegeHelper::townTypeInfixes[F_NUMBER] = {"CS", "RM", "TW", "IN", "NC", "DN", "ST", "FR", "EL"};
  4092. CBattleInterface::SiegeHelper::SiegeHelper(const CGTownInstance *siegeTown, const CBattleInterface * _owner)
  4093. : owner(_owner), town(siegeTown)
  4094. {
  4095. for(int g=0; g<ARRAY_COUNT(walls); ++g)
  4096. {
  4097. walls[g] = BitmapHandler::loadBitmap( getSiegeName(g) );
  4098. }
  4099. }
  4100. CBattleInterface::SiegeHelper::~SiegeHelper()
  4101. {
  4102. for(int g=0; g<ARRAY_COUNT(walls); ++g)
  4103. {
  4104. SDL_FreeSurface(walls[g]);
  4105. }
  4106. }
  4107. std::string CBattleInterface::SiegeHelper::getSiegeName(ui16 what, ui16 additInfo) const
  4108. {
  4109. if(what == 2 || what == 3 || what == 8)
  4110. {
  4111. if(additInfo == 3) additInfo = 2;
  4112. }
  4113. char buf[100];
  4114. SDL_itoa(additInfo, buf, 10);
  4115. std::string addit(buf);
  4116. switch(what)
  4117. {
  4118. case 0: //background
  4119. return "SG" + townTypeInfixes[town->town->typeID] + "BACK.BMP";
  4120. case 1: //background wall
  4121. {
  4122. switch(town->town->typeID)
  4123. {
  4124. case 5: case 4: case 1: case 6:
  4125. return "SG" + townTypeInfixes[town->town->typeID] + "TPW1.BMP";
  4126. case 0: case 2: case 3: case 7: case 8:
  4127. return "SG" + townTypeInfixes[town->town->typeID] + "TPWL.BMP";
  4128. default:
  4129. return "";
  4130. }
  4131. }
  4132. case 2: //keep
  4133. return "SG" + townTypeInfixes[town->town->typeID] + "MAN" + addit + ".BMP";
  4134. case 3: //bottom tower
  4135. return "SG" + townTypeInfixes[town->town->typeID] + "TW1" + addit + ".BMP";
  4136. case 4: //bottom wall
  4137. return "SG" + townTypeInfixes[town->town->typeID] + "WA1" + addit + ".BMP";
  4138. case 5: //below gate
  4139. return "SG" + townTypeInfixes[town->town->typeID] + "WA3" + addit + ".BMP";
  4140. case 6: //over gate
  4141. return "SG" + townTypeInfixes[town->town->typeID] + "WA4" + addit + ".BMP";
  4142. case 7: //upper wall
  4143. return "SG" + townTypeInfixes[town->town->typeID] + "WA6" + addit + ".BMP";
  4144. case 8: //upper tower
  4145. return "SG" + townTypeInfixes[town->town->typeID] + "TW2" + addit + ".BMP";
  4146. case 9: //gate
  4147. return "SG" + townTypeInfixes[town->town->typeID] + "DRW" + addit + ".BMP";
  4148. case 10: //gate arch
  4149. return "SG" + townTypeInfixes[town->town->typeID] + "ARCH.BMP";
  4150. case 11: //bottom static wall
  4151. return "SG" + townTypeInfixes[town->town->typeID] + "WA2.BMP";
  4152. case 12: //upper static wall
  4153. return "SG" + townTypeInfixes[town->town->typeID] + "WA5.BMP";
  4154. case 13: //moat
  4155. return "SG" + townTypeInfixes[town->town->typeID] + "MOAT.BMP";
  4156. case 14: //mlip
  4157. return "SG" + townTypeInfixes[town->town->typeID] + "MLIP.BMP";
  4158. case 15: //keep creature cover
  4159. return "SG" + townTypeInfixes[town->town->typeID] + "MANC.BMP";
  4160. case 16: //bottom turret creature cover
  4161. return "SG" + townTypeInfixes[town->town->typeID] + "TW1C.BMP";
  4162. case 17: //upper turret creature cover
  4163. return "SG" + townTypeInfixes[town->town->typeID] + "TW2C.BMP";
  4164. default:
  4165. return "";
  4166. }
  4167. }
  4168. /// What: 1. background wall, 2. keep, 3. bottom tower, 4. bottom wall, 5. wall below gate,
  4169. /// 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,
  4170. /// 15. keep turret cover, 16. lower turret cover, 17. upper turret cover
  4171. /// Positions are loaded from the config file: /config/wall_pos.txt
  4172. void CBattleInterface::SiegeHelper::printPartOfWall(SDL_Surface * to, int what)
  4173. {
  4174. Point pos = Point(-1, -1);
  4175. if (what >= 1 && what <= 17)
  4176. {
  4177. pos.x = graphics->wallPositions[town->town->typeID][what - 1].x + owner->pos.x;
  4178. pos.y = graphics->wallPositions[town->town->typeID][what - 1].y + owner->pos.y;
  4179. }
  4180. if(pos.x != -1)
  4181. {
  4182. blitAt(walls[what], pos.x, pos.y, to);
  4183. }
  4184. }
  4185. void CStackQueue::update()
  4186. {
  4187. stacksSorted.clear();
  4188. owner->curInt->cb->getStackQueue(stacksSorted, QUEUE_SIZE);
  4189. for (int i = 0; i < QUEUE_SIZE ; i++)
  4190. {
  4191. stackBoxes[i]->setStack(stacksSorted[i]);
  4192. }
  4193. }
  4194. CStackQueue::CStackQueue(bool Embedded, CBattleInterface * _owner)
  4195. :embedded(Embedded), owner(_owner)
  4196. {
  4197. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4198. if(embedded)
  4199. {
  4200. box = NULL;
  4201. bg = NULL;
  4202. pos.w = QUEUE_SIZE * 37;
  4203. pos.h = 32; //height of small creature img
  4204. pos.x = screen->w/2 - pos.w/2;
  4205. pos.y = (screen->h - 600)/2 + 10;
  4206. }
  4207. else
  4208. {
  4209. box = BitmapHandler::loadBitmap("CHRROP.pcx");
  4210. bg = BitmapHandler::loadBitmap("DIBOXPI.pcx");
  4211. pos.w = 600;
  4212. pos.h = bg->h;
  4213. }
  4214. stackBoxes.resize(QUEUE_SIZE);
  4215. for (int i = 0; i < QUEUE_SIZE; i++)
  4216. {
  4217. stackBoxes[i] = new StackBox(box);
  4218. stackBoxes[i]->pos.x += 6 + (embedded ? 37 : 79)*i;
  4219. }
  4220. }
  4221. CStackQueue::~CStackQueue()
  4222. {
  4223. SDL_FreeSurface(box);
  4224. }
  4225. void CStackQueue::showAll( SDL_Surface *to )
  4226. {
  4227. blitBg(to);
  4228. CIntObject::showAll(to);
  4229. }
  4230. void CStackQueue::blitBg( SDL_Surface * to )
  4231. {
  4232. if(bg)
  4233. {
  4234. for (int w = 0; w < pos.w; w += bg->w)
  4235. {
  4236. blitAtLoc(bg, w, 0, to);
  4237. }
  4238. }
  4239. }
  4240. void CStackQueue::StackBox::showAll( SDL_Surface *to )
  4241. {
  4242. assert(my);
  4243. if(bg)
  4244. {
  4245. graphics->blueToPlayersAdv(bg, my->owner);
  4246. //SDL_UpdateRect(bg, 0, 0, 0, 0);
  4247. SDL_Rect temp_rect = genRect(bg->h, bg->w, pos.x, pos.y);
  4248. CSDL_Ext::blit8bppAlphaTo24bpp(bg, NULL, to, &temp_rect);
  4249. //blitAt(bg, pos, to);
  4250. blitAt(graphics->bigImgs[my->getCreature()->idNumber], pos.x +9, pos.y + 1, to);
  4251. printAtMiddleLoc(makeNumberShort(my->count), pos.w/2, pos.h - 12, FONT_MEDIUM, zwykly, to);
  4252. }
  4253. else
  4254. {
  4255. blitAt(graphics->smallImgs[-2], pos, to);
  4256. blitAt(graphics->smallImgs[my->getCreature()->idNumber], pos, to);
  4257. const SDL_Color &ownerColor = (my->owner == 255 ? *graphics->neutralColor : graphics->playerColors[my->owner]);
  4258. CSDL_Ext::drawBorder(to, pos, int3(ownerColor.r, ownerColor.g, ownerColor.b));
  4259. printAtMiddleLoc(makeNumberShort(my->count), pos.w/2, pos.h - 8, FONT_TINY, zwykly, to);
  4260. }
  4261. }
  4262. void CStackQueue::StackBox::setStack( const CStack *nStack )
  4263. {
  4264. my = nStack;
  4265. }
  4266. CStackQueue::StackBox::StackBox(SDL_Surface *BG)
  4267. :my(NULL), bg(BG)
  4268. {
  4269. if(bg)
  4270. {
  4271. pos.w = bg->w;
  4272. pos.h = bg->h;
  4273. }
  4274. else
  4275. {
  4276. pos.w = pos.h = 32;
  4277. }
  4278. pos.y += 2;
  4279. }
  4280. CStackQueue::StackBox::~StackBox()
  4281. {
  4282. }
  4283. void CStackQueue::StackBox::hover( bool on )
  4284. {
  4285. }
  4286. double CatapultProjectileInfo::calculateY(double x)
  4287. {
  4288. return (facA * pow(10., -3.)) * pow(x, 2.0) + facB * x + facC;
  4289. }