CBattleInterface.cpp 146 KB

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