CBattleInterface.cpp 137 KB

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