CBattleInterface.cpp 141 KB

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