CBattleInterface.cpp 139 KB

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