CBattleInterface.cpp 147 KB

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