GUIClasses.cpp 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228
  1. #include "StdInc.h"
  2. #include "GUIClasses.h"
  3. #include "gui/SDL_Extensions.h"
  4. #include "CAdvmapInterface.h"
  5. #include "CBitmapHandler.h"
  6. #include "CDefHandler.h"
  7. #include "battle/CBattleInterface.h"
  8. #include "battle/CBattleInterfaceClasses.h"
  9. #include "../CCallback.h"
  10. #include "CCastleInterface.h"
  11. #include "CCreatureWindow.h"
  12. #include "gui/CCursorHandler.h"
  13. #include "CGameInfo.h"
  14. #include "CHeroWindow.h"
  15. #include "CMessage.h"
  16. #include "../lib/CConfigHandler.h"
  17. #include "battle/CCreatureAnimation.h"
  18. #include "CPlayerInterface.h"
  19. #include "Graphics.h"
  20. #include "CAnimation.h"
  21. #include "../lib/CArtHandler.h"
  22. #include "../lib/CBuildingHandler.h"
  23. #include "../lib/CGeneralTextHandler.h"
  24. #include "../lib/CHeroHandler.h"
  25. #include "../lib/CModHandler.h"
  26. #include "../lib/CSpellHandler.h"
  27. #include "../lib/CTownHandler.h"
  28. #include "../lib/CondSh.h"
  29. #include "../lib/mapping/CMap.h"
  30. #include "mapHandler.h"
  31. #include "../lib/CStopWatch.h"
  32. #include "../lib/NetPacksBase.h"
  33. #include "CSpellWindow.h"
  34. #include "CHeroWindow.h"
  35. #include "CVideoHandler.h"
  36. #include "../lib/StartInfo.h"
  37. #include "CPreGame.h"
  38. #include "../lib/HeroBonus.h"
  39. #include "../lib/CCreatureHandler.h"
  40. #include "CMusicHandler.h"
  41. #include "../lib/BattleState.h"
  42. #include "../lib/CGameState.h"
  43. #include "../lib/GameConstants.h"
  44. #include "gui/CGuiHandler.h"
  45. /*
  46. * GUIClasses.cpp, part of VCMI engine
  47. *
  48. * Authors: listed in file AUTHORS in main folder
  49. *
  50. * License: GNU General Public License v2.0 or later
  51. * Full text of license available in license.txt file, in main folder
  52. *
  53. */
  54. using namespace boost::assign;
  55. using namespace CSDL_Ext;
  56. extern std::queue<SDL_Event> events;
  57. extern boost::mutex eventsM;
  58. std::list<CFocusable*> CFocusable::focusables;
  59. CFocusable * CFocusable::inputWithFocus;
  60. #undef min
  61. #undef max
  62. void CArmyTooltip::init(const InfoAboutArmy &army)
  63. {
  64. OBJ_CONSTRUCTION_CAPTURING_ALL;
  65. new CLabel(66, 2, FONT_SMALL, TOPLEFT, Colors::WHITE, army.name);
  66. std::vector<Point> slotsPos;
  67. slotsPos.push_back(Point(36,73));
  68. slotsPos.push_back(Point(72,73));
  69. slotsPos.push_back(Point(108,73));
  70. slotsPos.push_back(Point(18,122));
  71. slotsPos.push_back(Point(54,122));
  72. slotsPos.push_back(Point(90,122));
  73. slotsPos.push_back(Point(126,122));
  74. for(auto & slot : army.army)
  75. {
  76. if(slot.first.getNum() >= GameConstants::ARMY_SIZE)
  77. {
  78. logGlobal->warnStream() << "Warning: " << army.name << " has stack in slot " << slot.first;
  79. continue;
  80. }
  81. new CAnimImage("CPRSMALL", slot.second.type->iconIndex, 0, slotsPos[slot.first.getNum()].x, slotsPos[slot.first.getNum()].y);
  82. std::string subtitle;
  83. if(army.army.isDetailed)
  84. subtitle = boost::lexical_cast<std::string>(slot.second.count);
  85. else
  86. {
  87. //if =0 - we have no information about stack size at all
  88. if (slot.second.count)
  89. subtitle = CGI->generaltexth->arraytxt[171 + 3*(slot.second.count)];
  90. }
  91. new CLabel(slotsPos[slot.first.getNum()].x + 17, slotsPos[slot.first.getNum()].y + 41, FONT_TINY, CENTER, Colors::WHITE, subtitle);
  92. }
  93. }
  94. CArmyTooltip::CArmyTooltip(Point pos, const InfoAboutArmy &army):
  95. CIntObject(0, pos)
  96. {
  97. init(army);
  98. }
  99. CArmyTooltip::CArmyTooltip(Point pos, const CArmedInstance * army):
  100. CIntObject(0, pos)
  101. {
  102. init(InfoAboutArmy(army, true));
  103. }
  104. void CHeroTooltip::init(const InfoAboutHero &hero)
  105. {
  106. OBJ_CONSTRUCTION_CAPTURING_ALL;
  107. new CAnimImage("PortraitsLarge", hero.portrait, 0, 3, 2);
  108. if(hero.details)
  109. {
  110. for (size_t i = 0; i < hero.details->primskills.size(); i++)
  111. new CLabel(75 + 28 * i, 58, FONT_SMALL, CENTER, Colors::WHITE,
  112. boost::lexical_cast<std::string>(hero.details->primskills[i]));
  113. new CLabel(158, 98, FONT_TINY, CENTER, Colors::WHITE,
  114. boost::lexical_cast<std::string>(hero.details->mana));
  115. new CAnimImage("IMRL22", hero.details->morale + 3, 0, 5, 74);
  116. new CAnimImage("ILCK22", hero.details->luck + 3, 0, 5, 91);
  117. }
  118. }
  119. CHeroTooltip::CHeroTooltip(Point pos, const InfoAboutHero &hero):
  120. CArmyTooltip(pos, hero)
  121. {
  122. init(hero);
  123. }
  124. CHeroTooltip::CHeroTooltip(Point pos, const CGHeroInstance * hero):
  125. CArmyTooltip(pos, InfoAboutHero(hero, true))
  126. {
  127. init(InfoAboutHero(hero, true));
  128. }
  129. void CTownTooltip::init(const InfoAboutTown &town)
  130. {
  131. OBJ_CONSTRUCTION_CAPTURING_ALL;
  132. //order of icons in def: fort, citadel, castle, no fort
  133. size_t fortIndex = town.fortLevel ? town.fortLevel - 1 : 3;
  134. new CAnimImage("ITMCLS", fortIndex, 0, 105, 31);
  135. assert(town.tType);
  136. size_t iconIndex = town.tType->clientInfo.icons[town.fortLevel > 0][town.built >= CGI->modh->settings.MAX_BUILDING_PER_TURN];
  137. new CAnimImage("itpt", iconIndex, 0, 3, 2);
  138. if(town.details)
  139. {
  140. new CAnimImage("ITMTLS", town.details->hallLevel, 0, 67, 31);
  141. if (town.details->goldIncome)
  142. new CLabel(157, 58, FONT_TINY, CENTER, Colors::WHITE,
  143. boost::lexical_cast<std::string>(town.details->goldIncome));
  144. if(town.details->garrisonedHero) //garrisoned hero icon
  145. new CPicture("TOWNQKGH", 149, 76);
  146. if(town.details->customRes)//silo is built
  147. {
  148. if (town.tType->primaryRes == Res::WOOD_AND_ORE )// wood & ore
  149. {
  150. new CAnimImage("SMALRES", Res::WOOD, 0, 7, 75);
  151. new CAnimImage("SMALRES", Res::ORE , 0, 7, 88);
  152. }
  153. else
  154. new CAnimImage("SMALRES", town.tType->primaryRes, 0, 7, 81);
  155. }
  156. }
  157. }
  158. CTownTooltip::CTownTooltip(Point pos, const InfoAboutTown &town):
  159. CArmyTooltip(pos, town)
  160. {
  161. init(town);
  162. }
  163. CTownTooltip::CTownTooltip(Point pos, const CGTownInstance * town):
  164. CArmyTooltip(pos, InfoAboutTown(town, true))
  165. {
  166. init(InfoAboutTown(town, true));
  167. }
  168. void CGarrisonSlot::setHighlight(bool on)
  169. {
  170. if (on)
  171. selectionImage->enable(); //show
  172. else
  173. selectionImage->disable(); //hide
  174. }
  175. void CGarrisonSlot::hover (bool on)
  176. {
  177. ////Hoverable::hover(on);
  178. if(on)
  179. {
  180. std::string temp;
  181. if(creature)
  182. {
  183. if(owner->getSelection())
  184. {
  185. if(owner->getSelection() == this)
  186. {
  187. temp = CGI->generaltexth->tcommands[4]; //View %s
  188. boost::algorithm::replace_first(temp,"%s",creature->nameSing);
  189. }
  190. else if (owner->getSelection()->creature == creature)
  191. {
  192. temp = CGI->generaltexth->tcommands[2]; //Combine %s armies
  193. boost::algorithm::replace_first(temp,"%s",creature->nameSing);
  194. }
  195. else if (owner->getSelection()->creature)
  196. {
  197. temp = CGI->generaltexth->tcommands[7]; //Exchange %s with %s
  198. boost::algorithm::replace_first(temp,"%s",owner->getSelection()->creature->nameSing);
  199. boost::algorithm::replace_first(temp,"%s",creature->nameSing);
  200. }
  201. else
  202. {
  203. logGlobal->warnStream() << "Warning - shouldn't be - highlighted void slot "<<owner->getSelection();
  204. logGlobal->warnStream() << "Highlighted set to nullptr";
  205. owner->selectSlot(nullptr);
  206. }
  207. }
  208. else
  209. {
  210. if(upg)
  211. {
  212. temp = CGI->generaltexth->tcommands[32]; //Select %s (visiting)
  213. }
  214. else if(owner->armedObjs[0] && owner->armedObjs[0]->ID == Obj::TOWN)
  215. {
  216. temp = CGI->generaltexth->tcommands[12]; //Select %s (in garrison)
  217. }
  218. else
  219. {
  220. temp = CGI->generaltexth->allTexts[481]; //Select %s
  221. }
  222. boost::algorithm::replace_first(temp,"%s",creature->nameSing);
  223. };
  224. }
  225. else
  226. {
  227. if(owner->getSelection())
  228. {
  229. const CArmedInstance *highl = owner->getSelection()->getObj();
  230. if( highl->needsLastStack() //we are moving stack from hero's
  231. && highl->stacksCount() == 1 //it's only stack
  232. && owner->getSelection()->upg != upg //we're moving it to the other garrison
  233. )
  234. {
  235. temp = CGI->generaltexth->tcommands[5]; //Cannot move last army to garrison
  236. }
  237. else
  238. {
  239. temp = CGI->generaltexth->tcommands[6]; //Move %s
  240. boost::algorithm::replace_first(temp,"%s",owner->getSelection()->creature->nameSing);
  241. }
  242. }
  243. else
  244. {
  245. temp = CGI->generaltexth->tcommands[11]; //Empty
  246. }
  247. }
  248. GH.statusbar->setText(temp);
  249. }
  250. else
  251. {
  252. GH.statusbar->clear();
  253. }
  254. }
  255. const CArmedInstance * CGarrisonSlot::getObj() const
  256. {
  257. return (!upg)?(owner->armedObjs[0]):(owner->armedObjs[1]);
  258. }
  259. bool CGarrisonSlot::our() const
  260. {
  261. return upg?(owner->owned[1]):(owner->owned[0]);
  262. }
  263. void CGarrisonSlot::clickRight(tribool down, bool previousState)
  264. {
  265. if(down && creature)
  266. {
  267. GH.pushInt(new CStackWindow(creature, true));
  268. }
  269. }
  270. void CGarrisonSlot::clickLeft(tribool down, bool previousState)
  271. {
  272. if(down)
  273. {
  274. bool refr = false;
  275. if(owner->getSelection())
  276. {
  277. if(owner->getSelection() == this) //view info
  278. {
  279. UpgradeInfo pom;
  280. LOCPLINT->cb->getUpgradeInfo(getObj(), ID, pom);
  281. bool canUpgrade = getObj()->tempOwner == LOCPLINT->playerID && pom.oldID>=0; //upgrade is possible
  282. bool canDismiss = getObj()->tempOwner == LOCPLINT->playerID && (getObj()->stacksCount()>1 || !getObj()->needsLastStack());
  283. std::function<void(CreatureID)> upgr = nullptr;
  284. std::function<void()> dism = nullptr;
  285. if(canUpgrade) upgr = [=] (CreatureID newID) { LOCPLINT->cb->upgradeCreature(getObj(), ID, newID); };
  286. if(canDismiss) dism = [=] { LOCPLINT->cb->dismissCreature(getObj(), ID); };
  287. owner->selectSlot(nullptr);
  288. owner->setSplittingMode(false);
  289. for(auto & elem : owner->splitButtons)
  290. elem->block(true);
  291. redraw();
  292. refr = true;
  293. GH.pushInt(new CStackWindow(myStack, dism, pom, upgr));
  294. }
  295. else
  296. {
  297. // Only allow certain moves if troops aren't removable or not ours.
  298. if ( ( owner->getSelection()->our()//our creature is selected
  299. || owner->getSelection()->creature == creature )//or we are rebalancing army
  300. && ( owner->removableUnits
  301. || (upg == 0 && ( owner->getSelection()->upg == 1 && !creature ) )
  302. || (upg == 1 && owner->getSelection()->upg == 1 ) ) )
  303. {
  304. //we want to split
  305. if((owner->getSplittingMode() || LOCPLINT->shiftPressed())
  306. && (!creature
  307. || (creature == owner->getSelection()->creature)))
  308. {
  309. owner->p2 = ID; //store the second stack pos
  310. owner->pb = upg;//store the second stack owner (up or down army)
  311. owner->setSplittingMode(false);
  312. int minLeft=0, minRight=0;
  313. if(upg != owner->getSelection()->upg) //not splitting within same army
  314. {
  315. if(owner->getSelection()->getObj()->stacksCount() == 1 //we're splitting away the last stack
  316. && owner->getSelection()->getObj()->needsLastStack() )
  317. {
  318. minLeft = 1;
  319. }
  320. if(getObj()->stacksCount() == 1 //destination army can't be emptied, unless we're rebalancing two stacks of same creature
  321. && owner->getSelection()->creature == creature
  322. && getObj()->needsLastStack() )
  323. {
  324. minRight = 1;
  325. }
  326. }
  327. int countLeft = owner->getSelection()->myStack ? owner->getSelection()->myStack->count : 0;
  328. int countRight = myStack ? myStack->count : 0;
  329. GH.pushInt(new CSplitWindow(owner->getSelection()->creature, boost::bind(&CGarrisonInt::splitStacks, owner, _1, _2),
  330. minLeft, minRight, countLeft, countRight));
  331. refr = true;
  332. }
  333. else if(creature != owner->getSelection()->creature) //swap
  334. {
  335. LOCPLINT->cb->swapCreatures(
  336. (!upg)?(owner->armedObjs[0]):(owner->armedObjs[1]),
  337. (!owner->getSelection()->upg)?(owner->armedObjs[0]):(owner->armedObjs[1]),
  338. ID,owner->getSelection()->ID);
  339. }
  340. else //merge
  341. {
  342. LOCPLINT->cb->mergeStacks(
  343. (!owner->getSelection()->upg)?(owner->armedObjs[0]):(owner->armedObjs[1]),
  344. (!upg)?(owner->armedObjs[0]):(owner->armedObjs[1]),
  345. owner->getSelection()->ID,ID);
  346. }
  347. }
  348. else // Highlight
  349. {
  350. if(creature)
  351. owner->selectSlot(this);
  352. redraw();
  353. refr = true;
  354. }
  355. }
  356. }
  357. else //highlight or drop artifact
  358. {
  359. bool artSelected = false;
  360. if (CWindowWithArtifacts* chw = dynamic_cast<CWindowWithArtifacts*>(GH.topInt())) //dirty solution
  361. {
  362. const CArtifactsOfHero::SCommonPart *commonInfo = chw->artSets.front()->commonInfo;
  363. if (const CArtifactInstance *art = commonInfo->src.art)
  364. {
  365. const CGHeroInstance *srcHero = commonInfo->src.AOH->getHero();
  366. artSelected = true;
  367. ArtifactLocation src(srcHero, commonInfo->src.slotID);
  368. ArtifactLocation dst(myStack, ArtifactPosition::CREATURE_SLOT);
  369. if (art->canBePutAt(dst, true))
  370. { //equip clicked stack
  371. if(dst.getArt())
  372. {
  373. //creature can wear only one active artifact
  374. //if we are placing a new one, the old one will be returned to the hero's backpack
  375. LOCPLINT->cb->swapArtifacts(dst, ArtifactLocation(srcHero, dst.getArt()->firstBackpackSlot(srcHero)));
  376. }
  377. LOCPLINT->cb->swapArtifacts(src, dst);
  378. }
  379. }
  380. }
  381. if (!artSelected && creature)
  382. {
  383. owner->selectSlot(this);
  384. if(creature)
  385. {
  386. for(auto & elem : owner->splitButtons)
  387. elem->block(false);
  388. }
  389. }
  390. redraw();
  391. refr = true;
  392. }
  393. if(refr) {hover(false); hover(true); } //to refresh statusbar
  394. }
  395. }
  396. void CGarrisonSlot::update()
  397. {
  398. if (getObj() != nullptr)
  399. {
  400. addUsedEvents(LCLICK | RCLICK | HOVER);
  401. myStack = getObj()->getStackPtr(ID);
  402. creature = myStack ? myStack->type : nullptr;
  403. }
  404. else
  405. {
  406. removeUsedEvents(LCLICK | RCLICK | HOVER);
  407. myStack = nullptr;
  408. creature = nullptr;
  409. }
  410. if (creature)
  411. {
  412. creatureImage->enable();
  413. creatureImage->setFrame(creature->iconIndex);
  414. stackCount->enable();
  415. stackCount->setText(boost::lexical_cast<std::string>(myStack->count));
  416. }
  417. else
  418. {
  419. creatureImage->disable();
  420. stackCount->disable();
  421. }
  422. }
  423. CGarrisonSlot::CGarrisonSlot(CGarrisonInt *Owner, int x, int y, SlotID IID, int Upg, const CStackInstance * Creature):
  424. ID(IID),
  425. owner(Owner),
  426. myStack(Creature),
  427. creature(Creature ? Creature->type : nullptr),
  428. upg(Upg)
  429. {
  430. OBJ_CONSTRUCTION_CAPTURING_ALL;
  431. if (getObj())
  432. addUsedEvents(LCLICK | RCLICK | HOVER);
  433. pos.x += x;
  434. pos.y += y;
  435. std::string imgName = owner->smallIcons ? "cprsmall" : "TWCRPORT";
  436. creatureImage = new CAnimImage(imgName, creature ? creature->iconIndex : 0);
  437. if (!creature)
  438. creatureImage->disable();
  439. selectionImage = new CAnimImage(imgName, 1);
  440. selectionImage->disable();
  441. if(Owner->smallIcons)
  442. {
  443. pos.w = 32;
  444. pos.h = 32;
  445. }
  446. else
  447. {
  448. pos.w = 58;
  449. pos.h = 64;
  450. }
  451. stackCount = new CLabel(pos.w, pos.h, owner->smallIcons ? FONT_TINY : FONT_MEDIUM, BOTTOMRIGHT, Colors::WHITE);
  452. if (!creature)
  453. stackCount->disable();
  454. else
  455. stackCount->setText(boost::lexical_cast<std::string>(myStack->count));
  456. }
  457. void CGarrisonInt::addSplitBtn(CAdventureMapButton * button)
  458. {
  459. addChild(button);
  460. button->recActions = defActions;
  461. splitButtons.push_back(button);
  462. button->block(getSelection() == nullptr);
  463. }
  464. void CGarrisonInt::createSet(std::vector<CGarrisonSlot*> &ret, const CCreatureSet * set, int posX, int posY, int distance, int Upg )
  465. {
  466. ret.resize(7);
  467. if (set)
  468. {
  469. for(auto & elem : set->Slots())
  470. {
  471. ret[elem.first.getNum()] = new CGarrisonSlot(this, posX + (elem.first.getNum()*distance), posY, elem.first, Upg, elem.second);
  472. }
  473. }
  474. for(int i=0; i<ret.size(); i++)
  475. if(!ret[i])
  476. ret[i] = new CGarrisonSlot(this, posX + (i*distance), posY, SlotID(i), Upg, nullptr);
  477. if (twoRows)
  478. for (int i=4; i<ret.size(); i++)
  479. {
  480. ret[i]->pos.x -= 126;
  481. ret[i]->pos.y += 37;
  482. };
  483. }
  484. void CGarrisonInt::createSlots()
  485. {
  486. OBJ_CONSTRUCTION_CAPTURING_ALL;
  487. int width = smallIcons? 32 : 58;
  488. createSet(slotsUp, armedObjs[0], 0, 0, width+interx, 0);
  489. createSet(slotsDown, armedObjs[1], garOffset.x, garOffset.y, width+interx, 1);
  490. }
  491. void CGarrisonInt::recreateSlots()
  492. {
  493. selectSlot(nullptr);
  494. setSplittingMode(false);
  495. for(auto & elem : splitButtons)
  496. elem->block(true);
  497. for(CGarrisonSlot * slot : slotsUp)
  498. slot->update();
  499. for(CGarrisonSlot * slot : slotsDown)
  500. slot->update();
  501. }
  502. void CGarrisonInt::splitClick()
  503. {
  504. if(!getSelection())
  505. return;
  506. setSplittingMode(!getSplittingMode());
  507. redraw();
  508. }
  509. void CGarrisonInt::splitStacks(int, int amountRight)
  510. {
  511. LOCPLINT->cb->splitStack(armedObjs[getSelection()->upg], armedObjs[pb], getSelection()->ID, p2, amountRight);
  512. }
  513. CGarrisonInt::CGarrisonInt(int x, int y, int inx, const Point &garsOffset,
  514. SDL_Surface *pomsur, const Point& SurOffset,
  515. const CArmedInstance *s1, const CArmedInstance *s2,
  516. bool _removableUnits, bool smallImgs, bool _twoRows ) :
  517. highlighted(nullptr),
  518. inSplittingMode(false),
  519. interx(inx),
  520. garOffset(garsOffset),
  521. smallIcons(smallImgs),
  522. removableUnits(_removableUnits),
  523. twoRows(_twoRows)
  524. {
  525. setArmy(s1, false);
  526. setArmy(s2, true);
  527. pos.x += x;
  528. pos.y += y;
  529. createSlots();
  530. }
  531. const CGarrisonSlot * CGarrisonInt::getSelection()
  532. {
  533. return highlighted;
  534. }
  535. void CGarrisonInt::selectSlot(CGarrisonSlot *slot)
  536. {
  537. if (slot != highlighted)
  538. {
  539. if (highlighted)
  540. highlighted->setHighlight(false);
  541. highlighted = slot;
  542. for (auto button : splitButtons)
  543. button->block(highlighted == nullptr);
  544. if (highlighted)
  545. highlighted->setHighlight(true);
  546. }
  547. }
  548. void CGarrisonInt::setSplittingMode(bool on)
  549. {
  550. assert(on == false || highlighted != nullptr); //can't be in splitting mode without selection
  551. if (inSplittingMode || on)
  552. {
  553. for(CGarrisonSlot * slot : slotsUp)
  554. slot->setHighlight( ( on && (slot->creature == nullptr || slot->creature == getSelection()->creature)));
  555. for(CGarrisonSlot * slot : slotsDown)
  556. slot->setHighlight( ( on && (slot->creature == nullptr || slot->creature == getSelection()->creature)));
  557. inSplittingMode = on;
  558. }
  559. }
  560. bool CGarrisonInt::getSplittingMode()
  561. {
  562. return inSplittingMode;
  563. }
  564. void CGarrisonInt::setArmy(const CArmedInstance *army, bool bottomGarrison)
  565. {
  566. owned[bottomGarrison] = army ? (army->tempOwner == LOCPLINT->playerID || army->tempOwner == PlayerColor::UNFLAGGABLE) : false;
  567. armedObjs[bottomGarrison] = army;
  568. }
  569. CInfoWindow::CInfoWindow(std::string Text, PlayerColor player, const TCompsInfo &comps, const TButtonsInfo &Buttons, bool delComps)
  570. {
  571. OBJ_CONSTRUCTION_CAPTURING_ALL;
  572. type |= BLOCK_ADV_HOTKEYS;
  573. ID = QueryID(-1);
  574. for(auto & Button : Buttons)
  575. {
  576. CAdventureMapButton *button = new CAdventureMapButton("","",boost::bind(&CInfoWindow::close,this),0,0,Button.first);
  577. button->borderColor = Colors::METALLIC_GOLD;
  578. button->borderEnabled = true;
  579. button->callback.add(Button.second); //each button will close the window apart from call-defined actions
  580. buttons.push_back(button);
  581. }
  582. text = new CTextBox(Text, Rect(0, 0, 250, 100), 0, FONT_MEDIUM, CENTER, Colors::WHITE);
  583. if(!text->slider)
  584. {
  585. text->resize(text->label->textSize);
  586. }
  587. if(buttons.size())
  588. {
  589. buttons.front()->assignedKeys.insert(SDLK_RETURN); //first button - reacts on enter
  590. buttons.back()->assignedKeys.insert(SDLK_ESCAPE); //last button - reacts on escape
  591. }
  592. for(auto & comp : comps)
  593. {
  594. comp->recActions = 0xff;
  595. addChild(comp);
  596. comp->recActions &= ~(SHOWALL | UPDATE);
  597. components.push_back(comp);
  598. }
  599. setDelComps(delComps);
  600. CMessage::drawIWindow(this,Text,player);
  601. }
  602. CInfoWindow::CInfoWindow()
  603. {
  604. ID = QueryID(-1);
  605. setDelComps(false);
  606. text = nullptr;
  607. }
  608. void CInfoWindow::close()
  609. {
  610. GH.popIntTotally(this);
  611. if(LOCPLINT)
  612. LOCPLINT->showingDialog->setn(false);
  613. }
  614. void CInfoWindow::show(SDL_Surface * to)
  615. {
  616. CIntObject::show(to);
  617. }
  618. CInfoWindow::~CInfoWindow()
  619. {
  620. if(!delComps)
  621. {
  622. for (auto & elem : components)
  623. removeChild(elem);
  624. }
  625. }
  626. void CInfoWindow::showAll(SDL_Surface * to)
  627. {
  628. CSimpleWindow::show(to);
  629. CIntObject::showAll(to);
  630. }
  631. void CInfoWindow::showInfoDialog(const std::string &text, const std::vector<CComponent *> *components, bool DelComps, PlayerColor player)
  632. {
  633. CInfoWindow * window = CInfoWindow::create(text, player, components, DelComps);
  634. GH.pushInt(window);
  635. }
  636. void CInfoWindow::showYesNoDialog(const std::string & text, const std::vector<CComponent*> *components, const CFunctionList<void( ) > &onYes, const CFunctionList<void()> &onNo, bool DelComps, PlayerColor player)
  637. {
  638. assert(!LOCPLINT || LOCPLINT->showingDialog->get());
  639. std::vector<std::pair<std::string,CFunctionList<void()> > > pom;
  640. pom.push_back(std::pair<std::string,CFunctionList<void()> >("IOKAY.DEF",0));
  641. pom.push_back(std::pair<std::string,CFunctionList<void()> >("ICANCEL.DEF",0));
  642. CInfoWindow * temp = new CInfoWindow(text, player, components ? *components : std::vector<CComponent*>(), pom, DelComps);
  643. for(auto & elem : onYes.funcs)
  644. temp->buttons[0]->callback += elem;
  645. for(auto & elem : onNo.funcs)
  646. temp->buttons[1]->callback += elem;
  647. GH.pushInt(temp);
  648. }
  649. void CInfoWindow::showOkDialog(const std::string & text, const std::vector<CComponent*> *components, const boost::function<void()> & onOk, bool delComps, PlayerColor player)
  650. {
  651. std::vector<std::pair<std::string,CFunctionList<void()> > > pom;
  652. pom.push_back(std::pair<std::string,CFunctionList<void()> >("IOKAY.DEF",0));
  653. CInfoWindow * temp = new CInfoWindow(text, player, *components, pom, delComps);
  654. temp->buttons[0]->callback += onOk;
  655. GH.pushInt(temp);
  656. }
  657. CInfoWindow * CInfoWindow::create(const std::string &text, PlayerColor playerID /*= 1*/, const std::vector<CComponent*> *components /*= nullptr*/, bool DelComps)
  658. {
  659. std::vector<std::pair<std::string,CFunctionList<void()> > > pom;
  660. pom.push_back(std::pair<std::string,CFunctionList<void()> >("IOKAY.DEF",0));
  661. CInfoWindow * ret = new CInfoWindow(text, playerID, components ? *components : std::vector<CComponent*>(), pom, DelComps);
  662. return ret;
  663. }
  664. std::string CInfoWindow::genText(std::string title, std::string description)
  665. {
  666. return std::string("{") + title + "}" + "\n\n" + description;
  667. }
  668. void CInfoWindow::setDelComps(bool DelComps)
  669. {
  670. delComps = DelComps;
  671. for(CComponent *comp : components)
  672. {
  673. if(delComps)
  674. comp->recActions |= DISPOSE;
  675. else
  676. comp->recActions &= ~DISPOSE;
  677. }
  678. }
  679. CInfoPopup::CInfoPopup(SDL_Surface * Bitmap, int x, int y, bool Free)
  680. :free(Free),bitmap(Bitmap)
  681. {
  682. init(x, y);
  683. }
  684. CInfoPopup::CInfoPopup(SDL_Surface * Bitmap, const Point &p, EAlignment alignment, bool Free/*=false*/)
  685. : free(Free),bitmap(Bitmap)
  686. {
  687. switch(alignment)
  688. {
  689. case BOTTOMRIGHT:
  690. init(p.x - Bitmap->w, p.y - Bitmap->h);
  691. break;
  692. case CENTER:
  693. init(p.x - Bitmap->w/2, p.y - Bitmap->h/2);
  694. break;
  695. case TOPLEFT:
  696. init(p.x, p.y);
  697. break;
  698. default:
  699. assert(0); //not implemented
  700. }
  701. }
  702. CInfoPopup::CInfoPopup(SDL_Surface *Bitmap, bool Free)
  703. {
  704. CCS->curh->hide();
  705. free=Free;
  706. bitmap=Bitmap;
  707. if(bitmap)
  708. {
  709. pos.x = screen->w/2 - bitmap->w/2;
  710. pos.y = screen->h/2 - bitmap->h/2;
  711. pos.h = bitmap->h;
  712. pos.w = bitmap->w;
  713. }
  714. }
  715. void CInfoPopup::close()
  716. {
  717. if(free)
  718. SDL_FreeSurface(bitmap);
  719. GH.popIntTotally(this);
  720. }
  721. void CInfoPopup::show(SDL_Surface * to)
  722. {
  723. blitAt(bitmap,pos.x,pos.y,to);
  724. }
  725. CInfoPopup::~CInfoPopup()
  726. {
  727. CCS->curh->show();
  728. }
  729. void CInfoPopup::init(int x, int y)
  730. {
  731. CCS->curh->hide();
  732. pos.x = x;
  733. pos.y = y;
  734. pos.h = bitmap->h;
  735. pos.w = bitmap->w;
  736. // Put the window back on screen if necessary
  737. vstd::amax(pos.x, 0);
  738. vstd::amax(pos.y, 0);
  739. vstd::amin(pos.x, screen->w - bitmap->w);
  740. vstd::amin(pos.y, screen->h - bitmap->h);
  741. }
  742. CComponent::CComponent(Etype Type, int Subtype, int Val, ESize imageSize):
  743. image(nullptr),
  744. perDay(false)
  745. {
  746. addUsedEvents(RCLICK);
  747. init(Type, Subtype, Val, imageSize);
  748. }
  749. CComponent::CComponent(const Component &c):
  750. image(nullptr),
  751. perDay(false)
  752. {
  753. addUsedEvents(RCLICK);
  754. if(c.id == Component::RESOURCE && c.when==-1)
  755. perDay = true;
  756. init((Etype)c.id,c.subtype,c.val, large);
  757. }
  758. void CComponent::init(Etype Type, int Subtype, int Val, ESize imageSize)
  759. {
  760. OBJ_CONSTRUCTION_CAPTURING_ALL;
  761. compType = Type;
  762. subtype = Subtype;
  763. val = Val;
  764. size = imageSize;
  765. assert(compType < typeInvalid);
  766. assert(size < sizeInvalid);
  767. setSurface(getFileName()[size], getIndex());
  768. pos.w = image->pos.w;
  769. pos.h = image->pos.h;
  770. EFonts font = FONT_SMALL;
  771. if (imageSize < small)
  772. font = FONT_TINY; //other sizes?
  773. pos.h += 4; //distance between text and image
  774. std::vector<std::string> textLines = CMessage::breakText(getSubtitle(), std::max<int>(80, pos.w), font);
  775. for(auto & line : textLines)
  776. {
  777. int height = graphics->fonts[font]->getLineHeight();
  778. auto label = new CLabel(pos.w/2, pos.h + height/2, font, CENTER, Colors::WHITE, line);
  779. pos.h += height;
  780. if (label->pos.w > pos.w)
  781. {
  782. pos.x -= (label->pos.w - pos.w)/2;
  783. pos.w = label->pos.w;
  784. }
  785. }
  786. }
  787. const std::vector<std::string> CComponent::getFileName()
  788. {
  789. static const std::string primSkillsArr [] = {"PSKIL32", "PSKIL32", "PSKIL42", "PSKILL"};
  790. static const std::string secSkillsArr [] = {"SECSK32", "SECSK32", "SECSKILL", "SECSK82"};
  791. static const std::string resourceArr [] = {"SMALRES", "RESOURCE", "RESOUR82", "RESOUR82"};
  792. static const std::string creatureArr [] = {"CPRSMALL", "CPRSMALL", "TWCRPORT", "TWCRPORT"};
  793. static const std::string artifactArr[] = {"Artifact", "Artifact", "Artifact", "Artifact"};
  794. static const std::string spellsArr [] = {"SpellInt", "SpellInt", "SPELLSCR", "SPELLSCR"};
  795. static const std::string moraleArr [] = {"IMRL22", "IMRL30", "IMRL42", "imrl82"};
  796. static const std::string luckArr [] = {"ILCK22", "ILCK30", "ILCK42", "ilck82"};
  797. static const std::string heroArr [] = {"PortraitsSmall", "PortraitsSmall", "PortraitsLarge", "PortraitsLarge"};
  798. static const std::string flagArr [] = {"CREST58", "CREST58", "CREST58", "CREST58"};
  799. auto gen = [](const std::string * arr)
  800. {
  801. return std::vector<std::string>(arr, arr + 4);
  802. };
  803. switch(compType)
  804. {
  805. case primskill: return gen(primSkillsArr);
  806. case secskill: return gen(secSkillsArr);
  807. case resource: return gen(resourceArr);
  808. case creature: return gen(creatureArr);
  809. case artifact: return gen(artifactArr);
  810. case experience: return gen(primSkillsArr);
  811. case spell: return gen(spellsArr);
  812. case morale: return gen(moraleArr);
  813. case luck: return gen(luckArr);
  814. case building: return std::vector<std::string>(4, CGI->townh->factions[subtype]->town->clientInfo.buildingsIcons);
  815. case hero: return gen(heroArr);
  816. case flag: return gen(flagArr);
  817. }
  818. assert(0);
  819. return std::vector<std::string>();
  820. }
  821. size_t CComponent::getIndex()
  822. {
  823. switch(compType)
  824. {
  825. case primskill: return subtype;
  826. case secskill: return subtype*3 + 3 + val - 1;
  827. case resource: return subtype;
  828. case creature: return CGI->creh->creatures[subtype]->iconIndex;
  829. case artifact: return CGI->arth->artifacts[subtype]->iconIndex;
  830. case experience: return 4;
  831. case spell: return subtype;
  832. case morale: return val+3;
  833. case luck: return val+3;
  834. case building: return val;
  835. case hero: return subtype;
  836. case flag: return subtype;
  837. }
  838. assert(0);
  839. return 0;
  840. }
  841. std::string CComponent::getDescription()
  842. {
  843. switch (compType)
  844. {
  845. case primskill: return (subtype < 4)? CGI->generaltexth->arraytxt[2+subtype] //Primary skill
  846. : CGI->generaltexth->allTexts[149]; //mana
  847. case secskill: return CGI->generaltexth->skillInfoTexts[subtype][val-1];
  848. case resource: return CGI->generaltexth->allTexts[242];
  849. case creature: return "";
  850. case artifact: return CGI->arth->artifacts[subtype]->Description();
  851. case experience: return CGI->generaltexth->allTexts[241];
  852. case spell: return CGI->spellh->objects[subtype]->getLevelInfo(val).description;
  853. case morale: return CGI->generaltexth->heroscrn[ 4 - (val>0) + (val<0)];
  854. case luck: return CGI->generaltexth->heroscrn[ 7 - (val>0) + (val<0)];
  855. case building: return CGI->townh->factions[subtype]->town->buildings[BuildingID(val)]->Description();
  856. case hero: return "";
  857. case flag: return "";
  858. }
  859. assert(0);
  860. return "";
  861. }
  862. std::string CComponent::getSubtitle()
  863. {
  864. if (!perDay)
  865. return getSubtitleInternal();
  866. std::string ret = CGI->generaltexth->allTexts[3];
  867. boost::replace_first(ret, "%d", getSubtitleInternal());
  868. return ret;
  869. }
  870. std::string CComponent::getSubtitleInternal()
  871. {
  872. //FIXME: some of these are horrible (e.g creature)
  873. switch(compType)
  874. {
  875. case primskill: return boost::str(boost::format("%+d %s") % val % (subtype < 4 ? CGI->generaltexth->primarySkillNames[subtype] : CGI->generaltexth->allTexts[387]));
  876. case secskill: return CGI->generaltexth->levels[val-1] + "\n" + CGI->generaltexth->skillName[subtype];
  877. case resource: return boost::lexical_cast<std::string>(val);
  878. case creature: return (val? boost::lexical_cast<std::string>(val) + " " : "") + CGI->creh->creatures[subtype]->*(val != 1 ? &CCreature::namePl : &CCreature::nameSing);
  879. case artifact: return CGI->arth->artifacts[subtype]->Name();
  880. case experience:
  881. {
  882. if (subtype == 1) //+1 level - tree of knowledge
  883. {
  884. std::string level = CGI->generaltexth->allTexts[442];
  885. boost::replace_first(level, "1", boost::lexical_cast<std::string>(val));
  886. return level;
  887. }
  888. else
  889. return boost::lexical_cast<std::string>(val); //amount of experience OR level required for seer hut;
  890. }
  891. case spell: return CGI->spellh->objects[subtype]->name;
  892. case morale: return "";
  893. case luck: return "";
  894. case building: return CGI->townh->factions[subtype]->town->buildings[BuildingID(val)]->Name();
  895. case hero: return "";
  896. case flag: return CGI->generaltexth->capColors[subtype];
  897. }
  898. assert(0);
  899. return "";
  900. }
  901. void CComponent::setSurface(std::string defName, int imgPos)
  902. {
  903. OBJ_CONSTRUCTION_CAPTURING_ALL;
  904. vstd::clear_pointer(image);
  905. image = new CAnimImage(defName, imgPos);
  906. }
  907. void CComponent::clickRight(tribool down, bool previousState)
  908. {
  909. if(!getDescription().empty())
  910. adventureInt->handleRightClick(getDescription(), down);
  911. }
  912. void CSelectableComponent::clickLeft(tribool down, bool previousState)
  913. {
  914. if (down)
  915. {
  916. if(onSelect)
  917. onSelect();
  918. }
  919. }
  920. void CSelectableComponent::init()
  921. {
  922. selected = false;
  923. }
  924. CSelectableComponent::CSelectableComponent(const Component &c, std::function<void()> OnSelect):
  925. CComponent(c),onSelect(OnSelect)
  926. {
  927. type |= REDRAW_PARENT;
  928. addUsedEvents(LCLICK | KEYBOARD);
  929. init();
  930. }
  931. CSelectableComponent::CSelectableComponent(Etype Type, int Sub, int Val, ESize imageSize, std::function<void()> OnSelect):
  932. CComponent(Type,Sub,Val, imageSize),onSelect(OnSelect)
  933. {
  934. type |= REDRAW_PARENT;
  935. addUsedEvents(LCLICK | KEYBOARD);
  936. init();
  937. }
  938. void CSelectableComponent::select(bool on)
  939. {
  940. if(on != selected)
  941. {
  942. selected = on;
  943. redraw();
  944. }
  945. }
  946. void CSelectableComponent::showAll(SDL_Surface * to)
  947. {
  948. CComponent::showAll(to);
  949. if(selected)
  950. {
  951. CSDL_Ext::drawBorder(to, Rect::around(image->pos), int3(239,215,123));
  952. }
  953. }
  954. void CComponentBox::selectionChanged(CSelectableComponent * newSelection)
  955. {
  956. if (newSelection == selected)
  957. return;
  958. if (selected)
  959. selected->select(false);
  960. selected = newSelection;
  961. if (onSelect)
  962. onSelect(selectedIndex());
  963. if (selected)
  964. selected->select(true);
  965. }
  966. int CComponentBox::selectedIndex()
  967. {
  968. if (selected)
  969. return std::find(components.begin(), components.end(), selected) - components.begin();
  970. return -1;
  971. }
  972. Point CComponentBox::getOrTextPos(CComponent *left, CComponent *right)
  973. {
  974. int leftSubtitle = ( left->pos.w - left->image->pos.w) / 2;
  975. int rightSubtitle = (right->pos.w - right->image->pos.w) / 2;
  976. int fullDistance = getDistance(left, right) + leftSubtitle + rightSubtitle;
  977. return Point(fullDistance/2 - leftSubtitle, (left->image->pos.h + right->image->pos.h) / 4);
  978. }
  979. int CComponentBox::getDistance(CComponent *left, CComponent *right)
  980. {
  981. static const int betweenImagesMin = 20;
  982. static const int betweenSubtitlesMin = 10;
  983. int leftSubtitle = ( left->pos.w - left->image->pos.w) / 2;
  984. int rightSubtitle = (right->pos.w - right->image->pos.w) / 2;
  985. int subtitlesOffset = leftSubtitle + rightSubtitle;
  986. return std::max(betweenSubtitlesMin, betweenImagesMin - subtitlesOffset);
  987. }
  988. void CComponentBox::placeComponents(bool selectable)
  989. {
  990. static const int betweenRows = 22;
  991. OBJ_CONSTRUCTION_CAPTURING_ALL;
  992. if (components.empty())
  993. return;
  994. //prepare components
  995. for(auto & comp : components)
  996. {
  997. addChild(comp);
  998. comp->moveTo(Point(pos.x, pos.y));
  999. }
  1000. struct RowData
  1001. {
  1002. size_t comps;
  1003. int width;
  1004. int height;
  1005. RowData (size_t Comps, int Width, int Height):
  1006. comps(Comps), width (Width), height (Height){};
  1007. };
  1008. std::vector<RowData> rows;
  1009. rows.push_back (RowData (0,0,0));
  1010. //split components in rows
  1011. CComponent * prevComp = nullptr;
  1012. for(CComponent * comp : components)
  1013. {
  1014. //make sure that components are smaller than our width
  1015. //assert(pos.w == 0 || pos.w < comp->pos.w);
  1016. const int distance = prevComp ? getDistance(prevComp, comp) : 0;
  1017. //start next row
  1018. if ((pos.w != 0 && rows.back().width + comp->pos.w + distance > pos.w) // row is full
  1019. || rows.back().comps >= 4) // no more than 4 comps per row
  1020. {
  1021. prevComp = nullptr;
  1022. rows.push_back (RowData (0,0,0));
  1023. }
  1024. if (prevComp)
  1025. rows.back().width += distance;
  1026. rows.back().comps++;
  1027. rows.back().width += comp->pos.w;
  1028. vstd::amax(rows.back().height, comp->pos.h);
  1029. prevComp = comp;
  1030. }
  1031. if (pos.w == 0)
  1032. {
  1033. for(auto & row : rows)
  1034. vstd::amax(pos.w, row.width);
  1035. }
  1036. int height = (rows.size() - 1) * betweenRows;
  1037. for(auto & row : rows)
  1038. height += row.height;
  1039. //assert(pos.h == 0 || pos.h < height);
  1040. if (pos.h == 0)
  1041. pos.h = height;
  1042. auto iter = components.begin();
  1043. int currentY = (pos.h - height) / 2;
  1044. //move components to their positions
  1045. for (auto & rows_row : rows)
  1046. {
  1047. // amount of free space we may add on each side of every component
  1048. int freeSpace = (pos.w - rows_row.width) / (rows_row.comps * 2);
  1049. prevComp = nullptr;
  1050. int currentX = 0;
  1051. for (size_t col = 0; col < rows_row.comps; col++)
  1052. {
  1053. currentX += freeSpace;
  1054. if (prevComp)
  1055. {
  1056. if (selectable)
  1057. {
  1058. Point orPos = Point(currentX - freeSpace, currentY) + getOrTextPos(prevComp, *iter);
  1059. new CLabel(orPos.x, orPos.y, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[4]);
  1060. }
  1061. currentX += getDistance(prevComp, *iter);
  1062. }
  1063. (*iter)->moveBy(Point(currentX, currentY));
  1064. currentX += (*iter)->pos.w;
  1065. currentX += freeSpace;
  1066. prevComp = *(iter++);
  1067. }
  1068. currentY += rows_row.height + betweenRows;
  1069. }
  1070. }
  1071. CComponentBox::CComponentBox(CComponent * _components, Rect position):
  1072. components(1, _components),
  1073. selected(nullptr)
  1074. {
  1075. type |= REDRAW_PARENT;
  1076. pos = position + pos;
  1077. placeComponents(false);
  1078. }
  1079. CComponentBox::CComponentBox(std::vector<CComponent *> _components, Rect position):
  1080. components(_components),
  1081. selected(nullptr)
  1082. {
  1083. type |= REDRAW_PARENT;
  1084. pos = position + pos;
  1085. placeComponents(false);
  1086. }
  1087. CComponentBox::CComponentBox(std::vector<CSelectableComponent *> _components, Rect position, std::function<void(int newID)> _onSelect):
  1088. components(_components.begin(), _components.end()),
  1089. selected(nullptr),
  1090. onSelect(_onSelect)
  1091. {
  1092. type |= REDRAW_PARENT;
  1093. pos = position + pos;
  1094. placeComponents(true);
  1095. assert(!components.empty());
  1096. int key = SDLK_1;
  1097. for(auto & comp : _components)
  1098. {
  1099. comp->onSelect = boost::bind(&CComponentBox::selectionChanged, this, comp);
  1100. comp->assignedKeys.insert(key++);
  1101. }
  1102. selectionChanged(_components.front());
  1103. }
  1104. void CSelWindow::selectionChange(unsigned to)
  1105. {
  1106. for (unsigned i=0;i<components.size();i++)
  1107. {
  1108. CSelectableComponent * pom = dynamic_cast<CSelectableComponent*>(components[i]);
  1109. if (!pom)
  1110. continue;
  1111. pom->select(i==to);
  1112. }
  1113. redraw();
  1114. }
  1115. CSelWindow::CSelWindow(const std::string &Text, PlayerColor player, int charperline, const std::vector<CSelectableComponent*> &comps, const std::vector<std::pair<std::string,CFunctionList<void()> > > &Buttons, QueryID askID)
  1116. {
  1117. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1118. ID = askID;
  1119. for(int i=0;i<Buttons.size();i++)
  1120. {
  1121. buttons.push_back(new CAdventureMapButton("","",Buttons[i].second,0,0,Buttons[i].first));
  1122. if(!i && askID.getNum() >= 0)
  1123. buttons.back()->callback += boost::bind(&CSelWindow::madeChoice,this);
  1124. buttons[i]->callback += boost::bind(&CInfoWindow::close,this); //each button will close the window apart from call-defined actions
  1125. }
  1126. text = new CTextBox(Text, Rect(0, 0, 250, 100), 0, FONT_MEDIUM, CENTER, Colors::WHITE);
  1127. buttons.front()->assignedKeys.insert(SDLK_RETURN); //first button - reacts on enter
  1128. buttons.back()->assignedKeys.insert(SDLK_ESCAPE); //last button - reacts on escape
  1129. if(buttons.size() > 1 && askID.getNum() >= 0) //cancel button functionality
  1130. buttons.back()->callback += boost::bind(&CCallback::selectionMade,LOCPLINT->cb.get(),0,askID);
  1131. for(int i=0;i<comps.size();i++)
  1132. {
  1133. comps[i]->recActions = 255;
  1134. addChild(comps[i]);
  1135. components.push_back(comps[i]);
  1136. comps[i]->onSelect = boost::bind(&CSelWindow::selectionChange,this,i);
  1137. if(i<9)
  1138. comps[i]->assignedKeys.insert(SDLK_1+i);
  1139. }
  1140. CMessage::drawIWindow(this, Text, player);
  1141. }
  1142. void CSelWindow::madeChoice()
  1143. {
  1144. if(ID.getNum() < 0)
  1145. return;
  1146. int ret = -1;
  1147. for (int i=0;i<components.size();i++)
  1148. {
  1149. if(dynamic_cast<CSelectableComponent*>(components[i])->selected)
  1150. {
  1151. ret = i;
  1152. }
  1153. }
  1154. LOCPLINT->cb->selectionMade(ret+1,ID);
  1155. }
  1156. CCreaturePic::CCreaturePic(int x, int y, const CCreature *cre, bool Big, bool Animated)
  1157. {
  1158. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1159. pos.x+=x;
  1160. pos.y+=y;
  1161. TFaction faction = cre->faction;
  1162. assert(CGI->townh->factions.size() > faction);
  1163. if(Big)
  1164. bg = new CPicture(CGI->townh->factions[faction]->creatureBg130);
  1165. else
  1166. bg = new CPicture(CGI->townh->factions[faction]->creatureBg120);
  1167. bg->needRefresh = true;
  1168. anim = new CCreatureAnim(0, 0, cre->animDefName, Rect());
  1169. anim->clipRect(cre->isDoubleWide()?170:150, 155, bg->pos.w, bg->pos.h);
  1170. anim->startPreview(cre->hasBonusOfType(Bonus::SIEGE_WEAPON));
  1171. pos.w = bg->pos.w;
  1172. pos.h = bg->pos.h;
  1173. }
  1174. CRecruitmentWindow::CCreatureCard::CCreatureCard(CRecruitmentWindow *window, const CCreature *crea, int totalAmount):
  1175. CIntObject(LCLICK | RCLICK),
  1176. parent(window),
  1177. selected(false),
  1178. creature(crea),
  1179. amount(totalAmount)
  1180. {
  1181. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1182. pic = new CCreaturePic(1,1, creature, true, true);
  1183. // 1 + 1 px for borders
  1184. pos.w = pic->pos.w + 2;
  1185. pos.h = pic->pos.h + 2;
  1186. }
  1187. void CRecruitmentWindow::CCreatureCard::select(bool on)
  1188. {
  1189. selected = on;
  1190. redraw();
  1191. }
  1192. void CRecruitmentWindow::CCreatureCard::clickLeft(tribool down, bool previousState)
  1193. {
  1194. if (down)
  1195. parent->select(this);
  1196. }
  1197. void CRecruitmentWindow::CCreatureCard::clickRight(tribool down, bool previousState)
  1198. {
  1199. if (down)
  1200. GH.pushInt(new CStackWindow(creature, true));
  1201. }
  1202. void CRecruitmentWindow::CCreatureCard::showAll(SDL_Surface * to)
  1203. {
  1204. CIntObject::showAll(to);
  1205. if (selected)
  1206. drawBorder(to, pos, int3(248, 0, 0));
  1207. else
  1208. drawBorder(to, pos, int3(232, 212, 120));
  1209. }
  1210. CRecruitmentWindow::CCostBox::CCostBox(Rect position, std::string title)
  1211. {
  1212. type |= REDRAW_PARENT;
  1213. pos = position + pos;
  1214. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1215. new CLabel(pos.w/2, 10, FONT_SMALL, CENTER, Colors::WHITE, title);
  1216. }
  1217. void CRecruitmentWindow::CCostBox::set(TResources res)
  1218. {
  1219. //just update values
  1220. for(auto & item : resources)
  1221. {
  1222. item.second.first->setText(boost::lexical_cast<std::string>(res[item.first]));
  1223. }
  1224. }
  1225. void CRecruitmentWindow::CCostBox::createItems(TResources res)
  1226. {
  1227. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1228. for(auto & curr : resources)
  1229. {
  1230. delete curr.second.first;
  1231. delete curr.second.second;
  1232. }
  1233. resources.clear();
  1234. TResources::nziterator iter(res);
  1235. while (iter.valid())
  1236. {
  1237. CAnimImage * image = new CAnimImage("RESOURCE", iter->resType);
  1238. CLabel * text = new CLabel(15, 43, FONT_SMALL, CENTER, Colors::WHITE, "0");
  1239. resources.insert(std::make_pair(iter->resType, std::make_pair(text, image)));
  1240. iter++;
  1241. }
  1242. if (!resources.empty())
  1243. {
  1244. int curx = pos.w / 2 - (16 * resources.size()) - (8 * (resources.size() - 1));
  1245. //reverse to display gold as first resource
  1246. for (auto & res : boost::adaptors::reverse(resources))
  1247. {
  1248. res.second.first->moveBy(Point(curx, 22));
  1249. res.second.second->moveBy(Point(curx, 22));
  1250. curx += 48;
  1251. }
  1252. }
  1253. redraw();
  1254. }
  1255. void CRecruitmentWindow::select(CCreatureCard *card)
  1256. {
  1257. if (card == selected)
  1258. return;
  1259. if (selected)
  1260. selected->select(false);
  1261. selected = card;
  1262. if (selected)
  1263. selected->select(true);
  1264. if (card)
  1265. {
  1266. si32 maxAmount = card->creature->maxAmount(LOCPLINT->cb->getResourceAmount());
  1267. vstd::amin(maxAmount, card->amount);
  1268. slider->setAmount(maxAmount);
  1269. if(slider->value != maxAmount)
  1270. slider->moveTo(maxAmount);
  1271. else // if slider already at 0 - emulate call to sliderMoved()
  1272. sliderMoved(maxAmount);
  1273. costPerTroopValue->createItems(card->creature->cost);
  1274. totalCostValue->createItems(card->creature->cost);
  1275. costPerTroopValue->set(card->creature->cost);
  1276. totalCostValue->set(card->creature->cost * maxAmount);
  1277. //Recruit %s
  1278. title->setText(boost::str(boost::format(CGI->generaltexth->tcommands[21]) % card->creature->namePl));
  1279. maxButton->block(maxAmount == 0);
  1280. slider->block(maxAmount == 0);
  1281. }
  1282. }
  1283. void CRecruitmentWindow::buy()
  1284. {
  1285. CreatureID crid = selected->creature->idNumber;
  1286. SlotID dstslot = dst-> getSlotFor(crid);
  1287. if(!dstslot.validSlot() && !vstd::contains(CGI->arth->bigArtifacts,CGI->arth->creatureToMachineID(crid))) //no available slot
  1288. {
  1289. std::string txt;
  1290. if(dst->ID == Obj::HERO)
  1291. {
  1292. txt = CGI->generaltexth->allTexts[425]; //The %s would join your hero, but there aren't enough provisions to support them.
  1293. boost::algorithm::replace_first(txt, "%s", slider->value > 1 ? CGI->creh->creatures[crid]->namePl : CGI->creh->creatures[crid]->nameSing);
  1294. }
  1295. else
  1296. {
  1297. txt = CGI->generaltexth->allTexts[17]; //There is no room in the garrison for this army.
  1298. }
  1299. LOCPLINT->showInfoDialog(txt);
  1300. return;
  1301. }
  1302. onRecruit(crid, slider->value);
  1303. if(level >= 0)
  1304. close();
  1305. }
  1306. void CRecruitmentWindow::showAll(SDL_Surface * to)
  1307. {
  1308. CWindowObject::showAll(to);
  1309. // recruit\total values
  1310. drawBorder(to, pos.x + 172, pos.y + 222, 67, 42, int3(239,215,123));
  1311. drawBorder(to, pos.x + 246, pos.y + 222, 67, 42, int3(239,215,123));
  1312. //cost boxes
  1313. drawBorder(to, pos.x + 64, pos.y + 222, 99, 76, int3(239,215,123));
  1314. drawBorder(to, pos.x + 322, pos.y + 222, 99, 76, int3(239,215,123));
  1315. //buttons borders
  1316. drawBorder(to, pos.x + 133, pos.y + 312, 66, 34, int3(173,142,66));
  1317. drawBorder(to, pos.x + 211, pos.y + 312, 66, 34, int3(173,142,66));
  1318. drawBorder(to, pos.x + 289, pos.y + 312, 66, 34, int3(173,142,66));
  1319. }
  1320. CRecruitmentWindow::CRecruitmentWindow(const CGDwelling *Dwelling, int Level, const CArmedInstance *Dst, const std::function<void(CreatureID,int)> &Recruit, int y_offset):
  1321. CWindowObject(PLAYER_COLORED, "TPRCRT"),
  1322. onRecruit(Recruit),
  1323. level(Level),
  1324. dst(Dst),
  1325. selected(nullptr),
  1326. dwelling(Dwelling)
  1327. {
  1328. moveBy(Point(0, y_offset));
  1329. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1330. new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  1331. slider = new CSlider(176,279,135,nullptr,0,0,0,true);
  1332. slider->moved = boost::bind(&CRecruitmentWindow::sliderMoved,this, _1);
  1333. maxButton = new CAdventureMapButton(CGI->generaltexth->zelp[553],boost::bind(&CSlider::moveToMax,slider),134,313,"IRCBTNS.DEF",SDLK_m);
  1334. buyButton = new CAdventureMapButton(CGI->generaltexth->zelp[554],boost::bind(&CRecruitmentWindow::buy,this),212,313,"IBY6432.DEF",SDLK_RETURN);
  1335. cancelButton = new CAdventureMapButton(CGI->generaltexth->zelp[555],boost::bind(&CRecruitmentWindow::close,this),290,313,"ICN6432.DEF",SDLK_ESCAPE);
  1336. title = new CLabel(243, 32, FONT_BIG, CENTER, Colors::YELLOW);
  1337. availableValue = new CLabel(205, 253, FONT_SMALL, CENTER, Colors::WHITE);
  1338. toRecruitValue = new CLabel(279, 253, FONT_SMALL, CENTER, Colors::WHITE);
  1339. costPerTroopValue = new CCostBox(Rect(65, 222, 97, 74), CGI->generaltexth->allTexts[346]);
  1340. totalCostValue = new CCostBox(Rect(323, 222, 97, 74), CGI->generaltexth->allTexts[466]);
  1341. new CLabel(205, 233, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[465]); //available t
  1342. new CLabel(279, 233, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[16]); //recruit t
  1343. availableCreaturesChanged();
  1344. }
  1345. void CRecruitmentWindow::availableCreaturesChanged()
  1346. {
  1347. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1348. size_t selectedIndex = 0;
  1349. if (!cards.empty() && selected) // find position of selected item
  1350. selectedIndex = std::find(cards.begin(), cards.end(), selected) - cards.begin();
  1351. //deselect card
  1352. select(nullptr);
  1353. //delete old cards
  1354. for(auto & card : cards)
  1355. delete card;
  1356. cards.clear();
  1357. for(int i=0; i<dwelling->creatures.size(); i++)
  1358. {
  1359. //find appropriate level
  1360. if(level >= 0 && i != level)
  1361. continue;
  1362. int amount = dwelling->creatures[i].first;
  1363. //create new cards
  1364. for(auto & creature : boost::adaptors::reverse(dwelling->creatures[i].second))
  1365. cards.push_back(new CCreatureCard(this, CGI->creh->creatures[creature], amount));
  1366. }
  1367. assert(!cards.empty());
  1368. const int creatureWidth = 102;
  1369. //normal distance between cards - 18px
  1370. int requiredSpace = 18;
  1371. //maximum distance we can use without reaching window borders
  1372. int availableSpace = pos.w - 50 - creatureWidth * cards.size();
  1373. if (cards.size() > 1) // avoid division by zero
  1374. availableSpace /= cards.size() - 1;
  1375. else
  1376. availableSpace = 0;
  1377. assert(availableSpace >= 0);
  1378. const int spaceBetween = std::min(requiredSpace, availableSpace);
  1379. const int totalCreatureWidth = spaceBetween + creatureWidth;
  1380. //now we know total amount of cards and can move them to correct position
  1381. int curx = pos.w / 2 - (creatureWidth*cards.size()/2) - (spaceBetween*(cards.size()-1)/2);
  1382. for(auto & card : cards)
  1383. {
  1384. card->moveBy(Point(curx, 64));
  1385. curx += totalCreatureWidth;
  1386. }
  1387. //restore selection
  1388. select(cards[selectedIndex]);
  1389. if(slider->value == slider->amount)
  1390. slider->moveTo(slider->amount);
  1391. else // if slider already at 0 - emulate call to sliderMoved()
  1392. sliderMoved(slider->amount);
  1393. }
  1394. void CRecruitmentWindow::sliderMoved(int to)
  1395. {
  1396. if (!selected)
  1397. return;
  1398. buyButton->block(!to);
  1399. availableValue->setText(boost::lexical_cast<std::string>(selected->amount - to));
  1400. toRecruitValue->setText(boost::lexical_cast<std::string>(to));
  1401. totalCostValue->set(selected->creature->cost * to);
  1402. }
  1403. CSplitWindow::CSplitWindow(const CCreature * creature, std::function<void(int, int)> callback_,
  1404. int leftMin_, int rightMin_, int leftAmount_, int rightAmount_):
  1405. CWindowObject(PLAYER_COLORED, "GPUCRDIV"),
  1406. callback(callback_),
  1407. leftAmount(leftAmount_),
  1408. rightAmount(rightAmount_),
  1409. leftMin(leftMin_),
  1410. rightMin(rightMin_),
  1411. slider(nullptr)
  1412. {
  1413. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1414. int total = leftAmount + rightAmount;
  1415. int leftMax = total - rightMin;
  1416. int rightMax = total - leftMin;
  1417. ok = new CAdventureMapButton("", "", boost::bind(&CSplitWindow::apply, this), 20, 263, "IOK6432", SDLK_RETURN);
  1418. cancel = new CAdventureMapButton("", "", boost::bind(&CSplitWindow::close, this), 214, 263, "ICN6432", SDLK_ESCAPE);
  1419. int sliderPositions = total - leftMin - rightMin;
  1420. leftInput = new CTextInput(Rect(20, 218, 100, 36), FONT_BIG, boost::bind(&CSplitWindow::setAmountText, this, _1, true));
  1421. rightInput = new CTextInput(Rect(176, 218, 100, 36), FONT_BIG, boost::bind(&CSplitWindow::setAmountText, this, _1, false));
  1422. //add filters to allow only number input
  1423. leftInput->filters.add(boost::bind(&CTextInput::numberFilter, _1, _2, leftMin, leftMax));
  1424. rightInput->filters.add(boost::bind(&CTextInput::numberFilter, _1, _2, rightMin, rightMax));
  1425. leftInput->setText(boost::lexical_cast<std::string>(leftAmount), false);
  1426. rightInput->setText(boost::lexical_cast<std::string>(rightAmount), false);
  1427. animLeft = new CCreaturePic(20, 54, creature, true, false);
  1428. animRight = new CCreaturePic(177, 54,creature, true, false);
  1429. slider = new CSlider(21, 194, 257, boost::bind(&CSplitWindow::sliderMoved, this, _1), 0, sliderPositions, rightAmount - rightMin, true);
  1430. std::string title = CGI->generaltexth->allTexts[256];
  1431. boost::algorithm::replace_first(title,"%s", creature->namePl);
  1432. new CLabel(150, 34, FONT_BIG, CENTER, Colors::YELLOW, title);
  1433. }
  1434. void CSplitWindow::setAmountText(std::string text, bool left)
  1435. {
  1436. try
  1437. {
  1438. setAmount(boost::lexical_cast<int>(text), left);
  1439. slider->moveTo(rightAmount - rightMin);
  1440. }
  1441. catch(boost::bad_lexical_cast &)
  1442. {
  1443. }
  1444. }
  1445. void CSplitWindow::setAmount(int value, bool left)
  1446. {
  1447. int total = leftAmount + rightAmount;
  1448. leftAmount = left ? value : total - value;
  1449. rightAmount = left ? total - value : value;
  1450. leftInput->setText(boost::lexical_cast<std::string>(leftAmount));
  1451. rightInput->setText(boost::lexical_cast<std::string>(rightAmount));
  1452. }
  1453. void CSplitWindow::apply()
  1454. {
  1455. callback(leftAmount, rightAmount);
  1456. close();
  1457. }
  1458. void CSplitWindow::sliderMoved(int to)
  1459. {
  1460. setAmount(rightMin + to, false);
  1461. }
  1462. CLevelWindow::CLevelWindow(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, std::function<void(ui32)> callback):
  1463. CWindowObject(PLAYER_COLORED, "LVLUPBKG"),
  1464. cb(callback)
  1465. {
  1466. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1467. LOCPLINT->showingDialog->setn(true);
  1468. new CAnimImage("PortraitsLarge", hero->portrait, 0, 170, 66);
  1469. new CAdventureMapButton("", "", boost::bind(&CLevelWindow::close, this), 297, 413, "IOKAY", SDLK_RETURN);
  1470. //%s has gained a level.
  1471. new CLabel(192, 33, FONT_MEDIUM, CENTER, Colors::WHITE,
  1472. boost::str(boost::format(CGI->generaltexth->allTexts[444]) % hero->name));
  1473. //%s is now a level %d %s.
  1474. new CLabel(192, 162, FONT_MEDIUM, CENTER, Colors::WHITE,
  1475. boost::str(boost::format(CGI->generaltexth->allTexts[445]) % hero->name % hero->level % hero->type->heroClass->name));
  1476. new CAnimImage("PSKIL42", pskill, 0, 174, 190);
  1477. new CLabel(192, 253, FONT_MEDIUM, CENTER, Colors::WHITE,
  1478. CGI->generaltexth->primarySkillNames[pskill] + " +1");
  1479. if (!skills.empty())
  1480. {
  1481. std::vector<CSelectableComponent *> comps;
  1482. for(auto & skill : skills)
  1483. {
  1484. comps.push_back(new CSelectableComponent(
  1485. CComponent::secskill,
  1486. skill,
  1487. hero->getSecSkillLevel( SecondarySkill(skill) )+1,
  1488. CComponent::medium));
  1489. }
  1490. box = new CComponentBox(comps, Rect(75, 300, pos.w - 150, 100));
  1491. }
  1492. else
  1493. box = nullptr;
  1494. }
  1495. CLevelWindow::~CLevelWindow()
  1496. {
  1497. //FIXME: call callback if there was nothing to select?
  1498. if (box && box->selectedIndex() != -1)
  1499. cb(box->selectedIndex());
  1500. LOCPLINT->showingDialog->setn(false);
  1501. }
  1502. void CMinorResDataBar::show(SDL_Surface * to)
  1503. {
  1504. }
  1505. void CMinorResDataBar::showAll(SDL_Surface * to)
  1506. {
  1507. blitAt(bg,pos.x,pos.y,to);
  1508. for (Res::ERes i=Res::WOOD; i<=Res::GOLD; vstd::advance(i, 1))
  1509. {
  1510. std::string text = boost::lexical_cast<std::string>(LOCPLINT->cb->getResourceAmount(i));
  1511. graphics->fonts[FONT_SMALL]->renderTextCenter(to, text, Colors::WHITE, Point(pos.x + 50 + 76 * i, pos.y + pos.h/2));
  1512. }
  1513. std::vector<std::string> temp;
  1514. temp.push_back(boost::lexical_cast<std::string>(LOCPLINT->cb->getDate(Date::MONTH)));
  1515. temp.push_back(boost::lexical_cast<std::string>(LOCPLINT->cb->getDate(Date::WEEK)));
  1516. temp.push_back(boost::lexical_cast<std::string>(LOCPLINT->cb->getDate(Date::DAY_OF_WEEK)));
  1517. std::string datetext = CGI->generaltexth->allTexts[62]+": %s, " + CGI->generaltexth->allTexts[63]
  1518. + ": %s, " + CGI->generaltexth->allTexts[64] + ": %s";
  1519. graphics->fonts[FONT_SMALL]->renderTextCenter(to, processStr(datetext,temp), Colors::WHITE, Point(pos.x+545+(pos.w-545)/2,pos.y+pos.h/2));
  1520. }
  1521. CMinorResDataBar::CMinorResDataBar()
  1522. {
  1523. bg = BitmapHandler::loadBitmap("KRESBAR.bmp");
  1524. SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
  1525. graphics->blueToPlayersAdv(bg,LOCPLINT->playerID);
  1526. pos.x = 7;
  1527. pos.y = 575;
  1528. pos.w = bg->w;
  1529. pos.h = bg->h;
  1530. }
  1531. CMinorResDataBar::~CMinorResDataBar()
  1532. {
  1533. SDL_FreeSurface(bg);
  1534. }
  1535. CObjectListWindow::CItem::CItem(CObjectListWindow *_parent, size_t _id, std::string _text):
  1536. parent(_parent),
  1537. index(_id)
  1538. {
  1539. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1540. border = new CPicture("TPGATES");
  1541. pos = border->pos;
  1542. addUsedEvents(LCLICK);
  1543. type |= REDRAW_PARENT;
  1544. text = new CLabel(pos.w/2, pos.h/2, FONT_SMALL, CENTER, Colors::WHITE, _text);
  1545. select(index == parent->selected);
  1546. }
  1547. void CObjectListWindow::CItem::select(bool on)
  1548. {
  1549. if (on)
  1550. border->recActions = 255;
  1551. else
  1552. border->recActions = ~(UPDATE | SHOWALL);
  1553. redraw();
  1554. }
  1555. void CObjectListWindow::CItem::clickLeft(tribool down, bool previousState)
  1556. {
  1557. if( previousState && !down)
  1558. parent->changeSelection(index);
  1559. }
  1560. CObjectListWindow::CObjectListWindow(const std::vector<int> &_items, CIntObject * titlePic, std::string _title, std::string _descr,
  1561. std::function<void(int)> Callback):
  1562. CWindowObject(PLAYER_COLORED, "TPGATE"),
  1563. onSelect(Callback)
  1564. {
  1565. items.reserve(_items.size());
  1566. for(int id : _items)
  1567. {
  1568. items.push_back(std::make_pair(id, CGI->mh->map->objects[id]->getObjectName()));
  1569. }
  1570. init(titlePic, _title, _descr);
  1571. }
  1572. CObjectListWindow::CObjectListWindow(const std::vector<std::string> &_items, CIntObject * titlePic, std::string _title, std::string _descr,
  1573. std::function<void(int)> Callback):
  1574. CWindowObject(PLAYER_COLORED, "TPGATE"),
  1575. onSelect(Callback)
  1576. {
  1577. items.reserve(_items.size());
  1578. for (size_t i=0; i<_items.size(); i++)
  1579. items.push_back(std::make_pair(int(i), _items[i]));
  1580. init(titlePic, _title, _descr);
  1581. }
  1582. void CObjectListWindow::init(CIntObject * titlePic, std::string _title, std::string _descr)
  1583. {
  1584. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1585. title = new CLabel(152, 27, FONT_BIG, CENTER, Colors::YELLOW, _title);
  1586. descr = new CLabel(145, 133, FONT_SMALL, CENTER, Colors::WHITE, _descr);
  1587. ok = new CAdventureMapButton("","",boost::bind(&CObjectListWindow::elementSelected, this),15,402,"IOKAY.DEF", SDLK_RETURN);
  1588. ok->block(true);
  1589. exit = new CAdventureMapButton("","",boost::bind(&CGuiHandler::popIntTotally,&GH, this),228,402,"ICANCEL.DEF",SDLK_ESCAPE);
  1590. if (titlePic)
  1591. {
  1592. titleImage = titlePic;
  1593. addChild(titleImage);
  1594. titleImage->recActions = defActions;
  1595. titleImage->pos.x = pos.w/2 + pos.x - titleImage->pos.w/2;
  1596. titleImage->pos.y =75 + pos.y - titleImage->pos.h/2;
  1597. }
  1598. list = new CListBox(boost::bind(&CObjectListWindow::genItem, this, _1), CListBox::DestroyFunc(),
  1599. Point(14, 151), Point(0, 25), 9, items.size(), 0, 1, Rect(262, -32, 256, 256) );
  1600. list->type |= REDRAW_PARENT;
  1601. }
  1602. CIntObject * CObjectListWindow::genItem(size_t index)
  1603. {
  1604. if (index < items.size())
  1605. return new CItem(this, index, items[index].second);
  1606. return nullptr;
  1607. }
  1608. void CObjectListWindow::elementSelected()
  1609. {
  1610. std::function<void(int)> toCall = onSelect;//save
  1611. int where = items[selected].first; //required variables
  1612. GH.popIntTotally(this);//then destroy window
  1613. toCall(where);//and send selected object
  1614. }
  1615. void CObjectListWindow::changeSelection(size_t which)
  1616. {
  1617. ok->block(false);
  1618. if (selected == which)
  1619. return;
  1620. std::list< CIntObject * > elements = list->getItems();
  1621. for(CIntObject * element : elements)
  1622. {
  1623. CItem *item;
  1624. if ( (item = dynamic_cast<CItem*>(element)) )
  1625. {
  1626. if (item->index == selected)
  1627. item->select(false);
  1628. if (item->index == which)
  1629. item->select(true);
  1630. }
  1631. }
  1632. selected = which;
  1633. }
  1634. void CObjectListWindow::keyPressed (const SDL_KeyboardEvent & key)
  1635. {
  1636. if(key.state != SDL_PRESSED)
  1637. return;
  1638. int sel = selected;
  1639. switch(key.keysym.sym)
  1640. {
  1641. break; case SDLK_UP:
  1642. sel -=1;
  1643. break; case SDLK_DOWN:
  1644. sel +=1;
  1645. break; case SDLK_PAGEUP:
  1646. sel -=9;
  1647. break; case SDLK_PAGEDOWN:
  1648. sel +=9;
  1649. break; case SDLK_HOME:
  1650. sel = 0;
  1651. break; case SDLK_END:
  1652. sel = items.size();
  1653. break; default:
  1654. return;
  1655. }
  1656. vstd::abetween(sel, 0, items.size()-1);
  1657. list->scrollTo(sel);
  1658. changeSelection(sel);
  1659. }
  1660. CTradeWindow::CTradeableItem::CTradeableItem(Point pos, EType Type, int ID, bool Left, int Serial):
  1661. CIntObject(LCLICK | HOVER | RCLICK, pos),
  1662. type(EType(-1)),// set to invalid, will be corrected in setType
  1663. id(ID),
  1664. serial(Serial),
  1665. left(Left)
  1666. {
  1667. downSelection = false;
  1668. hlp = nullptr;
  1669. image = nullptr;
  1670. setType(Type);
  1671. }
  1672. void CTradeWindow::CTradeableItem::setType(EType newType)
  1673. {
  1674. if (type != newType)
  1675. {
  1676. OBJ_CONSTRUCTION_CAPTURING_ALL;
  1677. type = newType;
  1678. delete image;
  1679. if (getIndex() < 0)
  1680. {
  1681. image = new CAnimImage(getFilename(), 0);
  1682. image->disable();
  1683. }
  1684. else
  1685. image = new CAnimImage(getFilename(), getIndex());
  1686. }
  1687. }
  1688. void CTradeWindow::CTradeableItem::setID(int newID)
  1689. {
  1690. if (id != newID)
  1691. {
  1692. id = newID;
  1693. if (image)
  1694. {
  1695. int index = getIndex();
  1696. if (index < 0)
  1697. image->disable();
  1698. else
  1699. {
  1700. image->enable();
  1701. image->setFrame(index);
  1702. }
  1703. }
  1704. }
  1705. }
  1706. std::string CTradeWindow::CTradeableItem::getFilename()
  1707. {
  1708. switch(type)
  1709. {
  1710. case RESOURCE:
  1711. return "RESOURCE";
  1712. case PLAYER:
  1713. return "CREST58";
  1714. case ARTIFACT_TYPE:
  1715. case ARTIFACT_PLACEHOLDER:
  1716. case ARTIFACT_INSTANCE:
  1717. return "artifact";
  1718. case CREATURE:
  1719. return "TWCRPORT";
  1720. default:
  1721. return "";
  1722. }
  1723. }
  1724. int CTradeWindow::CTradeableItem::getIndex()
  1725. {
  1726. if (id < 0)
  1727. return -1;
  1728. switch(type)
  1729. {
  1730. case RESOURCE:
  1731. case PLAYER:
  1732. return id;
  1733. case ARTIFACT_TYPE:
  1734. case ARTIFACT_INSTANCE:
  1735. case ARTIFACT_PLACEHOLDER:
  1736. return VLC->arth->artifacts[id]->iconIndex;
  1737. case CREATURE:
  1738. return VLC->creh->creatures[id]->iconIndex;
  1739. default:
  1740. return -1;
  1741. }
  1742. }
  1743. void CTradeWindow::CTradeableItem::showAll(SDL_Surface * to)
  1744. {
  1745. Point posToBitmap;
  1746. Point posToSubCenter;
  1747. switch(type)
  1748. {
  1749. case RESOURCE:
  1750. posToBitmap = Point(19,9);
  1751. posToSubCenter = Point(36, 59);
  1752. break;
  1753. case CREATURE_PLACEHOLDER:
  1754. case CREATURE:
  1755. posToSubCenter = Point(29, 76);
  1756. if(downSelection)
  1757. posToSubCenter.y += 5;
  1758. break;
  1759. case PLAYER:
  1760. posToSubCenter = Point(31, 76);
  1761. break;
  1762. case ARTIFACT_PLACEHOLDER:
  1763. case ARTIFACT_INSTANCE:
  1764. posToSubCenter = Point(19, 55);
  1765. if(downSelection)
  1766. posToSubCenter.y += 8;
  1767. break;
  1768. case ARTIFACT_TYPE:
  1769. posToSubCenter = Point(19, 58);
  1770. break;
  1771. }
  1772. if (image)
  1773. {
  1774. image->moveTo(pos.topLeft() + posToBitmap);
  1775. CIntObject::showAll(to);
  1776. }
  1777. printAtMiddleLoc(subtitle, posToSubCenter, FONT_SMALL, Colors::WHITE, to);
  1778. }
  1779. void CTradeWindow::CTradeableItem::clickLeft(tribool down, bool previousState)
  1780. {
  1781. CTradeWindow *mw = dynamic_cast<CTradeWindow *>(parent);
  1782. assert(mw);
  1783. if(down)
  1784. {
  1785. if(type == ARTIFACT_PLACEHOLDER)
  1786. {
  1787. CAltarWindow *aw = static_cast<CAltarWindow *>(mw);
  1788. if(const CArtifactInstance *movedArt = aw->arts->commonInfo->src.art)
  1789. {
  1790. aw->moveFromSlotToAltar(aw->arts->commonInfo->src.slotID, this, movedArt);
  1791. }
  1792. else if(const CArtifactInstance *art = getArtInstance())
  1793. {
  1794. aw->arts->commonInfo->src.AOH = aw->arts;
  1795. aw->arts->commonInfo->src.art = art;
  1796. aw->arts->commonInfo->src.slotID = aw->hero->getArtPos(art);
  1797. aw->arts->markPossibleSlots(art);
  1798. //aw->arts->commonInfo->dst.AOH = aw->arts;
  1799. CCS->curh->dragAndDropCursor(new CAnimImage("artifact", art->artType->iconIndex));
  1800. aw->arts->artifactsOnAltar.erase(art);
  1801. setID(-1);
  1802. subtitle = "";
  1803. aw->deal->block(!aw->arts->artifactsOnAltar.size());
  1804. }
  1805. aw->calcTotalExp();
  1806. return;
  1807. }
  1808. if(left)
  1809. {
  1810. if(mw->hLeft != this)
  1811. mw->hLeft = this;
  1812. else
  1813. return;
  1814. }
  1815. else
  1816. {
  1817. if(mw->hRight != this)
  1818. mw->hRight = this;
  1819. else
  1820. return;
  1821. }
  1822. mw->selectionChanged(left);
  1823. }
  1824. }
  1825. void CTradeWindow::CTradeableItem::showAllAt(const Point &dstPos, const std::string &customSub, SDL_Surface * to)
  1826. {
  1827. Rect oldPos = pos;
  1828. std::string oldSub = subtitle;
  1829. downSelection = true;
  1830. moveTo(dstPos);
  1831. subtitle = customSub;
  1832. showAll(to);
  1833. downSelection = false;
  1834. moveTo(oldPos.topLeft());
  1835. subtitle = oldSub;
  1836. }
  1837. void CTradeWindow::CTradeableItem::hover(bool on)
  1838. {
  1839. if(!on)
  1840. {
  1841. GH.statusbar->clear();
  1842. return;
  1843. }
  1844. switch(type)
  1845. {
  1846. case CREATURE:
  1847. case CREATURE_PLACEHOLDER:
  1848. GH.statusbar->setText(boost::str(boost::format(CGI->generaltexth->allTexts[481]) % CGI->creh->creatures[id]->namePl));
  1849. break;
  1850. case ARTIFACT_PLACEHOLDER:
  1851. if(id < 0)
  1852. GH.statusbar->setText(CGI->generaltexth->zelp[582].first);
  1853. else
  1854. GH.statusbar->setText(CGI->arth->artifacts[id]->Name());
  1855. break;
  1856. }
  1857. }
  1858. void CTradeWindow::CTradeableItem::clickRight(tribool down, bool previousState)
  1859. {
  1860. if(down)
  1861. {
  1862. switch(type)
  1863. {
  1864. case CREATURE:
  1865. case CREATURE_PLACEHOLDER:
  1866. //GH.statusbar->print(boost::str(boost::format(CGI->generaltexth->allTexts[481]) % CGI->creh->creatures[id]->namePl));
  1867. break;
  1868. case ARTIFACT_TYPE:
  1869. case ARTIFACT_PLACEHOLDER:
  1870. if(id >= 0)
  1871. adventureInt->handleRightClick(CGI->arth->artifacts[id]->Description(), down);
  1872. break;
  1873. }
  1874. }
  1875. }
  1876. std::string CTradeWindow::CTradeableItem::getName(int number /*= -1*/) const
  1877. {
  1878. switch(type)
  1879. {
  1880. case PLAYER:
  1881. return CGI->generaltexth->capColors[id];
  1882. case RESOURCE:
  1883. return CGI->generaltexth->restypes[id];
  1884. case CREATURE:
  1885. if(number == 1)
  1886. return CGI->creh->creatures[id]->nameSing;
  1887. else
  1888. return CGI->creh->creatures[id]->namePl;
  1889. case ARTIFACT_TYPE:
  1890. case ARTIFACT_INSTANCE:
  1891. return CGI->arth->artifacts[id]->Name();
  1892. }
  1893. assert(0);
  1894. return "";
  1895. }
  1896. const CArtifactInstance * CTradeWindow::CTradeableItem::getArtInstance() const
  1897. {
  1898. switch(type)
  1899. {
  1900. case ARTIFACT_PLACEHOLDER:
  1901. case ARTIFACT_INSTANCE:
  1902. return (const CArtifactInstance *)hlp;
  1903. default:
  1904. return nullptr;
  1905. }
  1906. }
  1907. void CTradeWindow::CTradeableItem::setArtInstance(const CArtifactInstance *art)
  1908. {
  1909. assert(type == ARTIFACT_PLACEHOLDER || type == ARTIFACT_INSTANCE);
  1910. hlp = art;
  1911. if(art)
  1912. setID(art->artType->id);
  1913. else
  1914. setID(-1);
  1915. }
  1916. CTradeWindow::CTradeWindow(std::string bgName, const IMarket *Market, const CGHeroInstance *Hero, EMarketMode::EMarketMode Mode):
  1917. CWindowObject(PLAYER_COLORED, bgName),
  1918. market(Market),
  1919. hero(Hero),
  1920. arts(nullptr),
  1921. hLeft(nullptr),
  1922. hRight(nullptr),
  1923. readyToTrade(false)
  1924. {
  1925. type |= BLOCK_ADV_HOTKEYS;
  1926. mode = Mode;
  1927. initTypes();
  1928. }
  1929. void CTradeWindow::initTypes()
  1930. {
  1931. switch(mode)
  1932. {
  1933. case EMarketMode::RESOURCE_RESOURCE:
  1934. itemsType[1] = RESOURCE;
  1935. itemsType[0] = RESOURCE;
  1936. break;
  1937. case EMarketMode::RESOURCE_PLAYER:
  1938. itemsType[1] = RESOURCE;
  1939. itemsType[0] = PLAYER;
  1940. break;
  1941. case EMarketMode::CREATURE_RESOURCE:
  1942. itemsType[1] = CREATURE;
  1943. itemsType[0] = RESOURCE;
  1944. break;
  1945. case EMarketMode::RESOURCE_ARTIFACT:
  1946. itemsType[1] = RESOURCE;
  1947. itemsType[0] = ARTIFACT_TYPE;
  1948. break;
  1949. case EMarketMode::ARTIFACT_RESOURCE:
  1950. itemsType[1] = ARTIFACT_INSTANCE;
  1951. itemsType[0] = RESOURCE;
  1952. break;
  1953. case EMarketMode::CREATURE_EXP:
  1954. itemsType[1] = CREATURE;
  1955. itemsType[0] = CREATURE_PLACEHOLDER;
  1956. break;
  1957. case EMarketMode::ARTIFACT_EXP:
  1958. itemsType[1] = ARTIFACT_TYPE;
  1959. itemsType[0] = ARTIFACT_PLACEHOLDER;
  1960. break;
  1961. }
  1962. }
  1963. void CTradeWindow::initItems(bool Left)
  1964. {
  1965. if(Left && (itemsType[1] == ARTIFACT_TYPE || itemsType[1] == ARTIFACT_INSTANCE))
  1966. {
  1967. int xOffset = 0, yOffset = 0;
  1968. if(mode == EMarketMode::ARTIFACT_RESOURCE)
  1969. {
  1970. xOffset = -361;
  1971. yOffset = +46;
  1972. auto hlp = new CTradeableItem(Point(137, 469), itemsType[Left], -1, 1, 0);
  1973. hlp->recActions &= ~(UPDATE | SHOWALL);
  1974. items[Left].push_back(hlp);
  1975. }
  1976. else //ARTIFACT_EXP
  1977. {
  1978. xOffset = -363;
  1979. yOffset = -12;
  1980. }
  1981. BLOCK_CAPTURING;
  1982. arts = new CArtifactsOfHero(Point(pos.x+xOffset, pos.y+yOffset));
  1983. arts->commonInfo = new CArtifactsOfHero::SCommonPart;
  1984. arts->commonInfo->participants.insert(arts);
  1985. arts->recActions = 255;
  1986. arts->setHero(hero);
  1987. arts->allowedAssembling = false;
  1988. addChild(arts);
  1989. artSets.push_back(arts);
  1990. if(mode == EMarketMode::ARTIFACT_RESOURCE)
  1991. arts->highlightModeCallback = boost::bind(&CTradeWindow::artifactSelected, this, _1);
  1992. return;
  1993. }
  1994. std::vector<int> *ids = getItemsIds(Left);
  1995. std::vector<Rect> pos;
  1996. int amount = -1;
  1997. getPositionsFor(pos, Left, itemsType[Left]);
  1998. if(Left || !ids)
  1999. amount = 7;
  2000. else
  2001. amount = ids->size();
  2002. if(ids)
  2003. vstd::amin(amount, ids->size());
  2004. for(int j=0; j<amount; j++)
  2005. {
  2006. int id = (ids && ids->size()>j) ? (*ids)[j] : j;
  2007. if(id < 0 && mode != EMarketMode::ARTIFACT_EXP) //when sacrificing artifacts we need to prepare empty slots
  2008. continue;
  2009. auto hlp = new CTradeableItem(pos[j].topLeft(), itemsType[Left], id, Left, j);
  2010. hlp->pos = pos[j] + this->pos.topLeft();
  2011. items[Left].push_back(hlp);
  2012. }
  2013. initSubs(Left);
  2014. }
  2015. std::vector<int> *CTradeWindow::getItemsIds(bool Left)
  2016. {
  2017. std::vector<int> *ids = nullptr;
  2018. if(mode == EMarketMode::ARTIFACT_EXP)
  2019. return new std::vector<int>(22, -1);
  2020. if(Left)
  2021. {
  2022. switch(itemsType[1])
  2023. {
  2024. case CREATURE:
  2025. ids = new std::vector<int>;
  2026. for(int i = 0; i < 7; i++)
  2027. {
  2028. if(const CCreature *c = hero->getCreature(SlotID(i)))
  2029. ids->push_back(c->idNumber);
  2030. else
  2031. ids->push_back(-1);
  2032. }
  2033. break;
  2034. }
  2035. }
  2036. else
  2037. {
  2038. switch(itemsType[0])
  2039. {
  2040. case PLAYER:
  2041. ids = new std::vector<int>;
  2042. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  2043. if(PlayerColor(i) != LOCPLINT->playerID && LOCPLINT->cb->getPlayerStatus(PlayerColor(i)) == EPlayerStatus::INGAME)
  2044. ids->push_back(i);
  2045. break;
  2046. case ARTIFACT_TYPE:
  2047. ids = new std::vector<int>(market->availableItemsIds(mode));
  2048. break;
  2049. }
  2050. }
  2051. return ids;
  2052. }
  2053. void CTradeWindow::getPositionsFor(std::vector<Rect> &poss, bool Left, EType type) const
  2054. {
  2055. if(mode == EMarketMode::ARTIFACT_EXP && !Left)
  2056. {
  2057. //22 boxes, 5 in row, last row: two boxes centered
  2058. int h, w, x, y, dx, dy;
  2059. h = w = 44;
  2060. x = 317;
  2061. y = 53;
  2062. dx = 54;
  2063. dy = 70;
  2064. for (int i = 0; i < 4 ; i++)
  2065. for (int j = 0; j < 5 ; j++)
  2066. poss += Rect(x + dx*j, y + dy*i, w, h);
  2067. poss += Rect(x + dx*1.5, y + dy*4, w, h);
  2068. poss += Rect(x + dx*2.5, y + dy*4, w, h);
  2069. }
  2070. else
  2071. {
  2072. //seven boxes:
  2073. // X X X
  2074. // X X X
  2075. // X
  2076. int h, w, x, y, dx, dy;
  2077. int leftToRightOffset;
  2078. getBaseForPositions(type, dx, dy, x, y, h, w, !Left, leftToRightOffset);
  2079. poss += genRect(h, w, x, y), genRect(h, w, x + dx, y), genRect(h, w, x + 2*dx, y),
  2080. genRect(h, w, x, y + dy), genRect(h, w, x + dx, y + dy), genRect(h, w, x + 2*dx, y + dy),
  2081. genRect(h, w, x + dx, y + 2*dy);
  2082. if(!Left)
  2083. {
  2084. for(Rect &r : poss)
  2085. r.x += leftToRightOffset;
  2086. }
  2087. }
  2088. }
  2089. void CTradeWindow::initSubs(bool Left)
  2090. {
  2091. for(CTradeableItem *t : items[Left])
  2092. {
  2093. if(Left)
  2094. {
  2095. switch(itemsType[1])
  2096. {
  2097. case CREATURE:
  2098. t->subtitle = boost::lexical_cast<std::string>(hero->getStackCount(SlotID(t->serial)));
  2099. break;
  2100. case RESOURCE:
  2101. t->subtitle = boost::lexical_cast<std::string>(LOCPLINT->cb->getResourceAmount(static_cast<Res::ERes>(t->serial)));
  2102. break;
  2103. }
  2104. }
  2105. else //right side
  2106. {
  2107. if(itemsType[0] == PLAYER)
  2108. {
  2109. t->subtitle = CGI->generaltexth->capColors[t->id];
  2110. }
  2111. else if(hLeft)//artifact, creature
  2112. {
  2113. int h1, h2; //hlp variables for getting offer
  2114. market->getOffer(hLeft->id, t->id, h1, h2, mode);
  2115. if(t->id != hLeft->id || mode != EMarketMode::RESOURCE_RESOURCE) //don't allow exchanging same resources
  2116. {
  2117. std::ostringstream oss;
  2118. oss << h2;
  2119. if(h1!=1)
  2120. oss << "/" << h1;
  2121. t->subtitle = oss.str();
  2122. }
  2123. else
  2124. t->subtitle = CGI->generaltexth->allTexts[164]; // n/a
  2125. }
  2126. else
  2127. t->subtitle = "";
  2128. }
  2129. }
  2130. }
  2131. void CTradeWindow::showAll(SDL_Surface * to)
  2132. {
  2133. CWindowObject::showAll(to);
  2134. if(hRight)
  2135. CSDL_Ext::drawBorder(to,hRight->pos.x-1,hRight->pos.y-1,hRight->pos.w+2,hRight->pos.h+2,int3(255,231,148));
  2136. if(hLeft && hLeft->type != ARTIFACT_INSTANCE)
  2137. CSDL_Ext::drawBorder(to,hLeft->pos.x-1,hLeft->pos.y-1,hLeft->pos.w+2,hLeft->pos.h+2,int3(255,231,148));
  2138. if(readyToTrade)
  2139. {
  2140. hLeft->showAllAt(pos.topLeft() + selectionOffset(true), selectionSubtitle(true), to);
  2141. hRight->showAllAt(pos.topLeft() + selectionOffset(false), selectionSubtitle(false), to);
  2142. }
  2143. }
  2144. void CTradeWindow::removeItems(const std::set<CTradeableItem *> &toRemove)
  2145. {
  2146. for(CTradeableItem *t : toRemove)
  2147. removeItem(t);
  2148. }
  2149. void CTradeWindow::removeItem(CTradeableItem * t)
  2150. {
  2151. items[t->left] -= t;
  2152. delete t;
  2153. if(hRight == t)
  2154. {
  2155. hRight = nullptr;
  2156. selectionChanged(false);
  2157. }
  2158. }
  2159. void CTradeWindow::getEmptySlots(std::set<CTradeableItem *> &toRemove)
  2160. {
  2161. for(CTradeableItem *t : items[1])
  2162. if(!hero->getStackCount(SlotID(t->serial)))
  2163. toRemove.insert(t);
  2164. }
  2165. void CTradeWindow::setMode(EMarketMode::EMarketMode Mode)
  2166. {
  2167. const IMarket *m = market;
  2168. const CGHeroInstance *h = hero;
  2169. CTradeWindow *nwindow = nullptr;
  2170. GH.popIntTotally(this);
  2171. switch(Mode)
  2172. {
  2173. case EMarketMode::CREATURE_EXP:
  2174. case EMarketMode::ARTIFACT_EXP:
  2175. nwindow = new CAltarWindow(m, h, Mode);
  2176. break;
  2177. default:
  2178. nwindow = new CMarketplaceWindow(m, h, Mode);
  2179. break;
  2180. }
  2181. GH.pushInt(nwindow);
  2182. }
  2183. void CTradeWindow::artifactSelected(CArtPlace *slot)
  2184. {
  2185. assert(mode == EMarketMode::ARTIFACT_RESOURCE);
  2186. items[1][0]->setArtInstance(slot->ourArt);
  2187. if(slot->ourArt)
  2188. hLeft = items[1][0];
  2189. else
  2190. hLeft = nullptr;
  2191. selectionChanged(true);
  2192. }
  2193. std::string CMarketplaceWindow::getBackgroundForMode(EMarketMode::EMarketMode mode)
  2194. {
  2195. switch(mode)
  2196. {
  2197. case EMarketMode::RESOURCE_RESOURCE:
  2198. return "TPMRKRES.bmp";
  2199. case EMarketMode::RESOURCE_PLAYER:
  2200. return "TPMRKPTS.bmp";
  2201. case EMarketMode::CREATURE_RESOURCE:
  2202. return "TPMRKCRS.bmp";
  2203. case EMarketMode::RESOURCE_ARTIFACT:
  2204. return "TPMRKABS.bmp";
  2205. case EMarketMode::ARTIFACT_RESOURCE:
  2206. return "TPMRKASS.bmp";
  2207. }
  2208. assert(0);
  2209. return "";
  2210. }
  2211. CMarketplaceWindow::CMarketplaceWindow(const IMarket *Market, const CGHeroInstance *Hero, EMarketMode::EMarketMode Mode)
  2212. : CTradeWindow(getBackgroundForMode(Mode), Market, Hero, Mode)
  2213. {
  2214. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2215. madeTransaction = false;
  2216. bool sliderNeeded = true;
  2217. new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  2218. std::string title;
  2219. if (market->o->ID == Obj::TOWN)
  2220. {
  2221. switch (mode)
  2222. {
  2223. break; case EMarketMode::CREATURE_RESOURCE:
  2224. title = CGI->townh->factions[ETownType::STRONGHOLD]->town->buildings[BuildingID::FREELANCERS_GUILD]->Name();
  2225. break; case EMarketMode::RESOURCE_ARTIFACT:
  2226. title = CGI->townh->factions[market->o->subID]->town->buildings[BuildingID::ARTIFACT_MERCHANT]->Name();
  2227. sliderNeeded = false;
  2228. break; case EMarketMode::ARTIFACT_RESOURCE:
  2229. title = CGI->townh->factions[market->o->subID]->town->buildings[BuildingID::ARTIFACT_MERCHANT]->Name();
  2230. sliderNeeded = false;
  2231. break; default:
  2232. title = CGI->generaltexth->allTexts[158];
  2233. }
  2234. }
  2235. else
  2236. {
  2237. switch (market->o->ID)
  2238. {
  2239. break; case Obj::BLACK_MARKET: title = CGI->generaltexth->allTexts[349];
  2240. break; case Obj::TRADING_POST: title = CGI->generaltexth->allTexts[159];
  2241. break; case Obj::TRADING_POST_SNOW: title = CGI->generaltexth->allTexts[159];
  2242. break; default: title = market->o->getObjectName();
  2243. }
  2244. }
  2245. new CLabel(300, 27, FONT_BIG, CENTER, Colors::YELLOW, title);
  2246. initItems(false);
  2247. initItems(true);
  2248. ok = new CAdventureMapButton(CGI->generaltexth->zelp[600],boost::bind(&CGuiHandler::popIntTotally,&GH,this),516,520,"IOK6432.DEF",SDLK_RETURN);
  2249. ok->assignedKeys.insert(SDLK_ESCAPE);
  2250. deal = new CAdventureMapButton(CGI->generaltexth->zelp[595],boost::bind(&CMarketplaceWindow::makeDeal,this),307,520,"TPMRKB.DEF");
  2251. deal->block(true);
  2252. if(sliderNeeded)
  2253. {
  2254. slider = new CSlider(231,490,137,nullptr,0,0);
  2255. slider->moved = boost::bind(&CMarketplaceWindow::sliderMoved,this,_1);
  2256. max = new CAdventureMapButton(CGI->generaltexth->zelp[596],boost::bind(&CMarketplaceWindow::setMax,this),229,520,"IRCBTNS.DEF");
  2257. max->block(true);
  2258. }
  2259. else
  2260. {
  2261. slider = nullptr;
  2262. max = nullptr;
  2263. deal->moveBy(Point(-30, 0));
  2264. }
  2265. Rect traderTextRect;
  2266. //left side
  2267. switch(Mode)
  2268. {
  2269. case EMarketMode::RESOURCE_RESOURCE:
  2270. case EMarketMode::RESOURCE_PLAYER:
  2271. case EMarketMode::RESOURCE_ARTIFACT:
  2272. new CLabel(154, 148, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[270]);
  2273. break;
  2274. case EMarketMode::CREATURE_RESOURCE:
  2275. //%s's Creatures
  2276. new CLabel(152, 102, FONT_SMALL, CENTER, Colors::WHITE,
  2277. boost::str(boost::format(CGI->generaltexth->allTexts[272]) % hero->name));
  2278. break;
  2279. case EMarketMode::ARTIFACT_RESOURCE:
  2280. //%s's Artifacts
  2281. new CLabel(152, 102, FONT_SMALL, CENTER, Colors::WHITE,
  2282. boost::str(boost::format(CGI->generaltexth->allTexts[272]) % hero->name));
  2283. break;
  2284. }
  2285. //right side
  2286. switch(Mode)
  2287. {
  2288. case EMarketMode::RESOURCE_RESOURCE:
  2289. case EMarketMode::CREATURE_RESOURCE:
  2290. case EMarketMode::RESOURCE_ARTIFACT:
  2291. case EMarketMode::ARTIFACT_RESOURCE:
  2292. new CLabel(445, 148, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[168]);
  2293. traderTextRect = Rect(316, 48, 260, 75);
  2294. break;
  2295. case EMarketMode::RESOURCE_PLAYER:
  2296. new CLabel(445, 55, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->allTexts[169]);
  2297. traderTextRect = Rect(28, 48, 260, 75);
  2298. break;
  2299. }
  2300. traderText = new CTextBox("", traderTextRect, 0, FONT_SMALL, CENTER);
  2301. int specialOffset = mode == EMarketMode::ARTIFACT_RESOURCE ? 35 : 0; //in selling artifacts mode we need to move res-res and art-res buttons down
  2302. if(printButtonFor(EMarketMode::RESOURCE_PLAYER))
  2303. new CAdventureMapButton(CGI->generaltexth->zelp[612],boost::bind(&CMarketplaceWindow::setMode,this, EMarketMode::RESOURCE_PLAYER), 18, 520,"TPMRKBU1.DEF");
  2304. if(printButtonFor(EMarketMode::RESOURCE_RESOURCE))
  2305. new CAdventureMapButton(CGI->generaltexth->zelp[605],boost::bind(&CMarketplaceWindow::setMode,this, EMarketMode::RESOURCE_RESOURCE), 516, 450 + specialOffset,"TPMRKBU5.DEF");
  2306. if(printButtonFor(EMarketMode::CREATURE_RESOURCE))
  2307. new CAdventureMapButton(CGI->generaltexth->zelp[599],boost::bind(&CMarketplaceWindow::setMode,this, EMarketMode::CREATURE_RESOURCE), 516, 485,"TPMRKBU4.DEF"); //was y=450, changed to not overlap res-res in some conditions
  2308. if(printButtonFor(EMarketMode::RESOURCE_ARTIFACT))
  2309. new CAdventureMapButton(CGI->generaltexth->zelp[598],boost::bind(&CMarketplaceWindow::setMode,this, EMarketMode::RESOURCE_ARTIFACT), 18, 450 + specialOffset,"TPMRKBU2.DEF");
  2310. if(printButtonFor(EMarketMode::ARTIFACT_RESOURCE))
  2311. new CAdventureMapButton(CGI->generaltexth->zelp[613],boost::bind(&CMarketplaceWindow::setMode,this, EMarketMode::ARTIFACT_RESOURCE), 18, 485,"TPMRKBU3.DEF"); //was y=450, changed to not overlap res-art in some conditions
  2312. updateTraderText();
  2313. }
  2314. CMarketplaceWindow::~CMarketplaceWindow()
  2315. {
  2316. hLeft = hRight = nullptr;
  2317. for(auto & elem : items[1])
  2318. delete elem;
  2319. for(auto & elem : items[0])
  2320. delete elem;
  2321. items[1].clear();
  2322. items[0].clear();
  2323. }
  2324. void CMarketplaceWindow::setMax()
  2325. {
  2326. slider->moveToMax();
  2327. }
  2328. void CMarketplaceWindow::makeDeal()
  2329. {
  2330. int sliderValue = 0;
  2331. if(slider)
  2332. sliderValue = slider->value;
  2333. else
  2334. sliderValue = !deal->isBlocked(); //should always be 1
  2335. if(!sliderValue)
  2336. return;
  2337. int leftIdToSend = -1;
  2338. switch (mode)
  2339. {
  2340. case EMarketMode::CREATURE_RESOURCE:
  2341. leftIdToSend = hLeft->serial;
  2342. break;
  2343. case EMarketMode::ARTIFACT_RESOURCE:
  2344. leftIdToSend = hLeft->getArtInstance()->id.getNum();
  2345. break;
  2346. default:
  2347. leftIdToSend = hLeft->id;
  2348. break;
  2349. }
  2350. if(slider)
  2351. {
  2352. LOCPLINT->cb->trade(market->o, mode, leftIdToSend, hRight->id, slider->value*r1, hero);
  2353. slider->moveTo(0);
  2354. }
  2355. else
  2356. {
  2357. LOCPLINT->cb->trade(market->o, mode, leftIdToSend, hRight->id, r2, hero);
  2358. }
  2359. madeTransaction = true;
  2360. hLeft = nullptr;
  2361. hRight = nullptr;
  2362. selectionChanged(true);
  2363. }
  2364. void CMarketplaceWindow::sliderMoved( int to )
  2365. {
  2366. redraw();
  2367. }
  2368. void CMarketplaceWindow::selectionChanged(bool side)
  2369. {
  2370. readyToTrade = hLeft && hRight;
  2371. if(mode == EMarketMode::RESOURCE_RESOURCE)
  2372. readyToTrade = readyToTrade && (hLeft->id != hRight->id); //for resource trade, two DIFFERENT resources must be selected
  2373. if(mode == EMarketMode::ARTIFACT_RESOURCE && !hLeft)
  2374. arts->unmarkSlots(false);
  2375. if(readyToTrade)
  2376. {
  2377. int soldItemId = hLeft->id;
  2378. market->getOffer(soldItemId, hRight->id, r1, r2, mode);
  2379. if(slider)
  2380. {
  2381. int newAmount = -1;
  2382. if(itemsType[1] == RESOURCE)
  2383. newAmount = LOCPLINT->cb->getResourceAmount(static_cast<Res::ERes>(soldItemId));
  2384. else if(itemsType[1] == CREATURE)
  2385. newAmount = hero->getStackCount(SlotID(hLeft->serial)) - (hero->Slots().size() == 1 && hero->needsLastStack());
  2386. else
  2387. assert(0);
  2388. slider->setAmount(newAmount / r1);
  2389. slider->moveTo(0);
  2390. max->block(false);
  2391. deal->block(false);
  2392. }
  2393. else if(itemsType[1] == RESOURCE) //buying -> check if we can afford transaction
  2394. {
  2395. deal->block(LOCPLINT->cb->getResourceAmount(static_cast<Res::ERes>(soldItemId)) < r1);
  2396. }
  2397. else
  2398. deal->block(false);
  2399. }
  2400. else
  2401. {
  2402. if(slider)
  2403. {
  2404. max->block(true);
  2405. slider->setAmount(0);
  2406. slider->moveTo(0);
  2407. }
  2408. deal->block(true);
  2409. }
  2410. if(side && itemsType[0] != PLAYER) //items[1] selection changed, recalculate offers
  2411. initSubs(false);
  2412. updateTraderText();
  2413. redraw();
  2414. }
  2415. bool CMarketplaceWindow::printButtonFor(EMarketMode::EMarketMode M) const
  2416. {
  2417. return market->allowsTrade(M) && M != mode && (hero || ( M != EMarketMode::CREATURE_RESOURCE && M != EMarketMode::RESOURCE_ARTIFACT && M != EMarketMode::ARTIFACT_RESOURCE ));
  2418. }
  2419. void CMarketplaceWindow::garrisonChanged()
  2420. {
  2421. if(mode != EMarketMode::CREATURE_RESOURCE)
  2422. return;
  2423. std::set<CTradeableItem *> toRemove;
  2424. getEmptySlots(toRemove);
  2425. removeItems(toRemove);
  2426. initSubs(true);
  2427. }
  2428. void CMarketplaceWindow::artifactsChanged(bool Left)
  2429. {
  2430. assert(!Left);
  2431. if(mode != EMarketMode::RESOURCE_ARTIFACT)
  2432. return;
  2433. std::vector<int> available = market->availableItemsIds(mode);
  2434. std::set<CTradeableItem *> toRemove;
  2435. for(CTradeableItem *t : items[0])
  2436. if(!vstd::contains(available, t->id))
  2437. toRemove.insert(t);
  2438. removeItems(toRemove);
  2439. redraw();
  2440. }
  2441. std::string CMarketplaceWindow::selectionSubtitle(bool Left) const
  2442. {
  2443. if(Left)
  2444. {
  2445. switch(itemsType[1])
  2446. {
  2447. case RESOURCE:
  2448. case CREATURE:
  2449. {
  2450. int val = slider
  2451. ? slider->value * r1
  2452. : (((deal->isBlocked())) ? 0 : r1);
  2453. return boost::lexical_cast<std::string>(val);
  2454. }
  2455. case ARTIFACT_INSTANCE:
  2456. return ((deal->isBlocked()) ? "0" : "1");
  2457. }
  2458. }
  2459. else
  2460. {
  2461. switch(itemsType[0])
  2462. {
  2463. case RESOURCE:
  2464. if(slider)
  2465. return boost::lexical_cast<std::string>( slider->value * r2 );
  2466. else
  2467. return boost::lexical_cast<std::string>(r2);
  2468. case ARTIFACT_TYPE:
  2469. return ((deal->isBlocked()) ? "0" : "1");
  2470. case PLAYER:
  2471. return (hRight ? CGI->generaltexth->capColors[hRight->id] : "");
  2472. }
  2473. }
  2474. return "???";
  2475. }
  2476. Point CMarketplaceWindow::selectionOffset(bool Left) const
  2477. {
  2478. if(Left)
  2479. {
  2480. switch(itemsType[1])
  2481. {
  2482. case RESOURCE:
  2483. return Point(122, 446);
  2484. case CREATURE:
  2485. return Point(128, 450);
  2486. case ARTIFACT_INSTANCE:
  2487. return Point(134, 466);
  2488. }
  2489. }
  2490. else
  2491. {
  2492. switch(itemsType[0])
  2493. {
  2494. case RESOURCE:
  2495. if(mode == EMarketMode::ARTIFACT_RESOURCE)
  2496. return Point(410, 469);
  2497. else
  2498. return Point(410, 446);
  2499. case ARTIFACT_TYPE:
  2500. return Point(425, 447);
  2501. case PLAYER:
  2502. return Point(417, 451);
  2503. }
  2504. }
  2505. assert(0);
  2506. return Point(0,0);
  2507. }
  2508. void CMarketplaceWindow::resourceChanged(int type, int val)
  2509. {
  2510. initSubs(true);
  2511. }
  2512. void CMarketplaceWindow::getBaseForPositions(EType type, int &dx, int &dy, int &x, int &y, int &h, int &w, bool Right, int &leftToRightOffset) const
  2513. {
  2514. switch(type)
  2515. {
  2516. case RESOURCE:
  2517. dx = 82;
  2518. dy = 79;
  2519. x = 39;
  2520. y = 180;
  2521. h = 66;
  2522. w = 74;
  2523. break;
  2524. case PLAYER:
  2525. dx = 83;
  2526. dy = 118;
  2527. h = 64;
  2528. w = 58;
  2529. x = 44;
  2530. y = 83;
  2531. assert(Right);
  2532. break;
  2533. case CREATURE://45,123
  2534. x = 45;
  2535. y = 123;
  2536. w = 58;
  2537. h = 64;
  2538. dx = 83;
  2539. dy = 98;
  2540. assert(!Right);
  2541. break;
  2542. case ARTIFACT_TYPE://45,123
  2543. x = 340-289;
  2544. y = 180;
  2545. w = 44;
  2546. h = 44;
  2547. dx = 83;
  2548. dy = 79;
  2549. break;
  2550. }
  2551. leftToRightOffset = 289;
  2552. }
  2553. void CMarketplaceWindow::updateTraderText()
  2554. {
  2555. if(readyToTrade)
  2556. {
  2557. if(mode == EMarketMode::RESOURCE_PLAYER)
  2558. {
  2559. //I can give %s to the %s player.
  2560. traderText->setText(boost::str(boost::format(CGI->generaltexth->allTexts[165]) % hLeft->getName() % hRight->getName()));
  2561. }
  2562. else if(mode == EMarketMode::RESOURCE_ARTIFACT)
  2563. {
  2564. //I can offer you the %s for %d %s of %s.
  2565. traderText->setText(boost::str(boost::format(CGI->generaltexth->allTexts[267]) % hRight->getName() % r1 % CGI->generaltexth->allTexts[160 + (r1==1)] % hLeft->getName()));
  2566. }
  2567. else if(mode == EMarketMode::RESOURCE_RESOURCE)
  2568. {
  2569. //I can offer you %d %s of %s for %d %s of %s.
  2570. traderText->setText(boost::str(boost::format(CGI->generaltexth->allTexts[157]) % r2 % CGI->generaltexth->allTexts[160 + (r2==1)] % hRight->getName() % r1 % CGI->generaltexth->allTexts[160 + (r1==1)] % hLeft->getName()));
  2571. }
  2572. else if(mode == EMarketMode::CREATURE_RESOURCE)
  2573. {
  2574. //I can offer you %d %s of %s for %d %s.
  2575. traderText->setText(boost::str(boost::format(CGI->generaltexth->allTexts[269]) % r2 % CGI->generaltexth->allTexts[160 + (r2==1)] % hRight->getName() % r1 % hLeft->getName(r1)));
  2576. }
  2577. else if(mode == EMarketMode::ARTIFACT_RESOURCE)
  2578. {
  2579. //I can offer you %d %s of %s for your %s.
  2580. traderText->setText(boost::str(boost::format(CGI->generaltexth->allTexts[268]) % r2 % CGI->generaltexth->allTexts[160 + (r2==1)] % hRight->getName() % hLeft->getName(r1)));
  2581. }
  2582. return;
  2583. }
  2584. int gnrtxtnr = -1;
  2585. if(madeTransaction)
  2586. {
  2587. if(mode == EMarketMode::RESOURCE_PLAYER)
  2588. gnrtxtnr = 166; //Are there any other resources you'd like to give away?
  2589. else
  2590. gnrtxtnr = 162; //You have received quite a bargain. I expect to make no profit on the deal. Can I interest you in any of my other wares?
  2591. }
  2592. else
  2593. {
  2594. if(mode == EMarketMode::RESOURCE_PLAYER)
  2595. gnrtxtnr = 167; //If you'd like to give any of your resources to another player, click on the item you wish to give and to whom.
  2596. else
  2597. gnrtxtnr = 163; //Please inspect our fine wares. If you feel like offering a trade, click on the items you wish to trade with and for.
  2598. }
  2599. traderText->setText(CGI->generaltexth->allTexts[gnrtxtnr]);
  2600. }
  2601. CAltarWindow::CAltarWindow(const IMarket *Market, const CGHeroInstance *Hero /*= nullptr*/, EMarketMode::EMarketMode Mode)
  2602. :CTradeWindow((Mode == EMarketMode::CREATURE_EXP ? "ALTARMON.bmp" : "ALTRART2.bmp"), Market, Hero, Mode)
  2603. {
  2604. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2605. if(Mode == EMarketMode::CREATURE_EXP)
  2606. {
  2607. //%s's Creatures
  2608. new CLabel(155, 30, FONT_SMALL, CENTER, Colors::YELLOW,
  2609. boost::str(boost::format(CGI->generaltexth->allTexts[272]) % hero->name));
  2610. //Altar of Sacrifice
  2611. new CLabel(450, 30, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[479]);
  2612. //To sacrifice creatures, move them from your army on to the Altar and click Sacrifice
  2613. new CTextBox(CGI->generaltexth->allTexts[480], Rect(320, 56, 256, 40), 0, FONT_SMALL, CENTER, Colors::YELLOW);
  2614. slider = new CSlider(231,481,137,nullptr,0,0);
  2615. slider->moved = boost::bind(&CAltarWindow::sliderMoved,this,_1);
  2616. max = new CAdventureMapButton(CGI->generaltexth->zelp[578],boost::bind(&CSlider::moveToMax, slider),147,520,"IRCBTNS.DEF");
  2617. sacrificedUnits.resize(GameConstants::ARMY_SIZE, 0);
  2618. sacrificeAll = new CAdventureMapButton(CGI->generaltexth->zelp[579],boost::bind(&CAltarWindow::SacrificeAll,this),393,520,"ALTARMY.DEF");
  2619. sacrificeBackpack = nullptr;
  2620. initItems(true);
  2621. mimicCres();
  2622. artIcon = nullptr;
  2623. }
  2624. else
  2625. {
  2626. //Sacrifice artifacts for experience
  2627. new CLabel(450, 34, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[477]);
  2628. //%s's Creatures
  2629. new CLabel(302, 423, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[478]);
  2630. sacrificeAll = new CAdventureMapButton(CGI->generaltexth->zelp[571], boost::bind(&CAltarWindow::SacrificeAll,this),393,520,"ALTFILL.DEF");
  2631. sacrificeAll->block(hero->artifactsInBackpack.empty() && hero->artifactsWorn.empty());
  2632. sacrificeBackpack = new CAdventureMapButton(CGI->generaltexth->zelp[570],boost::bind(&CAltarWindow::SacrificeBackpack,this),147,520,"ALTEMBK.DEF");
  2633. sacrificeBackpack->block(hero->artifactsInBackpack.empty());
  2634. slider = nullptr;
  2635. max = nullptr;
  2636. initItems(true);
  2637. initItems(false);
  2638. artIcon = new CAnimImage("ARTIFACT", 0, 0, 281, 442);
  2639. artIcon->disable();
  2640. }
  2641. //Experience needed to reach next level
  2642. new CTextBox(CGI->generaltexth->allTexts[475], Rect(15, 415, 125, 50), 0, FONT_SMALL, CENTER, Colors::YELLOW);
  2643. //Total experience on the Altar
  2644. new CTextBox(CGI->generaltexth->allTexts[476], Rect(15, 495, 125, 40), 0, FONT_SMALL, CENTER, Colors::YELLOW);
  2645. new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  2646. ok = new CAdventureMapButton(CGI->generaltexth->zelp[568],boost::bind(&CGuiHandler::popIntTotally,&GH,this),516,520,"IOK6432.DEF",SDLK_RETURN);
  2647. ok->assignedKeys.insert(SDLK_ESCAPE);
  2648. deal = new CAdventureMapButton(CGI->generaltexth->zelp[585],boost::bind(&CAltarWindow::makeDeal,this),269,520,"ALTSACR.DEF");
  2649. if(Hero->getAlignment() != ::EAlignment::EVIL && Mode == EMarketMode::CREATURE_EXP)
  2650. new CAdventureMapButton(CGI->generaltexth->zelp[580], boost::bind(&CTradeWindow::setMode,this, EMarketMode::ARTIFACT_EXP), 516, 421, "ALTART.DEF");
  2651. if(Hero->getAlignment() != ::EAlignment::GOOD && Mode == EMarketMode::ARTIFACT_EXP)
  2652. new CAdventureMapButton(CGI->generaltexth->zelp[572], boost::bind(&CTradeWindow::setMode,this, EMarketMode::CREATURE_EXP), 516, 421, "ALTSACC.DEF");
  2653. expPerUnit.resize(GameConstants::ARMY_SIZE, 0);
  2654. getExpValues();
  2655. expToLevel = new CLabel(73, 475, FONT_SMALL, CENTER);
  2656. expOnAltar = new CLabel(73, 543, FONT_SMALL, CENTER);
  2657. setExpToLevel();
  2658. calcTotalExp();
  2659. blockTrade();
  2660. }
  2661. CAltarWindow::~CAltarWindow()
  2662. {
  2663. }
  2664. void CAltarWindow::getBaseForPositions(EType type, int &dx, int &dy, int &x, int &y, int &h, int &w, bool Right, int &leftToRightOffset) const
  2665. {
  2666. leftToRightOffset = 289;
  2667. x = 45;
  2668. y = 110;
  2669. w = 58;
  2670. h = 64;
  2671. dx = 83;
  2672. dy = 98;
  2673. }
  2674. void CAltarWindow::sliderMoved(int to)
  2675. {
  2676. sacrificedUnits[hLeft->serial] = to;
  2677. updateRight(hRight);
  2678. deal->block(!to);
  2679. calcTotalExp();
  2680. redraw();
  2681. }
  2682. void CAltarWindow::makeDeal()
  2683. {
  2684. if(mode == EMarketMode::CREATURE_EXP)
  2685. {
  2686. blockTrade();
  2687. slider->value = 0;
  2688. std::vector<int> toSacrifice = sacrificedUnits;
  2689. for (int i = 0; i < toSacrifice.size(); i++)
  2690. {
  2691. if(toSacrifice[i])
  2692. LOCPLINT->cb->trade(market->o, mode, i, 0, toSacrifice[i], hero);
  2693. }
  2694. for(int& val : sacrificedUnits)
  2695. val = 0;
  2696. for(CTradeableItem *t : items[0])
  2697. {
  2698. t->setType(CREATURE_PLACEHOLDER);
  2699. t->subtitle = "";
  2700. }
  2701. }
  2702. else
  2703. {
  2704. for(const CArtifactInstance *art : arts->artifactsOnAltar) //sacrifice each artifact on the list
  2705. {
  2706. LOCPLINT->cb->trade(market->o, mode, hero->getArtPos(art), -1, 1, hero);
  2707. }
  2708. arts->artifactsOnAltar.clear();
  2709. for(CTradeableItem *t : items[0])
  2710. {
  2711. t->setID(-1);
  2712. t->subtitle = "";
  2713. }
  2714. arts->commonInfo->reset();
  2715. //arts->scrollBackpack(0);
  2716. deal->block(true);
  2717. }
  2718. calcTotalExp();
  2719. }
  2720. void CAltarWindow::SacrificeAll()
  2721. {
  2722. if(mode == EMarketMode::CREATURE_EXP)
  2723. {
  2724. bool movedAnything = false;
  2725. for(CTradeableItem *t : items[1])
  2726. sacrificedUnits[t->serial] = hero->getStackCount(SlotID(t->serial));
  2727. sacrificedUnits[items[1].front()->serial]--;
  2728. for(CTradeableItem *t : items[0])
  2729. {
  2730. updateRight(t);
  2731. if(t->type == CREATURE)
  2732. movedAnything = true;
  2733. }
  2734. deal->block(!movedAnything);
  2735. calcTotalExp();
  2736. }
  2737. else
  2738. {
  2739. for(auto i = hero->artifactsWorn.cbegin(); i != hero->artifactsWorn.cend(); i++)
  2740. {
  2741. if(i->second.artifact->artType->id != ArtifactID::ART_LOCK) //ignore locks from assembled artifacts
  2742. moveFromSlotToAltar(i->first, nullptr, i->second.artifact);
  2743. }
  2744. SacrificeBackpack();
  2745. }
  2746. redraw();
  2747. }
  2748. void CAltarWindow::selectionChanged(bool side)
  2749. {
  2750. if(mode != EMarketMode::CREATURE_EXP)
  2751. return;
  2752. CTradeableItem *&selected = side ? hLeft : hRight;
  2753. CTradeableItem *&theOther = side ? hRight : hLeft;
  2754. theOther = *std::find_if(items[!side].begin(), items[!side].end(), [&](const CTradeableItem * item)
  2755. {
  2756. return item->serial == selected->serial;
  2757. });
  2758. int stackCount = 0;
  2759. for (int i = 0; i < GameConstants::ARMY_SIZE; i++)
  2760. if(hero->getStackCount(SlotID(i)) > sacrificedUnits[i])
  2761. stackCount++;
  2762. slider->setAmount(hero->getStackCount(SlotID(hLeft->serial)) - (stackCount == 1));
  2763. slider->block(!slider->amount);
  2764. slider->value = sacrificedUnits[hLeft->serial];
  2765. max->block(!slider->amount);
  2766. readyToTrade = true;
  2767. redraw();
  2768. }
  2769. void CAltarWindow::mimicCres()
  2770. {
  2771. std::vector<Rect> positions;
  2772. getPositionsFor(positions, false, CREATURE);
  2773. for(CTradeableItem *t : items[1])
  2774. {
  2775. auto hlp = new CTradeableItem(positions[t->serial].topLeft(), CREATURE_PLACEHOLDER, t->id, false, t->serial);
  2776. hlp->pos = positions[t->serial] + this->pos.topLeft();
  2777. items[0].push_back(hlp);
  2778. }
  2779. }
  2780. Point CAltarWindow::selectionOffset(bool Left) const
  2781. {
  2782. if(Left)
  2783. return Point(150, 421);
  2784. else
  2785. return Point(396, 421);
  2786. }
  2787. std::string CAltarWindow::selectionSubtitle(bool Left) const
  2788. {
  2789. if(Left && slider && hLeft)
  2790. return boost::lexical_cast<std::string>(slider->value);
  2791. else if(!Left && hRight)
  2792. return hRight->subtitle;
  2793. else
  2794. return "";
  2795. }
  2796. void CAltarWindow::artifactsChanged(bool left)
  2797. {
  2798. }
  2799. void CAltarWindow::garrisonChanged()
  2800. {
  2801. if(mode != EMarketMode::CREATURE_EXP)
  2802. return;
  2803. std::set<CTradeableItem *> empty;
  2804. getEmptySlots(empty);
  2805. for(CTradeableItem *t : empty)
  2806. {
  2807. removeItem(*std::find_if(items[0].begin(), items[0].end(), [&](const CTradeableItem * item)
  2808. {
  2809. return item->serial == t->serial;
  2810. }));
  2811. }
  2812. initSubs(true);
  2813. getExpValues();
  2814. }
  2815. void CAltarWindow::getExpValues()
  2816. {
  2817. int dump;
  2818. for(CTradeableItem *t : items[1])
  2819. if(t->id >= 0)
  2820. market->getOffer(t->id, 0, dump, expPerUnit[t->serial], EMarketMode::CREATURE_EXP);
  2821. }
  2822. void CAltarWindow::calcTotalExp()
  2823. {
  2824. int val = 0;
  2825. if(mode == EMarketMode::CREATURE_EXP)
  2826. {
  2827. for (int i = 0; i < sacrificedUnits.size(); i++)
  2828. {
  2829. val += expPerUnit[i] * sacrificedUnits[i];
  2830. }
  2831. }
  2832. else
  2833. {
  2834. for(const CArtifactInstance *art : arts->artifactsOnAltar)
  2835. {
  2836. int dmp, valOfArt;
  2837. market->getOffer(art->artType->id, 0, dmp, valOfArt, mode);
  2838. val += valOfArt; //WAS val += valOfArt * arts->artifactsOnAltar.count(*i);
  2839. }
  2840. }
  2841. val = hero->calculateXp(val);
  2842. expOnAltar->setText(boost::lexical_cast<std::string>(val));
  2843. }
  2844. void CAltarWindow::setExpToLevel()
  2845. {
  2846. expToLevel->setText(boost::lexical_cast<std::string>(CGI->heroh->reqExp(CGI->heroh->level(hero->exp)+1) - hero->exp));
  2847. }
  2848. void CAltarWindow::blockTrade()
  2849. {
  2850. hLeft = hRight = nullptr;
  2851. readyToTrade = false;
  2852. if(slider)
  2853. {
  2854. slider->block(true);
  2855. max->block(true);
  2856. }
  2857. deal->block(true);
  2858. }
  2859. void CAltarWindow::updateRight(CTradeableItem *toUpdate)
  2860. {
  2861. int val = sacrificedUnits[toUpdate->serial];
  2862. toUpdate->setType(val ? CREATURE : CREATURE_PLACEHOLDER);
  2863. toUpdate->subtitle = val ? boost::str(boost::format(CGI->generaltexth->allTexts[122]) % boost::lexical_cast<std::string>(val * expPerUnit[toUpdate->serial])) : ""; //%s exp
  2864. }
  2865. int CAltarWindow::firstFreeSlot()
  2866. {
  2867. int ret = -1;
  2868. while(items[0][++ret]->id >= 0 && ret + 1 < items[0].size());
  2869. return ret < items[0].size() ? ret : -1;
  2870. }
  2871. void CAltarWindow::SacrificeBackpack()
  2872. {
  2873. std::multiset<const CArtifactInstance *> toOmmit = arts->artifactsOnAltar;
  2874. for (auto & elem : hero->artifactsInBackpack)
  2875. {
  2876. if(vstd::contains(toOmmit, elem.artifact))
  2877. {
  2878. toOmmit -= elem.artifact;
  2879. continue;
  2880. }
  2881. putOnAltar(nullptr, elem.artifact);
  2882. }
  2883. arts->scrollBackpack(0);
  2884. calcTotalExp();
  2885. }
  2886. void CAltarWindow::artifactPicked()
  2887. {
  2888. redraw();
  2889. }
  2890. void CAltarWindow::showAll(SDL_Surface * to)
  2891. {
  2892. CTradeWindow::showAll(to);
  2893. if(mode == EMarketMode::ARTIFACT_EXP && arts && arts->commonInfo->src.art)
  2894. {
  2895. artIcon->setFrame(arts->commonInfo->src.art->artType->iconIndex);
  2896. artIcon->showAll(to);
  2897. int dmp, val;
  2898. market->getOffer(arts->commonInfo->src.art->artType->id, 0, dmp, val, EMarketMode::ARTIFACT_EXP);
  2899. printAtMiddleLoc(boost::lexical_cast<std::string>(val), 304, 498, FONT_SMALL, Colors::WHITE, to);
  2900. }
  2901. }
  2902. bool CAltarWindow::putOnAltar(CTradeableItem* altarSlot, const CArtifactInstance *art)
  2903. {
  2904. int artID = art->artType->id;
  2905. if(artID != 1 && artID < 7) //special art
  2906. {
  2907. logGlobal->warnStream() << "Cannot put special artifact on altar!";
  2908. return false;
  2909. }
  2910. if(!altarSlot)
  2911. {
  2912. int slotIndex = firstFreeSlot();
  2913. if(slotIndex < 0)
  2914. {
  2915. logGlobal->warnStream() << "No free slots on altar!";
  2916. return false;
  2917. }
  2918. altarSlot = items[0][slotIndex];
  2919. }
  2920. int dmp, val;
  2921. market->getOffer(artID, 0, dmp, val, EMarketMode::ARTIFACT_EXP);
  2922. arts->artifactsOnAltar.insert(art);
  2923. altarSlot->setArtInstance(art);
  2924. altarSlot->subtitle = boost::lexical_cast<std::string>(val);
  2925. deal->block(false);
  2926. return true;
  2927. }
  2928. void CAltarWindow::moveFromSlotToAltar(ArtifactPosition slotID, CTradeableItem* altarSlot, const CArtifactInstance *art)
  2929. {
  2930. auto freeBackpackSlot = ArtifactPosition(hero->artifactsInBackpack.size() + GameConstants::BACKPACK_START);
  2931. if(arts->commonInfo->src.art)
  2932. {
  2933. arts->commonInfo->dst.slotID = freeBackpackSlot;
  2934. arts->commonInfo->dst.AOH = arts;
  2935. }
  2936. if(putOnAltar(altarSlot, art))
  2937. {
  2938. if(slotID < GameConstants::BACKPACK_START)
  2939. LOCPLINT->cb->swapArtifacts(ArtifactLocation(hero, slotID), ArtifactLocation(hero, freeBackpackSlot));
  2940. else
  2941. {
  2942. arts->commonInfo->src.clear();
  2943. arts->commonInfo->dst.clear();
  2944. CCS->curh->dragAndDropCursor(nullptr);
  2945. arts->unmarkSlots(false);
  2946. }
  2947. }
  2948. }
  2949. void CSystemOptionsWindow::setMusicVolume( int newVolume )
  2950. {
  2951. Settings volume = settings.write["general"]["music"];
  2952. volume->Float() = newVolume;
  2953. }
  2954. void CSystemOptionsWindow::setSoundVolume( int newVolume )
  2955. {
  2956. Settings volume = settings.write["general"]["sound"];
  2957. volume->Float() = newVolume;
  2958. }
  2959. void CSystemOptionsWindow::setHeroMoveSpeed( int newSpeed )
  2960. {
  2961. Settings speed = settings.write["adventure"]["heroSpeed"];
  2962. speed->Float() = newSpeed;
  2963. }
  2964. void CSystemOptionsWindow::setMapScrollingSpeed( int newSpeed )
  2965. {
  2966. Settings speed = settings.write["adventure"]["scrollSpeed"];
  2967. speed->Float() = newSpeed;
  2968. }
  2969. CSystemOptionsWindow::CSystemOptionsWindow():
  2970. CWindowObject(PLAYER_COLORED, "SysOpBck"),
  2971. onFullscreenChanged(settings.listen["video"]["fullscreen"])
  2972. {
  2973. OBJ_CONSTRUCTION_CAPTURING_ALL;
  2974. title = new CLabel(242, 32, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[568]);
  2975. const JsonNode & texts = CGI->generaltexth->localizedTexts["systemOptions"];
  2976. //left window section
  2977. leftGroup = new CLabelGroup(FONT_MEDIUM, CENTER, Colors::YELLOW);
  2978. leftGroup->add(122, 64, CGI->generaltexth->allTexts[569]);
  2979. leftGroup->add(122, 130, CGI->generaltexth->allTexts[570]);
  2980. leftGroup->add(122, 196, CGI->generaltexth->allTexts[571]);
  2981. leftGroup->add(122, 262, texts["resolutionButton"]["label"].String());
  2982. leftGroup->add(122, 347, CGI->generaltexth->allTexts[394]);
  2983. leftGroup->add(122, 412, CGI->generaltexth->allTexts[395]);
  2984. //right section
  2985. rightGroup = new CLabelGroup(FONT_MEDIUM, TOPLEFT, Colors::WHITE);
  2986. rightGroup->add(282, 57, CGI->generaltexth->allTexts[572]);
  2987. rightGroup->add(282, 89, CGI->generaltexth->allTexts[573]);
  2988. rightGroup->add(282, 121, CGI->generaltexth->allTexts[574]);
  2989. rightGroup->add(282, 153, CGI->generaltexth->allTexts[577]);
  2990. rightGroup->add(282, 185, texts["creatureWindowButton"]["label"].String());
  2991. rightGroup->add(282, 217, texts["fullscreenButton"]["label"].String());
  2992. //setting up buttons
  2993. load = new CAdventureMapButton (CGI->generaltexth->zelp[321].first, CGI->generaltexth->zelp[321].second,
  2994. boost::bind(&CSystemOptionsWindow::bloadf, this), 246, 298, "SOLOAD.DEF", SDLK_l);
  2995. load->swappedImages = true;
  2996. load->update();
  2997. save = new CAdventureMapButton (CGI->generaltexth->zelp[322].first, CGI->generaltexth->zelp[322].second,
  2998. boost::bind(&CSystemOptionsWindow::bsavef, this), 357, 298, "SOSAVE.DEF", SDLK_s);
  2999. save->swappedImages = true;
  3000. save->update();
  3001. restart = new CAdventureMapButton (CGI->generaltexth->zelp[323].first, CGI->generaltexth->zelp[323].second,
  3002. boost::bind(&CSystemOptionsWindow::brestartf, this), 246, 357, "SORSTRT", SDLK_r);
  3003. restart->swappedImages = true;
  3004. restart->update();
  3005. mainMenu = new CAdventureMapButton (CGI->generaltexth->zelp[320].first, CGI->generaltexth->zelp[320].second,
  3006. boost::bind(&CSystemOptionsWindow::bmainmenuf, this), 357, 357, "SOMAIN.DEF", SDLK_m);
  3007. mainMenu->swappedImages = true;
  3008. mainMenu->update();
  3009. quitGame = new CAdventureMapButton (CGI->generaltexth->zelp[324].first, CGI->generaltexth->zelp[324].second,
  3010. boost::bind(&CSystemOptionsWindow::bquitf, this), 246, 415, "soquit.def", SDLK_q);
  3011. quitGame->swappedImages = true;
  3012. quitGame->update();
  3013. backToMap = new CAdventureMapButton (CGI->generaltexth->zelp[325].first, CGI->generaltexth->zelp[325].second,
  3014. boost::bind(&CSystemOptionsWindow::breturnf, this), 357, 415, "soretrn.def", SDLK_RETURN);
  3015. backToMap->swappedImages = true;
  3016. backToMap->update();
  3017. backToMap->assignedKeys.insert(SDLK_ESCAPE);
  3018. heroMoveSpeed = new CHighlightableButtonsGroup(0);
  3019. heroMoveSpeed->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[349].second),CGI->generaltexth->zelp[349].second, "sysopb1.def", 28, 77, 1);
  3020. heroMoveSpeed->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[350].second),CGI->generaltexth->zelp[350].second, "sysopb2.def", 76, 77, 2);
  3021. heroMoveSpeed->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[351].second),CGI->generaltexth->zelp[351].second, "sysopb3.def", 124, 77, 4);
  3022. heroMoveSpeed->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[352].second),CGI->generaltexth->zelp[352].second, "sysopb4.def", 172, 77, 8);
  3023. heroMoveSpeed->select(settings["adventure"]["heroSpeed"].Float(), 1);
  3024. heroMoveSpeed->onChange = boost::bind(&CSystemOptionsWindow::setHeroMoveSpeed, this, _1);
  3025. mapScrollSpeed = new CHighlightableButtonsGroup(0);
  3026. mapScrollSpeed->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[357].second),CGI->generaltexth->zelp[357].second, "sysopb9.def", 28, 210, 1);
  3027. mapScrollSpeed->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[358].second),CGI->generaltexth->zelp[358].second, "sysob10.def", 92, 210, 2);
  3028. mapScrollSpeed->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[359].second),CGI->generaltexth->zelp[359].second, "sysob11.def", 156, 210, 4);
  3029. mapScrollSpeed->select(settings["adventure"]["scrollSpeed"].Float(), 1);
  3030. mapScrollSpeed->onChange = boost::bind(&CSystemOptionsWindow::setMapScrollingSpeed, this, _1);
  3031. musicVolume = new CHighlightableButtonsGroup(0, true);
  3032. for(int i=0; i<10; ++i)
  3033. musicVolume->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[326+i].second),CGI->generaltexth->zelp[326+i].second, "syslb.def", 29 + 19*i, 359, i*11);
  3034. musicVolume->select(CCS->musich->getVolume(), 1);
  3035. musicVolume->onChange = boost::bind(&CSystemOptionsWindow::setMusicVolume, this, _1);
  3036. effectsVolume = new CHighlightableButtonsGroup(0, true);
  3037. for(int i=0; i<10; ++i)
  3038. effectsVolume->addButton(boost::assign::map_list_of(0,CGI->generaltexth->zelp[336+i].second),CGI->generaltexth->zelp[336+i].second, "syslb.def", 29 + 19*i, 425, i*11);
  3039. effectsVolume->select(CCS->soundh->getVolume(), 1);
  3040. effectsVolume->onChange = boost::bind(&CSystemOptionsWindow::setSoundVolume, this, _1);
  3041. showReminder = new CHighlightableButton(
  3042. boost::bind(&CSystemOptionsWindow::toggleReminder, this, true), boost::bind(&CSystemOptionsWindow::toggleReminder, this, false),
  3043. std::map<int,std::string>(), CGI->generaltexth->zelp[361].second, false, "sysopchk.def", nullptr, 246, 87, false);
  3044. quickCombat = new CHighlightableButton(
  3045. boost::bind(&CSystemOptionsWindow::toggleQuickCombat, this, true), boost::bind(&CSystemOptionsWindow::toggleQuickCombat, this, false),
  3046. std::map<int,std::string>(), CGI->generaltexth->zelp[362].second, false, "sysopchk.def", nullptr, 246, 87+32, false);
  3047. spellbookAnim = new CHighlightableButton(
  3048. boost::bind(&CSystemOptionsWindow::toggleSpellbookAnim, this, true), boost::bind(&CSystemOptionsWindow::toggleSpellbookAnim, this, false),
  3049. std::map<int,std::string>(), CGI->generaltexth->zelp[364].second, false, "sysopchk.def", nullptr, 246, 87+64, false);
  3050. newCreatureWin = new CHighlightableButton(
  3051. boost::bind(&CSystemOptionsWindow::toggleCreatureWin, this, true), boost::bind(&CSystemOptionsWindow::toggleCreatureWin, this, false),
  3052. std::map<int,std::string>(), texts["creatureWindowButton"]["help"].String(), false, "sysopchk.def", nullptr, 246, 183, false);
  3053. fullscreen = new CHighlightableButton(
  3054. boost::bind(&CSystemOptionsWindow::toggleFullscreen, this, true), boost::bind(&CSystemOptionsWindow::toggleFullscreen, this, false),
  3055. std::map<int,std::string>(), texts["fullscreenButton"]["help"].String(), false, "sysopchk.def", nullptr, 246, 215, false);
  3056. showReminder->select(settings["adventure"]["heroReminder"].Bool());
  3057. quickCombat->select(settings["adventure"]["quickCombat"].Bool());
  3058. spellbookAnim->select(settings["video"]["spellbookAnimation"].Bool());
  3059. newCreatureWin->select(settings["general"]["classicCreatureWindow"].Bool());
  3060. fullscreen->select(settings["video"]["fullscreen"].Bool());
  3061. onFullscreenChanged([&](const JsonNode &newState){ fullscreen->select(newState.Bool());});
  3062. gameResButton = new CAdventureMapButton("", texts["resolutionButton"]["help"].String(),
  3063. boost::bind(&CSystemOptionsWindow::selectGameRes, this),
  3064. 28, 275,"SYSOB12", SDLK_g);
  3065. std::string resText;
  3066. resText += boost::lexical_cast<std::string>(settings["video"]["screenRes"]["width"].Float());
  3067. resText += "x";
  3068. resText += boost::lexical_cast<std::string>(settings["video"]["screenRes"]["height"].Float());
  3069. gameResLabel = new CLabel(170, 292, FONT_MEDIUM, CENTER, Colors::YELLOW, resText);
  3070. }
  3071. void CSystemOptionsWindow::selectGameRes()
  3072. {
  3073. std::vector<std::string> items;
  3074. const JsonNode & texts = CGI->generaltexth->localizedTexts["systemOptions"]["resolutionMenu"];
  3075. for( config::CConfigHandler::GuiOptionsMap::value_type& value : conf.guiOptions)
  3076. {
  3077. std::string resX = boost::lexical_cast<std::string>(value.first.first);
  3078. std::string resY = boost::lexical_cast<std::string>(value.first.second);
  3079. items.push_back(resX + 'x' + resY);
  3080. }
  3081. GH.pushInt(new CObjectListWindow(items, nullptr, texts["label"].String(), texts["help"].String(),
  3082. boost::bind(&CSystemOptionsWindow::setGameRes, this, _1)));
  3083. }
  3084. void CSystemOptionsWindow::setGameRes(int index)
  3085. {
  3086. auto iter = conf.guiOptions.begin();
  3087. std::advance(iter, index);
  3088. //do not set resolution to illegal one (0x0)
  3089. assert(iter!=conf.guiOptions.end() && iter->first.first > 0 && iter->first.second > 0);
  3090. Settings gameRes = settings.write["video"]["screenRes"];
  3091. gameRes["width"].Float() = iter->first.first;
  3092. gameRes["height"].Float() = iter->first.second;
  3093. std::string resText;
  3094. resText += boost::lexical_cast<std::string>(iter->first.first);
  3095. resText += "x";
  3096. resText += boost::lexical_cast<std::string>(iter->first.second);
  3097. gameResLabel->setText(resText);
  3098. }
  3099. void CSystemOptionsWindow::toggleReminder(bool on)
  3100. {
  3101. Settings heroReminder = settings.write["adventure"]["heroReminder"];
  3102. heroReminder->Bool() = on;
  3103. }
  3104. void CSystemOptionsWindow::toggleQuickCombat(bool on)
  3105. {
  3106. Settings quickCombat = settings.write["adventure"]["quickCombat"];
  3107. quickCombat->Bool() = on;
  3108. }
  3109. void CSystemOptionsWindow::toggleSpellbookAnim(bool on)
  3110. {
  3111. Settings quickCombat = settings.write["video"]["spellbookAnimation"];
  3112. quickCombat->Bool() = on;
  3113. }
  3114. void CSystemOptionsWindow::toggleCreatureWin(bool on)
  3115. {
  3116. Settings classicCreatureWindow = settings.write["general"]["classicCreatureWindow"];
  3117. classicCreatureWindow->Bool() = on;
  3118. }
  3119. void CSystemOptionsWindow::toggleFullscreen(bool on)
  3120. {
  3121. Settings fullscreen = settings.write["video"]["fullscreen"];
  3122. fullscreen->Bool() = on;
  3123. }
  3124. void CSystemOptionsWindow::bquitf()
  3125. {
  3126. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[578], [this]{ closeAndPushEvent(SDL_QUIT); }, 0);
  3127. }
  3128. void CSystemOptionsWindow::breturnf()
  3129. {
  3130. GH.popIntTotally(this);
  3131. }
  3132. void CSystemOptionsWindow::bmainmenuf()
  3133. {
  3134. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[578], [this]{ closeAndPushEvent(SDL_USEREVENT, RETURN_TO_MAIN_MENU); }, 0);
  3135. }
  3136. void CSystemOptionsWindow::bloadf()
  3137. {
  3138. GH.popIntTotally(this);
  3139. LOCPLINT->proposeLoadingGame();
  3140. }
  3141. void CSystemOptionsWindow::bsavef()
  3142. {
  3143. GH.popIntTotally(this);
  3144. GH.pushInt(new CSavingScreen(CPlayerInterface::howManyPeople > 1));
  3145. }
  3146. void CSystemOptionsWindow::brestartf()
  3147. {
  3148. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[67], [this]{ closeAndPushEvent(SDL_USEREVENT, RESTART_GAME); }, 0);
  3149. }
  3150. void CSystemOptionsWindow::closeAndPushEvent(int eventType, int code /*= 0*/)
  3151. {
  3152. GH.popIntTotally(this);
  3153. GH.pushSDLEvent(eventType, code);
  3154. }
  3155. CTavernWindow::CTavernWindow(const CGObjectInstance *TavernObj):
  3156. CWindowObject(PLAYER_COLORED, "TPTAVERN"),
  3157. tavernObj(TavernObj)
  3158. {
  3159. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3160. std::vector<const CGHeroInstance*> h = LOCPLINT->cb->getAvailableHeroes(TavernObj);
  3161. if(h.size() < 2)
  3162. h.resize(2, nullptr);
  3163. h1 = new HeroPortrait(selected,0,72,299,h[0]);
  3164. h2 = new HeroPortrait(selected,1,162,299,h[1]);
  3165. selected = 0;
  3166. if (!h[0])
  3167. selected = 1;
  3168. if (!h[0] && !h[1])
  3169. selected = -1;
  3170. oldSelected = -1;
  3171. new CLabel(200, 35, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[37]);
  3172. new CLabel(320, 328, FONT_SMALL, CENTER, Colors::WHITE, "2500");
  3173. new CTextBox(LOCPLINT->cb->getTavernGossip(tavernObj), Rect(32, 190, 330, 68), 0, FONT_SMALL, CENTER, Colors::WHITE);
  3174. new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  3175. cancel = new CAdventureMapButton(CGI->generaltexth->tavernInfo[7],"", boost::bind(&CTavernWindow::close, this), 310, 428, "ICANCEL.DEF", SDLK_ESCAPE);
  3176. recruit = new CAdventureMapButton("", "", boost::bind(&CTavernWindow::recruitb, this), 272, 355, "TPTAV01.DEF", SDLK_RETURN);
  3177. thiefGuild = new CAdventureMapButton(CGI->generaltexth->tavernInfo[5],"", boost::bind(&CTavernWindow::thievesguildb, this), 22, 428, "TPTAV02.DEF", SDLK_t);
  3178. if(LOCPLINT->cb->getResourceAmount(Res::GOLD) < 2500) //not enough gold
  3179. {
  3180. recruit->hoverTexts[0] = CGI->generaltexth->tavernInfo[0]; //Cannot afford a Hero
  3181. recruit->block(true);
  3182. }
  3183. else if(LOCPLINT->castleInt && LOCPLINT->cb->howManyHeroes(true) >= VLC->modh->settings.MAX_HEROES_AVAILABLE_PER_PLAYER)
  3184. {
  3185. recruit->hoverTexts[0] = CGI->generaltexth->tavernInfo[1]; //Cannot recruit. You already have %d Heroes.
  3186. boost::algorithm::replace_first(recruit->hoverTexts[0],"%d",boost::lexical_cast<std::string>(LOCPLINT->cb->howManyHeroes(true)));
  3187. recruit->block(true);
  3188. }
  3189. else if((!LOCPLINT->castleInt) && LOCPLINT->cb->howManyHeroes(false) >= VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER)
  3190. {
  3191. recruit->hoverTexts[0] = CGI->generaltexth->tavernInfo[1]; //Cannot recruit. You already have %d Heroes.
  3192. boost::algorithm::replace_first(recruit->hoverTexts[0], "%d", boost::lexical_cast<std::string>(LOCPLINT->cb->howManyHeroes(false)));
  3193. recruit->block(true);
  3194. }
  3195. else if(LOCPLINT->castleInt && LOCPLINT->castleInt->town->visitingHero)
  3196. {
  3197. recruit->hoverTexts[0] = CGI->generaltexth->tavernInfo[2]; //Cannot recruit. You already have a Hero in this town.
  3198. recruit->block(true);
  3199. }
  3200. else
  3201. {
  3202. if(selected == -1)
  3203. recruit->block(true);
  3204. }
  3205. if (LOCPLINT->castleInt)
  3206. CCS->videoh->open(LOCPLINT->castleInt->town->town->clientInfo.tavernVideo);
  3207. else
  3208. CCS->videoh->open("TAVERN.BIK");
  3209. }
  3210. void CTavernWindow::recruitb()
  3211. {
  3212. const CGHeroInstance *toBuy = (selected ? h2 : h1)->h;
  3213. const CGObjectInstance *obj = tavernObj;
  3214. close();
  3215. LOCPLINT->cb->recruitHero(obj, toBuy);
  3216. }
  3217. void CTavernWindow::thievesguildb()
  3218. {
  3219. GH.pushInt( new CThievesGuildWindow(tavernObj) );
  3220. }
  3221. CTavernWindow::~CTavernWindow()
  3222. {
  3223. CCS->videoh->close();
  3224. }
  3225. void CTavernWindow::show(SDL_Surface * to)
  3226. {
  3227. CWindowObject::show(to);
  3228. CCS->videoh->update(pos.x+70, pos.y+56, to, true, false);
  3229. if(selected >= 0)
  3230. {
  3231. HeroPortrait *sel = selected ? h2 : h1;
  3232. if (selected != oldSelected && !recruit->isBlocked())
  3233. {
  3234. // Selected hero just changed. Update RECRUIT button hover text if recruitment is allowed.
  3235. oldSelected = selected;
  3236. recruit->hoverTexts[0] = CGI->generaltexth->tavernInfo[3]; //Recruit %s the %s
  3237. boost::algorithm::replace_first(recruit->hoverTexts[0],"%s",sel->h->name);
  3238. boost::algorithm::replace_first(recruit->hoverTexts[0],"%s",sel->h->type->heroClass->name);
  3239. }
  3240. printAtMiddleWBLoc(sel->description, 146, 395, FONT_SMALL, 200, Colors::WHITE, to);
  3241. CSDL_Ext::drawBorder(to,sel->pos.x-2,sel->pos.y-2,sel->pos.w+4,sel->pos.h+4,int3(247,223,123));
  3242. }
  3243. }
  3244. void CTavernWindow::HeroPortrait::clickLeft(tribool down, bool previousState)
  3245. {
  3246. if(previousState && !down && h)
  3247. *_sel = _id;
  3248. }
  3249. void CTavernWindow::HeroPortrait::clickRight(tribool down, bool previousState)
  3250. {
  3251. if(down && h)
  3252. {
  3253. GH.pushInt(new CRClickPopupInt(new CHeroWindow(h), true));
  3254. }
  3255. }
  3256. CTavernWindow::HeroPortrait::HeroPortrait(int &sel, int id, int x, int y, const CGHeroInstance *H)
  3257. : h(H), _sel(&sel), _id(id)
  3258. {
  3259. addUsedEvents(LCLICK | RCLICK | HOVER);
  3260. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3261. h = H;
  3262. pos.x += x;
  3263. pos.y += y;
  3264. pos.w = 58;
  3265. pos.h = 64;
  3266. if(H)
  3267. {
  3268. hoverName = CGI->generaltexth->tavernInfo[4];
  3269. boost::algorithm::replace_first(hoverName,"%s",H->name);
  3270. int artifs = h->artifactsWorn.size() + h->artifactsInBackpack.size();
  3271. for(int i=13; i<=17; i++) //war machines and spellbook don't count
  3272. if(vstd::contains(h->artifactsWorn, ArtifactPosition(i)))
  3273. artifs--;
  3274. description = CGI->generaltexth->allTexts[215];
  3275. boost::algorithm::replace_first(description, "%s", h->name);
  3276. boost::algorithm::replace_first(description, "%d", boost::lexical_cast<std::string>(h->level));
  3277. boost::algorithm::replace_first(description, "%s", h->type->heroClass->name);
  3278. boost::algorithm::replace_first(description, "%d", boost::lexical_cast<std::string>(artifs));
  3279. new CAnimImage("portraitsLarge", h->portrait);
  3280. }
  3281. }
  3282. void CTavernWindow::HeroPortrait::hover( bool on )
  3283. {
  3284. //Hoverable::hover(on);
  3285. if(on)
  3286. GH.statusbar->setText(hoverName);
  3287. else
  3288. GH.statusbar->clear();
  3289. }
  3290. void CInGameConsole::show(SDL_Surface * to)
  3291. {
  3292. int number = 0;
  3293. std::vector<std::list< std::pair< std::string, int > >::iterator> toDel;
  3294. boost::unique_lock<boost::mutex> lock(texts_mx);
  3295. for(auto it = texts.begin(); it != texts.end(); ++it, ++number)
  3296. {
  3297. Point leftBottomCorner(0, screen->h);
  3298. if(LOCPLINT->battleInt)
  3299. {
  3300. leftBottomCorner = LOCPLINT->battleInt->pos.bottomLeft();
  3301. }
  3302. graphics->fonts[FONT_MEDIUM]->renderTextLeft(to, it->first, Colors::GREEN,
  3303. Point(leftBottomCorner.x + 50, leftBottomCorner.y - texts.size() * 20 - 80 + number*20));
  3304. if(SDL_GetTicks() - it->second > defaultTimeout)
  3305. {
  3306. toDel.push_back(it);
  3307. }
  3308. }
  3309. for(auto & elem : toDel)
  3310. {
  3311. texts.erase(elem);
  3312. }
  3313. }
  3314. void CInGameConsole::print(const std::string &txt)
  3315. {
  3316. boost::unique_lock<boost::mutex> lock(texts_mx);
  3317. int lineLen = conf.go()->ac.outputLineLength;
  3318. if(txt.size() < lineLen)
  3319. {
  3320. texts.push_back(std::make_pair(txt, SDL_GetTicks()));
  3321. if(texts.size() > maxDisplayedTexts)
  3322. {
  3323. texts.pop_front();
  3324. }
  3325. }
  3326. else
  3327. {
  3328. assert(lineLen);
  3329. for(int g=0; g<txt.size() / lineLen + 1; ++g)
  3330. {
  3331. std::string part = txt.substr(g * lineLen, lineLen);
  3332. if(part.size() == 0)
  3333. break;
  3334. texts.push_back(std::make_pair(part, SDL_GetTicks()));
  3335. if(texts.size() > maxDisplayedTexts)
  3336. {
  3337. texts.pop_front();
  3338. }
  3339. }
  3340. }
  3341. }
  3342. void CInGameConsole::keyPressed (const SDL_KeyboardEvent & key)
  3343. {
  3344. if(key.type != SDL_KEYDOWN) return;
  3345. if(!captureAllKeys && key.keysym.sym != SDLK_TAB) return; //because user is not entering any text
  3346. switch(key.keysym.sym)
  3347. {
  3348. case SDLK_TAB:
  3349. case SDLK_ESCAPE:
  3350. {
  3351. if(captureAllKeys)
  3352. {
  3353. captureAllKeys = false;
  3354. endEnteringText(false);
  3355. }
  3356. else if(SDLK_TAB)
  3357. {
  3358. captureAllKeys = true;
  3359. startEnteringText();
  3360. }
  3361. break;
  3362. }
  3363. case SDLK_RETURN: //enter key
  3364. {
  3365. if(enteredText.size() > 0 && captureAllKeys)
  3366. {
  3367. captureAllKeys = false;
  3368. endEnteringText(true);
  3369. CCS->soundh->playSound("CHAT");
  3370. }
  3371. break;
  3372. }
  3373. case SDLK_BACKSPACE:
  3374. {
  3375. if(enteredText.size() > 1)
  3376. {
  3377. enteredText.resize(enteredText.size()-1);
  3378. enteredText[enteredText.size()-1] = '_';
  3379. refreshEnteredText();
  3380. }
  3381. break;
  3382. }
  3383. case SDLK_UP: //up arrow
  3384. {
  3385. if(previouslyEntered.size() == 0)
  3386. break;
  3387. if(prevEntDisp == -1)
  3388. {
  3389. prevEntDisp = previouslyEntered.size() - 1;
  3390. enteredText = previouslyEntered[prevEntDisp] + "_";
  3391. refreshEnteredText();
  3392. }
  3393. else if( prevEntDisp > 0)
  3394. {
  3395. --prevEntDisp;
  3396. enteredText = previouslyEntered[prevEntDisp] + "_";
  3397. refreshEnteredText();
  3398. }
  3399. break;
  3400. }
  3401. case SDLK_DOWN: //down arrow
  3402. {
  3403. if(prevEntDisp != -1 && prevEntDisp+1 < previouslyEntered.size())
  3404. {
  3405. ++prevEntDisp;
  3406. enteredText = previouslyEntered[prevEntDisp] + "_";
  3407. refreshEnteredText();
  3408. }
  3409. else if(prevEntDisp+1 == previouslyEntered.size()) //useful feature
  3410. {
  3411. prevEntDisp = -1;
  3412. enteredText = "_";
  3413. refreshEnteredText();
  3414. }
  3415. break;
  3416. }
  3417. default:
  3418. {
  3419. if(enteredText.size() > 0 && enteredText.size() < conf.go()->ac.inputLineLength)
  3420. {
  3421. if( key.keysym.unicode < 0x80 && key.keysym.unicode > 0 )
  3422. {
  3423. enteredText[enteredText.size()-1] = (char)key.keysym.unicode;
  3424. enteredText += "_";
  3425. refreshEnteredText();
  3426. }
  3427. }
  3428. break;
  3429. }
  3430. }
  3431. }
  3432. void CInGameConsole::startEnteringText()
  3433. {
  3434. enteredText = "_";
  3435. if(GH.topInt() == adventureInt)
  3436. {
  3437. GH.statusbar->alignment = TOPLEFT;
  3438. GH.statusbar->setText(enteredText);
  3439. //Prevent changes to the text from mouse interaction with the adventure map
  3440. GH.statusbar->lock(true);
  3441. }
  3442. else if(LOCPLINT->battleInt)
  3443. {
  3444. LOCPLINT->battleInt->console->ingcAlter = enteredText;
  3445. }
  3446. }
  3447. void CInGameConsole::endEnteringText(bool printEnteredText)
  3448. {
  3449. prevEntDisp = -1;
  3450. if(printEnteredText)
  3451. {
  3452. std::string txt = enteredText.substr(0, enteredText.size()-1);
  3453. LOCPLINT->cb->sendMessage(txt);
  3454. previouslyEntered.push_back(txt);
  3455. //print(txt);
  3456. }
  3457. enteredText = "";
  3458. if(GH.topInt() == adventureInt)
  3459. {
  3460. GH.statusbar->alignment = CENTER;
  3461. GH.statusbar->lock(false);
  3462. GH.statusbar->clear();
  3463. }
  3464. else if(LOCPLINT->battleInt)
  3465. {
  3466. LOCPLINT->battleInt->console->ingcAlter = "";
  3467. }
  3468. }
  3469. void CInGameConsole::refreshEnteredText()
  3470. {
  3471. if(GH.topInt() == adventureInt)
  3472. {
  3473. GH.statusbar->lock(false);
  3474. GH.statusbar->clear();
  3475. GH.statusbar->setText(enteredText);
  3476. GH.statusbar->lock(true);
  3477. }
  3478. else if(LOCPLINT->battleInt)
  3479. {
  3480. LOCPLINT->battleInt->console->ingcAlter = enteredText;
  3481. }
  3482. }
  3483. CInGameConsole::CInGameConsole() : prevEntDisp(-1), defaultTimeout(10000), maxDisplayedTexts(10)
  3484. {
  3485. addUsedEvents(KEYBOARD);
  3486. }
  3487. CGarrisonWindow::CGarrisonWindow( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits ):
  3488. CWindowObject(PLAYER_COLORED, "GARRISON")
  3489. {
  3490. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3491. garr = new CGarrisonInt(92, 127, 4, Point(0,96), background->bg, Point(93,127), up, down, removableUnits);
  3492. {
  3493. CAdventureMapButton *split = new CAdventureMapButton(CGI->generaltexth->tcommands[3],"",boost::bind(&CGarrisonInt::splitClick,garr),88,314,"IDV6432.DEF");
  3494. removeChild(split);
  3495. garr->addSplitBtn(split);
  3496. }
  3497. quit = new CAdventureMapButton(CGI->generaltexth->tcommands[8],"",boost::bind(&CGarrisonWindow::close,this),399,314,"IOK6432.DEF",SDLK_RETURN);
  3498. std::string titleText;
  3499. if (garr->armedObjs[1]->tempOwner == garr->armedObjs[0]->tempOwner)
  3500. titleText = CGI->generaltexth->allTexts[709];
  3501. else
  3502. {
  3503. titleText = CGI->generaltexth->allTexts[35];
  3504. boost::algorithm::replace_first(titleText, "%s", garr->armedObjs[0]->Slots().begin()->second->type->namePl);
  3505. }
  3506. new CLabel(275, 30, FONT_BIG, CENTER, Colors::YELLOW, titleText);
  3507. new CAnimImage("CREST58", garr->armedObjs[0]->getOwner().getNum(), 0, 28, 124);
  3508. new CAnimImage("PortraitsLarge", dynamic_cast<const CGHeroInstance*>(garr->armedObjs[1])->portrait, 0, 29, 222);
  3509. }
  3510. IShowActivatable::IShowActivatable()
  3511. {
  3512. type = 0;
  3513. }
  3514. CGarrisonHolder::CGarrisonHolder()
  3515. {
  3516. }
  3517. void CWindowWithGarrison::updateGarrisons()
  3518. {
  3519. garr->recreateSlots();
  3520. }
  3521. CArtPlace::CArtPlace(Point position, const CArtifactInstance * Art):
  3522. locked(false), picked(false), marked(false), ourArt(Art)
  3523. {
  3524. pos += position;
  3525. pos.w = pos.h = 44;
  3526. createImage();
  3527. }
  3528. void CArtPlace::createImage()
  3529. {
  3530. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3531. int graphic = 0;
  3532. if (ourArt)
  3533. graphic = ourArt->artType->iconIndex;
  3534. if (locked)
  3535. graphic = ArtifactID::ART_LOCK;
  3536. image = new CAnimImage("artifact", graphic);
  3537. if (!ourArt)
  3538. image->disable();
  3539. selection = new CAnimImage("artifact", ArtifactID::ART_SELECTION);
  3540. selection->disable();
  3541. }
  3542. void CArtPlace::lockSlot(bool on)
  3543. {
  3544. if (locked == on)
  3545. return;
  3546. locked = on;
  3547. if (on)
  3548. image->setFrame(ArtifactID::ART_LOCK);
  3549. else
  3550. image->setFrame(ourArt->artType->iconIndex);
  3551. }
  3552. void CArtPlace::pickSlot(bool on)
  3553. {
  3554. if (picked == on)
  3555. return;
  3556. picked = on;
  3557. if (on)
  3558. image->disable();
  3559. else
  3560. image->enable();
  3561. }
  3562. void CArtPlace::selectSlot(bool on)
  3563. {
  3564. if (marked == on)
  3565. return;
  3566. marked = on;
  3567. if (on)
  3568. selection->enable();
  3569. else
  3570. selection->disable();
  3571. }
  3572. void CArtPlace::clickLeft(tribool down, bool previousState)
  3573. {
  3574. //LRClickableAreaWTextComp::clickLeft(down);
  3575. bool inBackpack = slotID >= GameConstants::BACKPACK_START,
  3576. srcInBackpack = ourOwner->commonInfo->src.slotID >= GameConstants::BACKPACK_START,
  3577. srcInSameHero = ourOwner->commonInfo->src.AOH == ourOwner;
  3578. if(ourOwner->highlightModeCallback && ourArt)
  3579. {
  3580. if(down)
  3581. {
  3582. if(ourArt->artType->id < 7) //War Machine or Spellbook
  3583. {
  3584. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[21]); //This item can't be traded.
  3585. }
  3586. else
  3587. {
  3588. ourOwner->unmarkSlots(false);
  3589. selectSlot(true);
  3590. ourOwner->highlightModeCallback(this);
  3591. }
  3592. }
  3593. return;
  3594. }
  3595. // If clicked on spellbook, open it only if no artifact is held at the moment.
  3596. if(ourArt && !down && previousState && !ourOwner->commonInfo->src.AOH)
  3597. {
  3598. if(ourArt->artType->id == 0)
  3599. {
  3600. auto spellWindow = new CSpellWindow(genRect(595, 620, (screen->w - 620)/2, (screen->h - 595)/2), ourOwner->curHero, LOCPLINT, LOCPLINT->battleInt);
  3601. GH.pushInt(spellWindow);
  3602. }
  3603. }
  3604. if (!down && previousState)
  3605. {
  3606. if(ourArt && ourArt->artType->id == 0) //spellbook
  3607. return; //this is handled separately
  3608. if(!ourOwner->commonInfo->src.AOH) //nothing has been clicked
  3609. {
  3610. if(ourArt //to prevent selecting empty slots (bugfix to what GrayFace reported)
  3611. && ourOwner->curHero->tempOwner == LOCPLINT->playerID)//can't take art from another player
  3612. {
  3613. if(ourArt->artType->id == 3) //catapult cannot be highlighted
  3614. {
  3615. std::vector<CComponent *> catapult(1, new CComponent(CComponent::artifact, 3, 0));
  3616. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[312], catapult); //The Catapult must be equipped.
  3617. return;
  3618. }
  3619. select();
  3620. }
  3621. }
  3622. else if(ourArt == ourOwner->commonInfo->src.art) //restore previously picked artifact
  3623. {
  3624. deselect();
  3625. }
  3626. else //perform artifact transition
  3627. {
  3628. if(inBackpack) // Backpack destination.
  3629. {
  3630. if(srcInBackpack && slotID == ourOwner->commonInfo->src.slotID + 1) //next slot (our is not visible, so visually same as "old" place) to the art -> make nothing, return artifact to slot
  3631. {
  3632. deselect();
  3633. }
  3634. else
  3635. {
  3636. const CArtifact * const cur = ourOwner->commonInfo->src.art->artType;
  3637. switch(cur->id)
  3638. {
  3639. case ArtifactID::CATAPULT:
  3640. //should not happen, catapult cannot be selected
  3641. assert(cur->id != ArtifactID::CATAPULT);
  3642. break;
  3643. case ArtifactID::BALLISTA: case ArtifactID::AMMO_CART: case ArtifactID::FIRST_AID_TENT: //war machines cannot go to backpack
  3644. LOCPLINT->showInfoDialog(boost::str(boost::format(CGI->generaltexth->allTexts[153]) % cur->Name()));
  3645. break;
  3646. default:
  3647. setMeAsDest();
  3648. vstd::amin(ourOwner->commonInfo->dst.slotID, ArtifactPosition(
  3649. ourOwner->curHero->artifactsInBackpack.size() + GameConstants::BACKPACK_START));
  3650. if(srcInBackpack && srcInSameHero)
  3651. {
  3652. if(!ourArt //cannot move from backpack to AFTER backpack -> combined with vstd::amin above it will guarantee that dest is at most the last artifact
  3653. || ourOwner->commonInfo->src.slotID < ourOwner->commonInfo->dst.slotID) //rearranging arts in backpack after taking src artifact, the dest id will be shifted
  3654. vstd::advance(ourOwner->commonInfo->dst.slotID, -1);
  3655. }
  3656. if(srcInSameHero && ourOwner->commonInfo->dst.slotID == ourOwner->commonInfo->src.slotID) //we came to src == dst
  3657. deselect();
  3658. else
  3659. ourOwner->realizeCurrentTransaction();
  3660. break;
  3661. }
  3662. }
  3663. }
  3664. //check if swap is possible
  3665. else if (fitsHere(ourOwner->commonInfo->src.art) &&
  3666. (!ourArt || ourOwner->curHero->tempOwner == LOCPLINT->playerID))
  3667. {
  3668. setMeAsDest();
  3669. //
  3670. // // Special case when the dest artifact can't be fit into the src slot.
  3671. // //CGI->arth->unequipArtifact(ourOwner->curHero->artifWorn, slotID);
  3672. // const CArtifactsOfHero* srcAOH = ourOwner->commonInfo->src.AOH;
  3673. // ui16 srcSlotID = ourOwner->commonInfo->src.slotID;
  3674. // if (ourArt && srcSlotID < 19 && !ourArt->canBePutAt(ArtifactLocation(srcAOH->curHero, srcSlotID)))
  3675. // {
  3676. // // Put dest artifact into owner's backpack.
  3677. // ourOwner->commonInfo->src.AOH = ourOwner;
  3678. // ourOwner->commonInfo->src.slotID = ourOwner->curHero->artifacts.size() + 19;
  3679. // }
  3680. ourOwner->realizeCurrentTransaction();
  3681. }
  3682. }
  3683. }
  3684. }
  3685. void CArtPlace::clickRight(tribool down, bool previousState)
  3686. {
  3687. if(down && ourArt && !locked && text.size() && !picked) //if there is no description or it's a lock, do nothing ;]
  3688. {
  3689. if (slotID < GameConstants::BACKPACK_START)
  3690. {
  3691. if(ourOwner->allowedAssembling)
  3692. {
  3693. std::vector<const CArtifact *> assemblyPossibilities = ourArt->assemblyPossibilities(ourOwner->curHero);
  3694. // If the artifact can be assembled, display dialog.
  3695. for(const CArtifact *combination : assemblyPossibilities)
  3696. {
  3697. LOCPLINT->showArtifactAssemblyDialog(
  3698. ourArt->artType->id,
  3699. combination->id,
  3700. true,
  3701. boost::bind(&CCallback::assembleArtifacts, LOCPLINT->cb.get(), ourOwner->curHero, slotID, true, combination->id),
  3702. 0);
  3703. if(assemblyPossibilities.size() > 2)
  3704. {
  3705. logGlobal->warnStream() << "More than one possibility of assembling... taking only first";
  3706. break;
  3707. }
  3708. return;
  3709. }
  3710. // Otherwise if the artifact can be diasassembled, display dialog.
  3711. if(ourArt->canBeDisassembled())
  3712. {
  3713. LOCPLINT->showArtifactAssemblyDialog(
  3714. ourArt->artType->id,
  3715. 0,
  3716. false,
  3717. boost::bind(&CCallback::assembleArtifacts, LOCPLINT->cb.get(), ourOwner->curHero, slotID, false, ArtifactID()),
  3718. 0);
  3719. return;
  3720. }
  3721. }
  3722. }
  3723. // Lastly just show the artifact description.
  3724. LRClickableAreaWTextComp::clickRight(down, previousState);
  3725. }
  3726. }
  3727. /**
  3728. * Selects artifact slot so that the containing artifact looks like it's picked up.
  3729. */
  3730. void CArtPlace::select ()
  3731. {
  3732. if (locked)
  3733. return;
  3734. selectSlot(true);
  3735. pickSlot(true);
  3736. if(ourArt->canBeDisassembled() && slotID < GameConstants::BACKPACK_START) //worn combined artifact -> locks have to disappear
  3737. {
  3738. for(int i = 0; i < GameConstants::BACKPACK_START; i++)
  3739. {
  3740. CArtPlace *ap = ourOwner->getArtPlace(i);
  3741. ap->pickSlot(ourArt->isPart(ap->ourArt));
  3742. }
  3743. }
  3744. //int backpackCorrection = -(slotID - Arts::BACKPACK_START < ourOwner->backpackPos);
  3745. CCS->curh->dragAndDropCursor(new CAnimImage("artifact", ourArt->artType->iconIndex));
  3746. ourOwner->commonInfo->src.setTo(this, false);
  3747. ourOwner->markPossibleSlots(ourArt);
  3748. if(slotID >= GameConstants::BACKPACK_START)
  3749. ourOwner->scrollBackpack(0); //will update slots
  3750. ourOwner->updateParentWindow();
  3751. ourOwner->safeRedraw();
  3752. }
  3753. /**
  3754. * Deselects the artifact slot. FIXME: Not used. Maybe it should?
  3755. */
  3756. void CArtPlace::deselect ()
  3757. {
  3758. pickSlot(false);
  3759. if(ourArt && ourArt->canBeDisassembled()) //combined art returned to its slot -> restore locks
  3760. {
  3761. for(int i = 0; i < GameConstants::BACKPACK_START; i++)
  3762. ourOwner->getArtPlace(i)->pickSlot(false);
  3763. }
  3764. CCS->curh->dragAndDropCursor(nullptr);
  3765. ourOwner->unmarkSlots();
  3766. ourOwner->commonInfo->src.clear();
  3767. if(slotID >= GameConstants::BACKPACK_START)
  3768. ourOwner->scrollBackpack(0); //will update slots
  3769. ourOwner->updateParentWindow();
  3770. ourOwner->safeRedraw();
  3771. }
  3772. void CArtPlace::showAll(SDL_Surface * to)
  3773. {
  3774. if (ourArt && !picked && ourArt == ourOwner->curHero->getArt(slotID, false)) //last condition is needed for disassembling -> artifact may be gone, but we don't know yet TODO: real, nice solution
  3775. {
  3776. CIntObject::showAll(to);
  3777. }
  3778. if(marked && active)
  3779. {
  3780. // Draw vertical bars.
  3781. for (int i = 0; i < pos.h; ++i)
  3782. {
  3783. CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x, pos.y + i, 240, 220, 120);
  3784. CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x + pos.w - 1, pos.y + i, 240, 220, 120);
  3785. }
  3786. // Draw horizontal bars.
  3787. for (int i = 0; i < pos.w; ++i)
  3788. {
  3789. CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x + i, pos.y, 240, 220, 120);
  3790. CSDL_Ext::SDL_PutPixelWithoutRefresh(to, pos.x + i, pos.y + pos.h - 1, 240, 220, 120);
  3791. }
  3792. }
  3793. }
  3794. bool CArtPlace::fitsHere(const CArtifactInstance * art) const
  3795. {
  3796. // You can place 'no artifact' anywhere.
  3797. if(!art)
  3798. return true;
  3799. // Anything can but War Machines can be placed in backpack.
  3800. if (slotID >= GameConstants::BACKPACK_START)
  3801. return !CGI->arth->isBigArtifact(art->artType->id);
  3802. return art->canBePutAt(ArtifactLocation(ourOwner->curHero, slotID), true);
  3803. }
  3804. void CArtPlace::setMeAsDest(bool backpackAsVoid /*= true*/)
  3805. {
  3806. ourOwner->commonInfo->dst.setTo(this, backpackAsVoid);
  3807. }
  3808. void CArtPlace::setArtifact(const CArtifactInstance *art)
  3809. {
  3810. baseType = -1; //by default we don't store any component
  3811. ourArt = art;
  3812. if(!art)
  3813. {
  3814. image->disable();
  3815. text = std::string();
  3816. hoverText = CGI->generaltexth->allTexts[507];
  3817. }
  3818. else
  3819. {
  3820. image->enable();
  3821. image->setFrame(locked ? ArtifactID::ART_LOCK : art->artType->iconIndex);
  3822. std::string artDesc = ourArt->artType->Description();
  3823. if (vstd::contains (artDesc, '{'))
  3824. text = artDesc;
  3825. else
  3826. text = '{' + ourArt->artType->Name() + "}\n\n" + artDesc; //workaround for new artifacts with single name, turns it to H3-style
  3827. if(art->artType->id == 1) //spell scroll
  3828. {
  3829. // we expect scroll description to be like this: This scroll contains the [spell name] spell which is added into your spell book for as long as you carry the scroll.
  3830. // so we want to replace text in [...] with a spell name
  3831. // however other language versions don't have name placeholder at all, so we have to be careful
  3832. int spellID = art->getGivenSpellID();
  3833. size_t nameStart = text.find_first_of('[');
  3834. size_t nameEnd = text.find_first_of(']', nameStart);
  3835. if(spellID >= 0)
  3836. {
  3837. if(nameStart != std::string::npos && nameEnd != std::string::npos)
  3838. text = text.replace(nameStart, nameEnd - nameStart + 1, CGI->spellh->objects[spellID]->name);
  3839. //add spell component info (used to provide a pic in r-click popup)
  3840. baseType = CComponent::spell;
  3841. type = spellID;
  3842. bonusValue = 0;
  3843. }
  3844. }
  3845. else
  3846. {
  3847. baseType = CComponent::artifact;
  3848. type = art->artType->id;
  3849. bonusValue = 0;
  3850. }
  3851. if (art->artType->constituents) //display info about components of combined artifact
  3852. {
  3853. //TODO
  3854. }
  3855. else if (art->artType->constituentOf.size()) //display info about set
  3856. {
  3857. std::string artList;
  3858. auto combinedArt = art->artType->constituentOf[0];
  3859. text += "\n\n";
  3860. text += "{" + combinedArt->Name() + "}";
  3861. int wornArtifacts = 0;
  3862. for (auto a : *combinedArt->constituents) //TODO: can the artifact be a part of more than one set?
  3863. {
  3864. artList += "\n" + a->Name();
  3865. if (ourOwner->curHero->hasArt(a->id, true))
  3866. wornArtifacts++;
  3867. }
  3868. text += " (" + boost::str(boost::format("%d") % wornArtifacts) + " / " +
  3869. boost::str(boost::format("%d") % combinedArt->constituents->size()) + ")" + artList;
  3870. //TODO: fancy colors and fonts for this text
  3871. }
  3872. if (locked) // Locks should appear as empty.
  3873. hoverText = CGI->generaltexth->allTexts[507];
  3874. else
  3875. hoverText = boost::str(boost::format(CGI->generaltexth->heroscrn[1]) % ourArt->artType->Name());
  3876. }
  3877. }
  3878. void LRClickableAreaWTextComp::clickLeft(tribool down, bool previousState)
  3879. {
  3880. if((!down) && previousState)
  3881. {
  3882. std::vector<CComponent*> comp(1, createComponent());
  3883. LOCPLINT->showInfoDialog(text, comp);
  3884. }
  3885. }
  3886. LRClickableAreaWTextComp::LRClickableAreaWTextComp(const Rect &Pos, int BaseType)
  3887. : LRClickableAreaWText(Pos), baseType(BaseType), bonusValue(-1)
  3888. {
  3889. }
  3890. CComponent * LRClickableAreaWTextComp::createComponent() const
  3891. {
  3892. if(baseType >= 0)
  3893. return new CComponent(CComponent::Etype(baseType), type, bonusValue);
  3894. else
  3895. return nullptr;
  3896. }
  3897. void LRClickableAreaWTextComp::clickRight(tribool down, bool previousState)
  3898. {
  3899. if(down)
  3900. {
  3901. if(CComponent *comp = createComponent())
  3902. {
  3903. CRClickPopup::createAndPush(text, CInfoWindow::TCompsInfo(1, comp));
  3904. return;
  3905. }
  3906. }
  3907. LRClickableAreaWText::clickRight(down, previousState); //only if with-component variant not occurred
  3908. }
  3909. CHeroArea::CHeroArea(int x, int y, const CGHeroInstance * _hero):hero(_hero)
  3910. {
  3911. OBJ_CONSTRUCTION_CAPTURING_ALL;
  3912. addUsedEvents(LCLICK | RCLICK | HOVER);
  3913. pos.x += x; pos.w = 58;
  3914. pos.y += y; pos.h = 64;
  3915. if (hero)
  3916. new CAnimImage("PortraitsLarge", hero->portrait);
  3917. }
  3918. void CHeroArea::clickLeft(tribool down, bool previousState)
  3919. {
  3920. if((!down) && previousState && hero)
  3921. LOCPLINT->openHeroWindow(hero);
  3922. }
  3923. void CHeroArea::clickRight(tribool down, bool previousState)
  3924. {
  3925. if((!down) && previousState && hero)
  3926. LOCPLINT->openHeroWindow(hero);
  3927. }
  3928. void CHeroArea::hover(bool on)
  3929. {
  3930. if (on && hero)
  3931. GH.statusbar->setText(hero->getObjectName());
  3932. else
  3933. GH.statusbar->clear();
  3934. }
  3935. void LRClickableAreaOpenTown::clickLeft(tribool down, bool previousState)
  3936. {
  3937. if((!down) && previousState && town)
  3938. {
  3939. LOCPLINT->openTownWindow(town);
  3940. if ( type == 2 )
  3941. LOCPLINT->castleInt->builds->buildingClicked(BuildingID::VILLAGE_HALL);
  3942. else if ( type == 3 && town->fortLevel() )
  3943. LOCPLINT->castleInt->builds->buildingClicked(BuildingID::FORT);
  3944. }
  3945. }
  3946. void LRClickableAreaOpenTown::clickRight(tribool down, bool previousState)
  3947. {
  3948. if((!down) && previousState && town)
  3949. LOCPLINT->openTownWindow(town);//TODO: popup?
  3950. }
  3951. LRClickableAreaOpenTown::LRClickableAreaOpenTown()
  3952. : LRClickableAreaWTextComp(Rect(0,0,0,0), -1)
  3953. {
  3954. }
  3955. void CArtifactsOfHero::SCommonPart::reset()
  3956. {
  3957. src.clear();
  3958. dst.clear();
  3959. CCS->curh->dragAndDropCursor(nullptr);
  3960. }
  3961. void CArtifactsOfHero::setHero(const CGHeroInstance * hero)
  3962. {
  3963. // // An update is made, rather than initialization.
  3964. // if (curHero && curHero->id == hero->id)
  3965. // {
  3966. // if(curHero != hero)
  3967. // {
  3968. // //delete curHero;
  3969. // curHero = hero; //was: creating a copy
  3970. // }
  3971. //
  3972. // // Compensate backpack pos if an artifact was insertad before it.
  3973. // if (commonInfo->dst.slotID >= 19 && commonInfo->destAOH == this
  3974. // && commonInfo->dst.slotID - 19 < backpackPos)
  3975. // {
  3976. // backpackPos++;
  3977. // }
  3978. //
  3979. // if (updateState && commonInfo->srcAOH == this)
  3980. // {
  3981. // // A swap was made, make the replaced artifact the current selected.
  3982. // if (commonInfo->dst.slotID < 19 && commonInfo->destArtifact)
  3983. // {
  3984. // // // Temporarily remove artifact from hero.
  3985. // // if (commonInfo->srcSlotID < 19)
  3986. // // CGI->arth->unequipArtifact(curHero->artifWorn, commonInfo->srcSlotID);
  3987. // // else
  3988. // // curHero->artifacts.erase(curHero->artifacts.begin() + (commonInfo->srcSlotID - 19));
  3989. //
  3990. // updateParentWindow(); //TODO: evil! but does the thing
  3991. //
  3992. // // Source <- Dest
  3993. // commonInfo->srcArtifact = commonInfo->destArtifact;
  3994. //
  3995. // // Reset destination parameters.
  3996. // commonInfo->dst.clear();
  3997. //
  3998. // CCS->curh->dragAndDropCursor(graphics->artDefs->ourImages[commonInfo->srcArtifact->id].bitmap);
  3999. // markPossibleSlots(commonInfo->srcArtifact);
  4000. // }
  4001. // else if (commonInfo->destAOH != nullptr)
  4002. // {
  4003. // // Reset all parameters.
  4004. // commonInfo->reset();
  4005. // unmarkSlots();
  4006. // }
  4007. // }
  4008. // }
  4009. // else
  4010. // {
  4011. // commonInfo->reset();
  4012. // }
  4013. //
  4014. // if(hero != curHero)
  4015. // {
  4016. // // delete curHero;
  4017. // // curHero = new CGHeroInstance(*hero);
  4018. // curHero = hero; //was: creating a copy
  4019. // }
  4020. curHero = hero;
  4021. if (curHero->artifactsInBackpack.size() > 0)
  4022. backpackPos %= curHero->artifactsInBackpack.size();
  4023. else
  4024. backpackPos = 0;
  4025. // Fill the slots for worn artifacts and backpack.
  4026. for (int g = 0; g < artWorn.size() ; g++)
  4027. setSlotData(artWorn[g], ArtifactPosition(g));
  4028. scrollBackpack(0);
  4029. }
  4030. void CArtifactsOfHero::dispose()
  4031. {
  4032. //vstd::clear_pointer(curHero);
  4033. //unmarkSlots(false);
  4034. CCS->curh->dragAndDropCursor(nullptr);
  4035. }
  4036. void CArtifactsOfHero::scrollBackpack(int dir)
  4037. {
  4038. int artsInBackpack = curHero->artifactsInBackpack.size();
  4039. backpackPos += dir;
  4040. if(backpackPos < 0)// No guarantee of modulus behavior with negative operands -> we keep it positive
  4041. backpackPos += artsInBackpack;
  4042. if(artsInBackpack)
  4043. backpackPos %= artsInBackpack;
  4044. std::multiset<const CArtifactInstance *> toOmit = artifactsOnAltar;
  4045. if(commonInfo->src.art) //if we picked an art from backapck, its slot has to be omitted
  4046. toOmit.insert(commonInfo->src.art);
  4047. int omitedSoFar = 0;
  4048. //set new data
  4049. size_t s = 0;
  4050. for( ; s < artsInBackpack; ++s)
  4051. {
  4052. if (s < artsInBackpack)
  4053. {
  4054. auto slotID = ArtifactPosition(GameConstants::BACKPACK_START + (s + backpackPos)%artsInBackpack);
  4055. const CArtifactInstance *art = curHero->getArt(slotID);
  4056. assert(art);
  4057. if(!vstd::contains(toOmit, art))
  4058. {
  4059. if(s - omitedSoFar < backpack.size())
  4060. setSlotData(backpack[s-omitedSoFar], slotID);
  4061. }
  4062. else
  4063. {
  4064. toOmit -= art;
  4065. omitedSoFar++;
  4066. continue;
  4067. }
  4068. }
  4069. }
  4070. for( ; s - omitedSoFar < backpack.size(); s++)
  4071. eraseSlotData(backpack[s-omitedSoFar], ArtifactPosition(GameConstants::BACKPACK_START + s));
  4072. //in artifact merchant selling artifacts we may have highlight on one of backpack artifacts -> market needs update, cause artifact under highlight changed
  4073. if(highlightModeCallback)
  4074. {
  4075. for(auto & elem : backpack)
  4076. {
  4077. if(elem->marked)
  4078. {
  4079. highlightModeCallback(elem);
  4080. break;
  4081. }
  4082. }
  4083. }
  4084. //blocking scrolling if there is not enough artifacts to scroll
  4085. bool scrollingPossible = artsInBackpack - omitedSoFar > backpack.size();
  4086. leftArtRoll->block(!scrollingPossible);
  4087. rightArtRoll->block(!scrollingPossible);
  4088. safeRedraw();
  4089. }
  4090. /**
  4091. * Marks possible slots where a given artifact can be placed, except backpack.
  4092. *
  4093. * @param art Artifact checked against.
  4094. */
  4095. void CArtifactsOfHero::markPossibleSlots(const CArtifactInstance* art)
  4096. {
  4097. for(CArtifactsOfHero *aoh : commonInfo->participants)
  4098. for(CArtPlace *place : aoh->artWorn)
  4099. place->selectSlot(art->canBePutAt(ArtifactLocation(aoh->curHero, place->slotID), true));
  4100. safeRedraw();
  4101. }
  4102. /**
  4103. * Unamarks all slots.
  4104. */
  4105. void CArtifactsOfHero::unmarkSlots(bool withRedraw /*= true*/)
  4106. {
  4107. if(commonInfo)
  4108. for(CArtifactsOfHero *aoh : commonInfo->participants)
  4109. aoh->unmarkLocalSlots(false);
  4110. else
  4111. unmarkLocalSlots(false);\
  4112. if(withRedraw)
  4113. safeRedraw();
  4114. }
  4115. void CArtifactsOfHero::unmarkLocalSlots(bool withRedraw /*= true*/)
  4116. {
  4117. for(CArtPlace *place : artWorn)
  4118. place->selectSlot(false);
  4119. for(CArtPlace *place : backpack)
  4120. place->selectSlot(false);
  4121. if(withRedraw)
  4122. safeRedraw();
  4123. }
  4124. /**
  4125. * Assigns an artifacts to an artifact place depending on it's new slot ID.
  4126. */
  4127. void CArtifactsOfHero::setSlotData(CArtPlace* artPlace, ArtifactPosition slotID)
  4128. {
  4129. if(!artPlace && slotID >= GameConstants::BACKPACK_START) //spurious call from artifactMoved in attempt to update hidden backpack slot
  4130. {
  4131. return;
  4132. }
  4133. artPlace->pickSlot(false);
  4134. artPlace->slotID = slotID;
  4135. if(const ArtSlotInfo *asi = curHero->getSlot(slotID))
  4136. {
  4137. artPlace->setArtifact(asi->artifact);
  4138. artPlace->lockSlot(asi->locked);
  4139. }
  4140. else
  4141. artPlace->setArtifact(nullptr);
  4142. }
  4143. /**
  4144. * Makes given artifact slot appear as empty with a certain slot ID.
  4145. */
  4146. void CArtifactsOfHero::eraseSlotData (CArtPlace* artPlace, ArtifactPosition slotID)
  4147. {
  4148. artPlace->pickSlot(false);
  4149. artPlace->slotID = slotID;
  4150. artPlace->setArtifact(nullptr);
  4151. }
  4152. CArtifactsOfHero::CArtifactsOfHero(std::vector<CArtPlace *> ArtWorn, std::vector<CArtPlace *> Backpack,
  4153. CAdventureMapButton *leftScroll, CAdventureMapButton *rightScroll, bool createCommonPart):
  4154. curHero(nullptr),
  4155. artWorn(ArtWorn), backpack(Backpack),
  4156. backpackPos(0), commonInfo(nullptr), updateState(false),
  4157. leftArtRoll(leftScroll), rightArtRoll(rightScroll),
  4158. allowedAssembling(true), highlightModeCallback(nullptr)
  4159. {
  4160. if(createCommonPart)
  4161. {
  4162. commonInfo = new CArtifactsOfHero::SCommonPart;
  4163. commonInfo->participants.insert(this);
  4164. }
  4165. // Init slots for worn artifacts.
  4166. for (size_t g = 0; g < artWorn.size() ; g++)
  4167. {
  4168. artWorn[g]->ourOwner = this;
  4169. eraseSlotData(artWorn[g], ArtifactPosition(g));
  4170. }
  4171. // Init slots for the backpack.
  4172. for(size_t s=0; s<backpack.size(); ++s)
  4173. {
  4174. backpack[s]->ourOwner = this;
  4175. eraseSlotData(backpack[s], ArtifactPosition(GameConstants::BACKPACK_START + s));
  4176. }
  4177. leftArtRoll->callback += boost::bind(&CArtifactsOfHero::scrollBackpack,this,-1);
  4178. rightArtRoll->callback += boost::bind(&CArtifactsOfHero::scrollBackpack,this,+1);
  4179. }
  4180. CArtifactsOfHero::CArtifactsOfHero(const Point& position, bool createCommonPart /*= false*/)
  4181. : curHero(nullptr), backpackPos(0), commonInfo(nullptr), updateState(false), allowedAssembling(true), highlightModeCallback(nullptr)
  4182. {
  4183. if(createCommonPart)
  4184. {
  4185. commonInfo = new CArtifactsOfHero::SCommonPart;
  4186. commonInfo->participants.insert(this);
  4187. }
  4188. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4189. pos += position;
  4190. artWorn.resize(19);
  4191. std::vector<Point> slotPos;
  4192. slotPos += Point(509,30), Point(567,240), Point(509,80),
  4193. Point(383,68), Point(564,183), Point(509,130),
  4194. Point(431,68), Point(610,183), Point(515,295),
  4195. Point(383,143), Point(399,194), Point(415,245),
  4196. Point(431,296), Point(564,30), Point(610,30),
  4197. Point(610,76), Point(610,122), Point(610,310),
  4198. Point(381,296);
  4199. // Create slots for worn artifacts.
  4200. for (size_t g = 0; g < GameConstants::BACKPACK_START ; g++)
  4201. {
  4202. artWorn[g] = new CArtPlace(slotPos[g]);
  4203. artWorn[g]->ourOwner = this;
  4204. eraseSlotData(artWorn[g], ArtifactPosition(g));
  4205. }
  4206. // Create slots for the backpack.
  4207. for(size_t s=0; s<5; ++s)
  4208. {
  4209. auto add = new CArtPlace(Point(403 + 46 * s, 365));
  4210. add->ourOwner = this;
  4211. eraseSlotData(add, ArtifactPosition(GameConstants::BACKPACK_START + s));
  4212. backpack.push_back(add);
  4213. }
  4214. leftArtRoll = new CAdventureMapButton(std::string(), std::string(), boost::bind(&CArtifactsOfHero::scrollBackpack,this,-1), 379, 364, "hsbtns3.def", SDLK_LEFT);
  4215. rightArtRoll = new CAdventureMapButton(std::string(), std::string(), boost::bind(&CArtifactsOfHero::scrollBackpack,this,+1), 632, 364, "hsbtns5.def", SDLK_RIGHT);
  4216. }
  4217. CArtifactsOfHero::~CArtifactsOfHero()
  4218. {
  4219. dispose();
  4220. }
  4221. void CArtifactsOfHero::updateParentWindow()
  4222. {
  4223. if (CHeroWindow* chw = dynamic_cast<CHeroWindow*>(GH.topInt()))
  4224. {
  4225. if(updateState)
  4226. chw->curHero = curHero;
  4227. else
  4228. chw->update(curHero, true);
  4229. }
  4230. else if(CExchangeWindow* cew = dynamic_cast<CExchangeWindow*>(GH.topInt()))
  4231. {
  4232. //use our copy of hero to draw window
  4233. if(cew->heroInst[0]->id == curHero->id)
  4234. cew->heroInst[0] = curHero;
  4235. else
  4236. cew->heroInst[1] = curHero;
  4237. if(!updateState)
  4238. {
  4239. cew->deactivate();
  4240. // for(int g=0; g<ARRAY_COUNT(cew->heroInst); ++g)
  4241. // {
  4242. // if(cew->heroInst[g] == curHero)
  4243. // {
  4244. // cew->artifs[g]->setHero(curHero);
  4245. // }
  4246. // }
  4247. cew->prepareBackground();
  4248. cew->redraw();
  4249. cew->activate();
  4250. }
  4251. }
  4252. }
  4253. void CArtifactsOfHero::safeRedraw()
  4254. {
  4255. if (active)
  4256. {
  4257. if(parent)
  4258. parent->redraw();
  4259. else
  4260. redraw();
  4261. }
  4262. }
  4263. void CArtifactsOfHero::realizeCurrentTransaction()
  4264. {
  4265. assert(commonInfo->src.AOH);
  4266. assert(commonInfo->dst.AOH);
  4267. LOCPLINT->cb->swapArtifacts(ArtifactLocation(commonInfo->src.AOH->curHero, commonInfo->src.slotID),
  4268. ArtifactLocation(commonInfo->dst.AOH->curHero, commonInfo->dst.slotID));
  4269. }
  4270. void CArtifactsOfHero::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  4271. {
  4272. bool isCurHeroSrc = src.isHolder(curHero),
  4273. isCurHeroDst = dst.isHolder(curHero);
  4274. if(isCurHeroSrc && src.slot >= GameConstants::BACKPACK_START)
  4275. updateSlot(src.slot);
  4276. if(isCurHeroDst && dst.slot >= GameConstants::BACKPACK_START)
  4277. updateSlot(dst.slot);
  4278. if(isCurHeroSrc || isCurHeroDst) //we need to update all slots, artifact might be combined and affect more slots
  4279. updateWornSlots(false);
  4280. if (!src.isHolder(curHero) && !isCurHeroDst)
  4281. return;
  4282. if(commonInfo->src == src) //artifact was taken from us
  4283. {
  4284. assert(commonInfo->dst == dst //expected movement from slot ot slot
  4285. || dst.slot == dst.getHolderArtSet()->artifactsInBackpack.size() + GameConstants::BACKPACK_START //artifact moved back to backpack (eg. to make place for art we are moving)
  4286. || dst.getHolderArtSet()->bearerType() != ArtBearer::HERO);
  4287. commonInfo->reset();
  4288. unmarkSlots();
  4289. }
  4290. else if(commonInfo->dst == src) //the dest artifact was moved -> we are picking it
  4291. {
  4292. assert(dst.slot >= GameConstants::BACKPACK_START);
  4293. commonInfo->reset();
  4294. CArtPlace *ap = nullptr;
  4295. for(CArtifactsOfHero *aoh : commonInfo->participants)
  4296. {
  4297. if(dst.isHolder(aoh->curHero))
  4298. {
  4299. commonInfo->src.AOH = aoh;
  4300. if((ap = aoh->getArtPlace(dst.slot)))
  4301. break;
  4302. }
  4303. }
  4304. if(ap)
  4305. {
  4306. ap->select();
  4307. }
  4308. else
  4309. {
  4310. commonInfo->src.art = dst.getArt();
  4311. commonInfo->src.slotID = dst.slot;
  4312. assert(commonInfo->src.AOH);
  4313. CCS->curh->dragAndDropCursor(new CAnimImage("artifact", dst.getArt()->artType->iconIndex));
  4314. markPossibleSlots(dst.getArt());
  4315. }
  4316. }
  4317. else if(src.slot >= GameConstants::BACKPACK_START &&
  4318. src.slot < commonInfo->src.slotID &&
  4319. src.isHolder(commonInfo->src.AOH->curHero)) //artifact taken from before currently picked one
  4320. {
  4321. //int fixedSlot = src.hero->getArtPos(commonInfo->src.art);
  4322. vstd::advance(commonInfo->src.slotID, -1);
  4323. assert(commonInfo->src.valid());
  4324. }
  4325. else
  4326. {
  4327. //when moving one artifact onto another it leads to two art movements: dst->backapck; src->dst
  4328. // however after first movement we pick the art from backpack and the second movement coming when
  4329. // we have a different artifact may look surprising... but it's valid.
  4330. }
  4331. updateParentWindow();
  4332. int shift = 0;
  4333. // if(dst.slot >= Arts::BACKPACK_START && dst.slot - Arts::BACKPACK_START < backpackPos)
  4334. // shift++;
  4335. //
  4336. if(src.slot < GameConstants::BACKPACK_START && dst.slot - GameConstants::BACKPACK_START < backpackPos)
  4337. shift++;
  4338. if(dst.slot < GameConstants::BACKPACK_START && src.slot - GameConstants::BACKPACK_START < backpackPos)
  4339. shift--;
  4340. if( (isCurHeroSrc && src.slot >= GameConstants::BACKPACK_START)
  4341. || (isCurHeroDst && dst.slot >= GameConstants::BACKPACK_START) )
  4342. scrollBackpack(shift); //update backpack slots
  4343. }
  4344. void CArtifactsOfHero::artifactRemoved(const ArtifactLocation &al)
  4345. {
  4346. if(al.isHolder(curHero))
  4347. {
  4348. if(al.slot < GameConstants::BACKPACK_START)
  4349. updateWornSlots(0);
  4350. else
  4351. scrollBackpack(0); //update backpack slots
  4352. }
  4353. }
  4354. CArtPlace * CArtifactsOfHero::getArtPlace(int slot)
  4355. {
  4356. if(slot < GameConstants::BACKPACK_START)
  4357. {
  4358. return artWorn[slot];
  4359. }
  4360. else
  4361. {
  4362. for(CArtPlace *ap : backpack)
  4363. if(ap->slotID == slot)
  4364. return ap;
  4365. }
  4366. return nullptr;
  4367. }
  4368. void CArtifactsOfHero::artifactAssembled(const ArtifactLocation &al)
  4369. {
  4370. if(al.isHolder(curHero))
  4371. updateWornSlots();
  4372. }
  4373. void CArtifactsOfHero::artifactDisassembled(const ArtifactLocation &al)
  4374. {
  4375. if(al.isHolder(curHero))
  4376. updateWornSlots();
  4377. }
  4378. void CArtifactsOfHero::updateWornSlots(bool redrawParent /*= true*/)
  4379. {
  4380. for(int i = 0; i < artWorn.size(); i++)
  4381. updateSlot(ArtifactPosition(i));
  4382. if(redrawParent)
  4383. updateParentWindow();
  4384. }
  4385. const CGHeroInstance * CArtifactsOfHero::getHero() const
  4386. {
  4387. return curHero;
  4388. }
  4389. void CArtifactsOfHero::updateSlot(ArtifactPosition slotID)
  4390. {
  4391. setSlotData(getArtPlace(slotID), slotID);
  4392. }
  4393. void CExchangeWindow::questlog(int whichHero)
  4394. {
  4395. CCS->curh->dragAndDropCursor(nullptr);
  4396. }
  4397. void CExchangeWindow::prepareBackground()
  4398. {
  4399. //printing heroes' names and levels
  4400. auto genTitle = [](const CGHeroInstance *h)
  4401. {
  4402. return boost::str(boost::format(CGI->generaltexth->allTexts[138])
  4403. % h->name % h->level % h->type->heroClass->name);
  4404. };
  4405. new CLabel(147, 25, FONT_SMALL, CENTER, Colors::WHITE, genTitle(heroInst[0]));
  4406. new CLabel(653, 25, FONT_SMALL, CENTER, Colors::WHITE, genTitle(heroInst[1]));
  4407. //printing primary skills
  4408. for(int g=0; g<4; ++g)
  4409. new CAnimImage("PSKIL32", g, 0, 385, 19 + 36*g);
  4410. //heroes related thing
  4411. for(int b=0; b<ARRAY_COUNT(heroInst); b++)
  4412. {
  4413. CHeroWithMaybePickedArtifact heroWArt = CHeroWithMaybePickedArtifact(this, heroInst[b]);
  4414. //printing primary skills' amounts
  4415. for(int m=0; m<GameConstants::PRIMARY_SKILLS; ++m)
  4416. new CLabel(352 + 93 * b, 35 + 36 * m, FONT_SMALL, CENTER, Colors::WHITE,
  4417. boost::lexical_cast<std::string>(heroWArt.getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(m))));
  4418. //printing secondary skills
  4419. for(int m=0; m<heroInst[b]->secSkills.size(); ++m)
  4420. {
  4421. int id = heroInst[b]->secSkills[m].first;
  4422. int level = heroInst[b]->secSkills[m].second;
  4423. new CAnimImage("SECSK32", id*3 + level + 2 , 0, 32 + 36 * m + 454 * b, 88);
  4424. }
  4425. //hero's specialty
  4426. new CAnimImage("UN32", heroInst[b]->type->imageIndex, 0, 67 + 490*b, 45);
  4427. //experience
  4428. new CAnimImage("PSKIL32", 4, 0, 103 + 490*b, 45);
  4429. new CLabel(119 + 490*b, 71, FONT_SMALL, CENTER, Colors::WHITE, makeNumberShort(heroInst[b]->exp));
  4430. //mana points
  4431. new CAnimImage("PSKIL32", 5, 0, 139 + 490*b, 45);
  4432. new CLabel(155 + 490*b, 71, FONT_SMALL, CENTER, Colors::WHITE, makeNumberShort(heroInst[b]->mana));
  4433. }
  4434. //printing portraits
  4435. new CAnimImage("PortraitsLarge", heroInst[0]->portrait, 0, 257, 13);
  4436. new CAnimImage("PortraitsLarge", heroInst[1]->portrait, 0, 485, 13);
  4437. }
  4438. CExchangeWindow::CExchangeWindow(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID queryID):
  4439. CWindowObject(PLAYER_COLORED | BORDERED, "TRADE2")
  4440. {
  4441. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4442. heroInst[0] = LOCPLINT->cb->getHero(hero1);
  4443. heroInst[1] = LOCPLINT->cb->getHero(hero2);
  4444. prepareBackground();
  4445. artifs[0] = new CArtifactsOfHero(Point(-334, 150));
  4446. artifs[0]->commonInfo = new CArtifactsOfHero::SCommonPart;
  4447. artifs[0]->commonInfo->participants.insert(artifs[0]);
  4448. artifs[0]->setHero(heroInst[0]);
  4449. artifs[1] = new CArtifactsOfHero(Point(96, 150));
  4450. artifs[1]->commonInfo = artifs[0]->commonInfo;
  4451. artifs[1]->commonInfo->participants.insert(artifs[1]);
  4452. artifs[1]->setHero(heroInst[1]);
  4453. artSets.push_back(artifs[0]);
  4454. artSets.push_back(artifs[1]);
  4455. //primary skills
  4456. for(int g=0; g<4; ++g)
  4457. {
  4458. //primary skill's clickable areas
  4459. primSkillAreas.push_back(new LRClickableAreaWTextComp());
  4460. primSkillAreas[g]->pos = genRect(32, 140, pos.x + 329, pos.y + 19 + 36 * g);
  4461. primSkillAreas[g]->text = CGI->generaltexth->arraytxt[2+g];
  4462. primSkillAreas[g]->type = g;
  4463. primSkillAreas[g]->bonusValue = -1;
  4464. primSkillAreas[g]->baseType = 0;
  4465. primSkillAreas[g]->hoverText = CGI->generaltexth->heroscrn[1];
  4466. boost::replace_first(primSkillAreas[g]->hoverText, "%s", CGI->generaltexth->primarySkillNames[g]);
  4467. }
  4468. //heroes related thing
  4469. for(int b=0; b<ARRAY_COUNT(heroInst); b++)
  4470. {
  4471. //secondary skill's clickable areas
  4472. for(int g=0; g<heroInst[b]->secSkills.size(); ++g)
  4473. {
  4474. int skill = heroInst[b]->secSkills[g].first,
  4475. level = heroInst[b]->secSkills[g].second; // <1, 3>
  4476. secSkillAreas[b].push_back(new LRClickableAreaWTextComp());
  4477. secSkillAreas[b][g]->pos = genRect(32, 32, pos.x + 32 + g*36 + b*454 , pos.y + 88);
  4478. secSkillAreas[b][g]->baseType = 1;
  4479. secSkillAreas[b][g]->type = skill;
  4480. secSkillAreas[b][g]->bonusValue = level;
  4481. secSkillAreas[b][g]->text = CGI->generaltexth->skillInfoTexts[skill][level-1];
  4482. secSkillAreas[b][g]->hoverText = CGI->generaltexth->heroscrn[21];
  4483. boost::algorithm::replace_first(secSkillAreas[b][g]->hoverText, "%s", CGI->generaltexth->levels[level - 1]);
  4484. boost::algorithm::replace_first(secSkillAreas[b][g]->hoverText, "%s", CGI->generaltexth->skillName[skill]);
  4485. }
  4486. portrait[b] = new CHeroArea(257 + 228*b, 13, heroInst[b]);
  4487. specialty[b] = new LRClickableAreaWText();
  4488. specialty[b]->pos = genRect(32, 32, pos.x + 69 + 490*b, pos.y + 45);
  4489. specialty[b]->hoverText = CGI->generaltexth->heroscrn[27];
  4490. specialty[b]->text = heroInst[b]->type->specDescr;
  4491. experience[b] = new LRClickableAreaWText();
  4492. experience[b]->pos = genRect(32, 32, pos.x + 105 + 490*b, pos.y + 45);
  4493. experience[b]->hoverText = CGI->generaltexth->heroscrn[9];
  4494. experience[b]->text = CGI->generaltexth->allTexts[2].c_str();
  4495. boost::algorithm::replace_first(experience[b]->text, "%d", boost::lexical_cast<std::string>(heroInst[b]->level));
  4496. boost::algorithm::replace_first(experience[b]->text, "%d", boost::lexical_cast<std::string>(CGI->heroh->reqExp(heroInst[b]->level+1)));
  4497. boost::algorithm::replace_first(experience[b]->text, "%d", boost::lexical_cast<std::string>(heroInst[b]->exp));
  4498. spellPoints[b] = new LRClickableAreaWText();
  4499. spellPoints[b]->pos = genRect(32, 32, pos.x + 141 + 490*b, pos.y + 45);
  4500. spellPoints[b]->hoverText = CGI->generaltexth->heroscrn[22];
  4501. spellPoints[b]->text = CGI->generaltexth->allTexts[205];
  4502. boost::algorithm::replace_first(spellPoints[b]->text, "%s", heroInst[b]->name);
  4503. boost::algorithm::replace_first(spellPoints[b]->text, "%d", boost::lexical_cast<std::string>(heroInst[b]->mana));
  4504. boost::algorithm::replace_first(spellPoints[b]->text, "%d", boost::lexical_cast<std::string>(heroInst[b]->manaLimit()));
  4505. //setting morale
  4506. morale[b] = new MoraleLuckBox(true, genRect(32, 32, 176 + 490*b, 39), true);
  4507. morale[b]->set(heroInst[b]);
  4508. //setting luck
  4509. luck[b] = new MoraleLuckBox(false, genRect(32, 32, 212 + 490*b, 39), true);
  4510. luck[b]->set(heroInst[b]);
  4511. }
  4512. //buttons
  4513. quit = new CAdventureMapButton(CGI->generaltexth->zelp[600], boost::bind(&CExchangeWindow::close, this), 732, 567, "IOKAY.DEF", SDLK_RETURN);
  4514. if(queryID.getNum() > 0)
  4515. quit->callback += [=]{ LOCPLINT->cb->selectionMade(0, queryID); };
  4516. questlogButton[0] = new CAdventureMapButton(CGI->generaltexth->heroscrn[0], "", boost::bind(&CExchangeWindow::questlog,this, 0), 10, 44, "hsbtns4.def");
  4517. questlogButton[1] = new CAdventureMapButton(CGI->generaltexth->heroscrn[0], "", boost::bind(&CExchangeWindow::questlog,this, 1), 740, 44, "hsbtns4.def");
  4518. Rect barRect(5, 578, 725, 18);
  4519. ourBar = new CGStatusBar(new CPicture(*background, barRect, 5, 578, false));
  4520. //garrison interface
  4521. garr = new CGarrisonInt(69, 131, 4, Point(418,0), *background, Point(69,131), heroInst[0],heroInst[1], true, true);
  4522. garr->addSplitBtn(new CAdventureMapButton(CGI->generaltexth->tcommands[3], "", boost::bind(&CGarrisonInt::splitClick, garr), 10, 132, "TSBTNS.DEF"));
  4523. garr->addSplitBtn(new CAdventureMapButton(CGI->generaltexth->tcommands[3], "", boost::bind(&CGarrisonInt::splitClick, garr), 740, 132, "TSBTNS.DEF"));
  4524. }
  4525. CExchangeWindow::~CExchangeWindow() //d-tor
  4526. {
  4527. delete artifs[0]->commonInfo;
  4528. artifs[0]->commonInfo = nullptr;
  4529. artifs[1]->commonInfo = nullptr;
  4530. }
  4531. CShipyardWindow::CShipyardWindow(const std::vector<si32> &cost, int state, int boatType, const std::function<void()> &onBuy):
  4532. CWindowObject(PLAYER_COLORED, "TPSHIP")
  4533. {
  4534. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4535. bgWater = new CPicture("TPSHIPBK", 100, 69);
  4536. std::string boatFilenames[3] = {"AB01_", "AB02_", "AB03_"};
  4537. Point waterCenter = Point(bgWater->pos.x+bgWater->pos.w/2, bgWater->pos.y+bgWater->pos.h/2);
  4538. bgShip = new CAnimImage(boatFilenames[boatType], 0, 7, 120, 96, CShowableAnim::USE_RLE);
  4539. bgShip->center(waterCenter);
  4540. // Create resource icons and costs.
  4541. std::string goldValue = boost::lexical_cast<std::string>(cost[Res::GOLD]);
  4542. std::string woodValue = boost::lexical_cast<std::string>(cost[Res::WOOD]);
  4543. goldCost = new CLabel(118, 294, FONT_SMALL, CENTER, Colors::WHITE, goldValue);
  4544. woodCost = new CLabel(212, 294, FONT_SMALL, CENTER, Colors::WHITE, woodValue);
  4545. goldPic = new CAnimImage("RESOURCE", Res::GOLD, 0, 100, 244);
  4546. woodPic = new CAnimImage("RESOURCE", Res::WOOD, 0, 196, 244);
  4547. quit = new CAdventureMapButton(CGI->generaltexth->allTexts[599], "", boost::bind(&CShipyardWindow::close, this), 224, 312, "ICANCEL", SDLK_RETURN);
  4548. build = new CAdventureMapButton(CGI->generaltexth->allTexts[598], "", boost::bind(&CShipyardWindow::close, this), 42, 312, "IBUY30", SDLK_RETURN);
  4549. build->callback += onBuy;
  4550. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  4551. {
  4552. if(cost[i] > LOCPLINT->cb->getResourceAmount(i))
  4553. {
  4554. build->block(true);
  4555. break;
  4556. }
  4557. }
  4558. statusBar = new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  4559. title = new CLabel(164, 27, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[13]);
  4560. costLabel = new CLabel(164, 220, FONT_MEDIUM, CENTER, Colors::WHITE, CGI->generaltexth->jktexts[14]);
  4561. }
  4562. CPuzzleWindow::CPuzzleWindow(const int3 &GrailPos, double discoveredRatio):
  4563. CWindowObject(PLAYER_COLORED | BORDERED, "PUZZLE"),
  4564. grailPos(GrailPos),
  4565. currentAlpha(SDL_ALPHA_OPAQUE)
  4566. {
  4567. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4568. CCS->soundh->playSound(soundBase::OBELISK);
  4569. quitb = new CAdventureMapButton(CGI->generaltexth->allTexts[599], "", boost::bind(&CPuzzleWindow::close, this), 670, 538, "IOK6432.DEF", SDLK_RETURN);
  4570. quitb->assignedKeys.insert(SDLK_ESCAPE);
  4571. quitb->borderColor = Colors::METALLIC_GOLD;
  4572. quitb->borderEnabled = true;
  4573. new CPicture("PUZZLOGO", 607, 3);
  4574. new CLabel(700, 95, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[463]);
  4575. new CResDataBar("ARESBAR.bmp", 3, 575, 32, 2, 85, 85);
  4576. int faction = LOCPLINT->cb->getStartInfo()->playerInfos.find(LOCPLINT->playerID)->second.castle;
  4577. auto & puzzleMap = CGI->townh->factions[faction]->puzzleMap;
  4578. for(auto & elem : puzzleMap)
  4579. {
  4580. const SPuzzleInfo & info = elem;
  4581. auto piece = new CPicture(info.filename, info.x, info.y);
  4582. //piece that will slowly disappear
  4583. if(info.whenUncovered <= GameConstants::PUZZLE_MAP_PIECES * discoveredRatio)
  4584. {
  4585. piecesToRemove.push_back(piece);
  4586. piece->needRefresh = true;
  4587. piece->recActions = piece->recActions & ~SHOWALL;
  4588. }
  4589. }
  4590. }
  4591. void CPuzzleWindow::showAll(SDL_Surface * to)
  4592. {
  4593. int3 moveInt = int3(8, 9, 0);
  4594. Rect mapRect = genRect(544, 591, pos.x + 8, pos.y + 7);
  4595. CGI->mh->terrainRect
  4596. (grailPos - moveInt, adventureInt->anim,
  4597. &LOCPLINT->cb->getVisibilityMap(), true, adventureInt->heroAnim,
  4598. to, &mapRect, 0, 0, true, moveInt);
  4599. CWindowObject::showAll(to);
  4600. }
  4601. void CPuzzleWindow::show(SDL_Surface * to)
  4602. {
  4603. static int animSpeed = 2;
  4604. if (currentAlpha < animSpeed)
  4605. {
  4606. //animation done
  4607. for(auto & piece : piecesToRemove)
  4608. delete piece;
  4609. piecesToRemove.clear();
  4610. }
  4611. else
  4612. {
  4613. //update disappearing puzzles
  4614. for(auto & piece : piecesToRemove)
  4615. piece->setAlpha(currentAlpha);
  4616. currentAlpha -= animSpeed;
  4617. }
  4618. CWindowObject::show(to);
  4619. }
  4620. void CTransformerWindow::CItem::move()
  4621. {
  4622. if (left)
  4623. moveBy(Point(289, 0));
  4624. else
  4625. moveBy(Point(-289, 0));
  4626. left = !left;
  4627. }
  4628. void CTransformerWindow::CItem::clickLeft(tribool down, bool previousState)
  4629. {
  4630. if(previousState && (!down))
  4631. {
  4632. move();
  4633. parent->showAll(screen2);
  4634. }
  4635. }
  4636. void CTransformerWindow::CItem::update()
  4637. {
  4638. icon->setFrame(parent->army->getCreature(SlotID(id))->idNumber + 2);
  4639. }
  4640. CTransformerWindow::CItem::CItem(CTransformerWindow * parent, int size, int id):
  4641. id(id), size(size), parent(parent)
  4642. {
  4643. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4644. addUsedEvents(LCLICK);
  4645. left = true;
  4646. pos.w = 58;
  4647. pos.h = 64;
  4648. pos.x += 45 + (id%3)*83 + id/6*83;
  4649. pos.y += 109 + (id/3)*98;
  4650. icon = new CAnimImage("TWCRPORT", parent->army->getCreature(SlotID(id))->idNumber + 2);
  4651. new CLabel(28, 76,FONT_SMALL, CENTER, Colors::WHITE, boost::lexical_cast<std::string>(size));//stack size
  4652. }
  4653. void CTransformerWindow::makeDeal()
  4654. {
  4655. for (auto & elem : items)
  4656. if (!elem->left)
  4657. LOCPLINT->cb->trade(town, EMarketMode::CREATURE_UNDEAD, elem->id, 0, 0, hero);
  4658. }
  4659. void CTransformerWindow::addAll()
  4660. {
  4661. for (auto & elem : items)
  4662. if (elem->left)
  4663. elem->move();
  4664. showAll(screen2);
  4665. }
  4666. void CTransformerWindow::updateGarrisons()
  4667. {
  4668. for(auto & item : items)
  4669. {
  4670. item->update();
  4671. }
  4672. }
  4673. CTransformerWindow::CTransformerWindow(const CGHeroInstance * _hero, const CGTownInstance * _town):
  4674. CWindowObject(PLAYER_COLORED, "SKTRNBK"),
  4675. hero(_hero),
  4676. town(_town)
  4677. {
  4678. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4679. if (hero)
  4680. army = hero;
  4681. else
  4682. army = town;
  4683. for (int i=0; i<GameConstants::ARMY_SIZE; i++ )
  4684. if ( army->getCreature(SlotID(i)) )
  4685. items.push_back(new CItem(this, army->getStackCount(SlotID(i)), i));
  4686. all = new CAdventureMapButton(CGI->generaltexth->zelp[590],boost::bind(&CTransformerWindow::addAll,this), 146,416,"ALTARMY.DEF",SDLK_a);
  4687. convert= new CAdventureMapButton(CGI->generaltexth->zelp[591],boost::bind(&CTransformerWindow::makeDeal,this), 269,416,"ALTSACR.DEF",SDLK_RETURN);
  4688. cancel = new CAdventureMapButton(CGI->generaltexth->zelp[592],boost::bind(&CTransformerWindow::close, this),392,416,"ICANCEL.DEF",SDLK_ESCAPE);
  4689. bar = new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  4690. new CLabel(153, 29,FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[485]);//holding area
  4691. new CLabel(153+295, 29, FONT_SMALL, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[486]);//transformer
  4692. new CTextBox(CGI->generaltexth->allTexts[487], Rect(26, 56, 255, 40), 0, FONT_MEDIUM, CENTER, Colors::YELLOW);//move creatures to create skeletons
  4693. new CTextBox(CGI->generaltexth->allTexts[488], Rect(320, 56, 255, 40), 0, FONT_MEDIUM, CENTER, Colors::YELLOW);//creatures here will become skeletons
  4694. }
  4695. void CUniversityWindow::CItem::clickLeft(tribool down, bool previousState)
  4696. {
  4697. if(previousState && (!down))
  4698. {
  4699. if ( state() != 2 )
  4700. return;
  4701. auto win = new CUnivConfirmWindow(parent, ID, LOCPLINT->cb->getResourceAmount(Res::GOLD) >= 2000);
  4702. GH.pushInt(win);
  4703. }
  4704. }
  4705. void CUniversityWindow::CItem::clickRight(tribool down, bool previousState)
  4706. {
  4707. if(down)
  4708. {
  4709. CRClickPopup::createAndPush(CGI->generaltexth->skillInfoTexts[ID][0],
  4710. new CComponent(CComponent::secskill, ID, 1));
  4711. }
  4712. }
  4713. void CUniversityWindow::CItem::hover(bool on)
  4714. {
  4715. if (on)
  4716. GH.statusbar->setText(CGI->generaltexth->skillName[ID]);
  4717. else
  4718. GH.statusbar->clear();
  4719. }
  4720. int CUniversityWindow::CItem::state()
  4721. {
  4722. if (parent->hero->getSecSkillLevel(SecondarySkill(ID)))//hero know this skill
  4723. return 1;
  4724. if (!parent->hero->canLearnSkill())//can't learn more skills
  4725. return 0;
  4726. if (parent->hero->type->heroClass->secSkillProbability[ID]==0)//can't learn this skill (like necromancy for most of non-necros)
  4727. return 0;
  4728. return 2;
  4729. }
  4730. void CUniversityWindow::CItem::showAll(SDL_Surface * to)
  4731. {
  4732. CPicture * bar;
  4733. switch (state())
  4734. {
  4735. case 0: bar = parent->red;
  4736. break;
  4737. case 1: bar = parent->yellow;
  4738. break;
  4739. case 2: bar = parent->green;
  4740. break;
  4741. default:bar = nullptr;
  4742. break;
  4743. }
  4744. assert(bar);
  4745. blitAtLoc(bar->bg, -28, -22, to);
  4746. blitAtLoc(bar->bg, -28, 48, to);
  4747. printAtMiddleLoc (CGI->generaltexth->skillName[ID], 22, -13, FONT_SMALL, Colors::WHITE,to);//Name
  4748. printAtMiddleLoc (CGI->generaltexth->levels[0], 22, 57, FONT_SMALL, Colors::WHITE,to);//Level(always basic)
  4749. CAnimImage::showAll(to);
  4750. }
  4751. CUniversityWindow::CItem::CItem(CUniversityWindow * _parent, int _ID, int X, int Y):
  4752. CAnimImage ("SECSKILL", _ID*3+3, 0, X, Y),
  4753. ID(_ID),
  4754. parent(_parent)
  4755. {
  4756. addUsedEvents(LCLICK | RCLICK | HOVER);
  4757. }
  4758. CUniversityWindow::CUniversityWindow(const CGHeroInstance * _hero, const IMarket * _market):
  4759. CWindowObject(PLAYER_COLORED, "UNIVERS1"),
  4760. hero(_hero),
  4761. market(_market)
  4762. {
  4763. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4764. green = new CPicture("UNIVGREN.PCX");
  4765. yellow = new CPicture("UNIVGOLD.PCX");//bars
  4766. red = new CPicture("UNIVRED.PCX");
  4767. green->recActions =
  4768. yellow->recActions =
  4769. red->recActions = DISPOSE;
  4770. CIntObject * titlePic = nullptr;
  4771. if (market->o->ID == Obj::TOWN)
  4772. titlePic = new CAnimImage(CGI->townh->factions[ETownType::CONFLUX]->town->clientInfo.buildingsIcons, BuildingID::MAGIC_UNIVERSITY);
  4773. else
  4774. titlePic = new CPicture("UNIVBLDG");
  4775. titlePic->center(Point(232 + pos.x, 76 + pos.y));
  4776. //Clerk speech
  4777. new CTextBox(CGI->generaltexth->allTexts[603], Rect(24, 129, 413, 70), 0, FONT_SMALL, CENTER, Colors::WHITE);
  4778. //University
  4779. new CLabel(231, 26, FONT_MEDIUM, CENTER, Colors::YELLOW, CGI->generaltexth->allTexts[602]);
  4780. std::vector<int> list = market->availableItemsIds(EMarketMode::RESOURCE_SKILL);
  4781. assert(list.size() == 4);
  4782. for (int i=0; i<list.size(); i++)//prepare clickable items
  4783. items.push_back(new CItem(this, list[i], 54+i*104, 234));
  4784. cancel = new CAdventureMapButton(CGI->generaltexth->zelp[632],
  4785. boost::bind(&CUniversityWindow::close, this),200,313,"IOKAY.DEF",SDLK_RETURN);
  4786. bar = new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  4787. }
  4788. CUnivConfirmWindow::CUnivConfirmWindow(CUniversityWindow * PARENT, int SKILL, bool available ):
  4789. CWindowObject(PLAYER_COLORED, "UNIVERS2.PCX"),
  4790. parent(PARENT)
  4791. {
  4792. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4793. std::string text = CGI->generaltexth->allTexts[608];
  4794. boost::replace_first(text, "%s", CGI->generaltexth->levels[0]);
  4795. boost::replace_first(text, "%s", CGI->generaltexth->skillName[SKILL]);
  4796. boost::replace_first(text, "%d", "2000");
  4797. new CTextBox(text, Rect(24, 129, 413, 70), 0, FONT_SMALL, CENTER, Colors::WHITE);//Clerk speech
  4798. new CLabel(230, 37, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth-> skillName[SKILL]);//Skill name
  4799. new CAnimImage("SECSKILL", SKILL*3+3, 0, 211, 51);//skill
  4800. new CLabel(230, 107, FONT_SMALL, CENTER, Colors::WHITE, CGI->generaltexth->levels[1]);//Skill level
  4801. new CAnimImage("RESOURCE", Res::GOLD, 0, 210, 210);//gold
  4802. new CLabel(230, 267, FONT_SMALL, CENTER, Colors::WHITE, "2000");//Cost
  4803. std::string hoverText = CGI->generaltexth->allTexts[609];
  4804. boost::replace_first(hoverText, "%s", CGI->generaltexth->levels[0]+ " " + CGI->generaltexth->skillName[SKILL]);
  4805. text = CGI->generaltexth->zelp[633].second;
  4806. boost::replace_first(text, "%s", CGI->generaltexth->levels[0]);
  4807. boost::replace_first(text, "%s", CGI->generaltexth->skillName[SKILL]);
  4808. boost::replace_first(text, "%d", "2000");
  4809. confirm= new CAdventureMapButton(hoverText, text, boost::bind(&CUnivConfirmWindow::makeDeal, this, SKILL),
  4810. 148,299,"IBY6432.DEF",SDLK_RETURN);
  4811. confirm->block(!available);
  4812. cancel = new CAdventureMapButton(CGI->generaltexth->zelp[631],boost::bind(&CUnivConfirmWindow::close, this),
  4813. 252,299,"ICANCEL.DEF",SDLK_ESCAPE);
  4814. bar = new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  4815. }
  4816. void CUnivConfirmWindow::makeDeal(int skill)
  4817. {
  4818. LOCPLINT->cb->trade(parent->market->o, EMarketMode::RESOURCE_SKILL, 6, skill, 1, parent->hero);
  4819. close();
  4820. }
  4821. CHillFortWindow::CHillFortWindow(const CGHeroInstance *visitor, const CGObjectInstance *object):
  4822. CWindowObject(PLAYER_COLORED, "APHLFTBK"),
  4823. fort(object),
  4824. hero(visitor)
  4825. {
  4826. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4827. slotsCount=7;
  4828. resources = CDefHandler::giveDefEss("SMALRES.DEF");
  4829. new CLabel(325, 32, FONT_BIG, CENTER, Colors::YELLOW, fort->getObjectName());//Hill Fort
  4830. heroPic = new CHeroArea(30, 60, hero);
  4831. currState.resize(slotsCount+1);
  4832. costs.resize(slotsCount);
  4833. totalSumm.resize(GameConstants::RESOURCE_QUANTITY);
  4834. std::vector<std::string> files;
  4835. files += "APHLF1R.DEF", "APHLF1Y.DEF", "APHLF1G.DEF";
  4836. for (int i=0; i<slotsCount; i++)
  4837. {
  4838. currState[i] = getState(SlotID(i));
  4839. upgrade[i] = new CAdventureMapButton(getTextForSlot(SlotID(i)),"",boost::bind(&CHillFortWindow::makeDeal, this, SlotID(i)),
  4840. 107+i*76, 171, "", SDLK_1+i, &files);
  4841. upgrade[i]->block(currState[i] == -1);
  4842. }
  4843. files.clear();
  4844. files += "APHLF4R.DEF", "APHLF4Y.DEF", "APHLF4G.DEF";
  4845. currState[slotsCount] = getState(SlotID(slotsCount));
  4846. upgradeAll = new CAdventureMapButton(CGI->generaltexth->allTexts[432],"",boost::bind(&CHillFortWindow::makeDeal, this, SlotID(slotsCount)),
  4847. 30, 231, "", SDLK_0, &files);
  4848. quit = new CAdventureMapButton("","",boost::bind(&CHillFortWindow::close, this), 294, 275, "IOKAY.DEF", SDLK_RETURN);
  4849. bar = new CGStatusBar(new CPicture(*background, Rect(8, pos.h - 26, pos.w - 16, 19), 8, pos.h - 26));
  4850. garr = new CGarrisonInt(108, 60, 18, Point(),background->bg,Point(108,60),hero,nullptr);
  4851. updateGarrisons();
  4852. }
  4853. void CHillFortWindow::updateGarrisons()
  4854. {
  4855. for (int i=0; i<GameConstants::RESOURCE_QUANTITY; i++)
  4856. totalSumm[i]=0;
  4857. for (int i=0; i<slotsCount; i++)
  4858. {
  4859. costs[i].clear();
  4860. int newState = getState(SlotID(i));
  4861. if (newState != -1)
  4862. {
  4863. UpgradeInfo info;
  4864. LOCPLINT->cb->getUpgradeInfo(hero, SlotID(i), info);
  4865. if (info.newID.size())//we have upgrades here - update costs
  4866. {
  4867. costs[i] = info.cost[0] * hero->getStackCount(SlotID(i));
  4868. totalSumm += costs[i];
  4869. }
  4870. }
  4871. currState[i] = newState;
  4872. upgrade[i]->setIndex(newState);
  4873. upgrade[i]->block(currState[i] == -1);
  4874. upgrade[i]->hoverTexts[0] = getTextForSlot(SlotID(i));
  4875. }
  4876. int newState = getState(SlotID(slotsCount));
  4877. currState[slotsCount] = newState;
  4878. upgradeAll->setIndex(newState);
  4879. garr->recreateSlots();
  4880. }
  4881. void CHillFortWindow::makeDeal(SlotID slot)
  4882. {
  4883. assert(slot.getNum()>=0);
  4884. int offset = (slot.getNum() == slotsCount)?2:0;
  4885. switch (currState[slot.getNum()])
  4886. {
  4887. case 0:
  4888. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[314 + offset],
  4889. std::vector<CComponent*>(), soundBase::sound_todo);
  4890. break;
  4891. case 1:
  4892. LOCPLINT->showInfoDialog(CGI->generaltexth->allTexts[313 + offset],
  4893. std::vector<CComponent*>(), soundBase::sound_todo);
  4894. break;
  4895. case 2:
  4896. for (int i=0; i<slotsCount; i++)
  4897. if ( slot.getNum() ==i || ( slot.getNum() == slotsCount && currState[i] == 2 ) )//this is activated slot or "upgrade all"
  4898. {
  4899. UpgradeInfo info;
  4900. LOCPLINT->cb->getUpgradeInfo(hero, SlotID(i), info);
  4901. LOCPLINT->cb->upgradeCreature(hero, SlotID(i), info.newID[0]);
  4902. }
  4903. break;
  4904. }
  4905. }
  4906. void CHillFortWindow::showAll (SDL_Surface *to)
  4907. {
  4908. CWindowObject::showAll(to);
  4909. for ( int i=0; i<slotsCount; i++)
  4910. {
  4911. if ( currState[i] == 0 || currState[i] == 2 )
  4912. {
  4913. if ( costs[i].size() )//we have several elements
  4914. {
  4915. int curY = 128;//reverse iterator is used to display gold as first element
  4916. for(int j = costs[i].size()-1; j >= 0; j--)
  4917. {
  4918. int val = costs[i][j];
  4919. if(!val) continue;
  4920. blitAtLoc(resources->ourImages[j].bitmap, 104+76*i, curY, to);
  4921. printToLoc(boost::lexical_cast<std::string>(val), 168+76*i, curY+16, FONT_SMALL, Colors::WHITE, to);
  4922. curY += 20;
  4923. }
  4924. }
  4925. else//free upgrade - print gold image and "Free" text
  4926. {
  4927. blitAtLoc(resources->ourImages[6].bitmap, 104+76*i, 128, to);
  4928. printToLoc(CGI->generaltexth->allTexts[344], 168+76*i, 144, FONT_SMALL, Colors::WHITE, to);
  4929. }
  4930. }
  4931. }
  4932. for (int i=0; i<GameConstants::RESOURCE_QUANTITY; i++)
  4933. {
  4934. if (totalSumm[i])//this resource is used - display it
  4935. {
  4936. blitAtLoc(resources->ourImages[i].bitmap, 104+76*i, 237, to);
  4937. printToLoc(boost::lexical_cast<std::string>(totalSumm[i]), 166+76*i, 253, FONT_SMALL, Colors::WHITE, to);
  4938. }
  4939. }
  4940. }
  4941. std::string CHillFortWindow::getTextForSlot(SlotID slot)
  4942. {
  4943. if ( !hero->getCreature(slot) )//we don`t have creature here
  4944. return "";
  4945. std::string str = CGI->generaltexth->allTexts[318];
  4946. int amount = hero->getStackCount(slot);
  4947. if ( amount == 1 )
  4948. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->nameSing);
  4949. else
  4950. boost::algorithm::replace_first(str,"%s",hero->getCreature(slot)->namePl);
  4951. return str;
  4952. }
  4953. int CHillFortWindow::getState(SlotID slot)
  4954. {
  4955. TResources myRes = LOCPLINT->cb->getResourceAmount();
  4956. if ( slot.getNum() == slotsCount )//"Upgrade all" slot
  4957. {
  4958. bool allUpgraded = true;//All creatures are upgraded?
  4959. for (int i=0; i<slotsCount; i++)
  4960. allUpgraded &= currState[i] == 1 || currState[i] == -1;
  4961. if (allUpgraded)
  4962. return 1;
  4963. if(!totalSumm.canBeAfforded(myRes))
  4964. return 0;
  4965. return 2;
  4966. }
  4967. if (hero->slotEmpty(slot))//no creature here
  4968. return -1;
  4969. UpgradeInfo info;
  4970. LOCPLINT->cb->getUpgradeInfo(hero, slot, info);
  4971. if (!info.newID.size())//already upgraded
  4972. return 1;
  4973. if(!(info.cost[0] * hero->getStackCount(slot)).canBeAfforded(myRes))
  4974. return 0;
  4975. return 2;//can upgrade
  4976. }
  4977. CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
  4978. CWindowObject(PLAYER_COLORED | BORDERED, "TpRank"),
  4979. owner(_owner)
  4980. {
  4981. OBJ_CONSTRUCTION_CAPTURING_ALL;
  4982. type |= BLOCK_ADV_HOTKEYS;
  4983. SThievesGuildInfo tgi; //info to be displayed
  4984. LOCPLINT->cb->getThievesGuildInfo(tgi, owner);
  4985. exitb = new CAdventureMapButton (CGI->generaltexth->allTexts[600], "", boost::bind(&CThievesGuildWindow::close,this), 748, 556, "TPMAGE1", SDLK_RETURN);
  4986. exitb->assignedKeys.insert(SDLK_ESCAPE);
  4987. statusBar = new CGStatusBar(3, 555, "TStatBar.bmp", 742);
  4988. resdatabar = new CMinorResDataBar();
  4989. resdatabar->pos.x += pos.x;
  4990. resdatabar->pos.y += pos.y;
  4991. //data for information table:
  4992. // fields[row][column] = list of id's of players for this box
  4993. static std::vector< std::vector< PlayerColor > > SThievesGuildInfo::* fields[] =
  4994. { &SThievesGuildInfo::numOfTowns, &SThievesGuildInfo::numOfHeroes, &SThievesGuildInfo::gold,
  4995. &SThievesGuildInfo::woodOre, &SThievesGuildInfo::mercSulfCrystGems, &SThievesGuildInfo::obelisks,
  4996. &SThievesGuildInfo::artifacts, &SThievesGuildInfo::army, &SThievesGuildInfo::income };
  4997. //printing texts & descriptions to background
  4998. for(int g=0; g<12; ++g)
  4999. {
  5000. int posY[] = {400, 460, 510};
  5001. int y;
  5002. if(g < 9)
  5003. y = 52 + 32*g;
  5004. else
  5005. y = posY[g-9];
  5006. std::string text = CGI->generaltexth->jktexts[24+g];
  5007. boost::algorithm::trim_if(text,boost::algorithm::is_any_of("\""));
  5008. new CLabel(135, y, FONT_MEDIUM, CENTER, Colors::YELLOW, text);
  5009. }
  5010. for(int g=1; g<tgi.playerColors.size(); ++g)
  5011. new CAnimImage("PRSTRIPS", g-1, 0, 250 + 66*g, 7);
  5012. for(int g=0; g<tgi.playerColors.size(); ++g)
  5013. new CLabel(283 + 66*g, 24, FONT_BIG, CENTER, Colors::YELLOW, CGI->generaltexth->jktexts[16+g]);
  5014. //printing flags
  5015. for(int g = 0; g < ARRAY_COUNT(fields); ++g) //by lines
  5016. {
  5017. for(int b=0; b<(tgi .* fields[g]).size(); ++b) //by places (1st, 2nd, ...)
  5018. {
  5019. std::vector<PlayerColor> &players = (tgi .* fields[g])[b]; //get players with this place in this line
  5020. //position of box
  5021. int xpos = 259 + 66 * b;
  5022. int ypos = 41 + 32 * g;
  5023. size_t rowLength[2]; //size of each row
  5024. rowLength[0] = std::min<size_t>(players.size(), 4);
  5025. rowLength[1] = players.size() - rowLength[0];
  5026. for (size_t j=0; j< 2; j++)
  5027. {
  5028. // origin of this row | offset for 2nd row| shift right for short rows
  5029. //if we have 2 rows, start either from mid or beginning (depending on count), otherwise center the flags
  5030. int rowStartX = xpos + (j ? 6 + (rowLength[j] < 3 ? 12 : 0) : 24 - 6 * rowLength[j]);
  5031. int rowStartY = ypos + (j ? 4 : 0);
  5032. for (size_t i=0; i< rowLength[j]; i++)
  5033. {
  5034. new CAnimImage("itgflags", players[i + j*4].getNum(), 0, rowStartX + i*12, rowStartY);
  5035. }
  5036. }
  5037. }
  5038. }
  5039. static const std::string colorToBox[] = {"PRRED.BMP", "PRBLUE.BMP", "PRTAN.BMP", "PRGREEN.BMP", "PRORANGE.BMP", "PRPURPLE.BMP", "PRTEAL.BMP", "PRROSE.bmp"};
  5040. //printing best hero
  5041. int counter = 0;
  5042. for(auto & iter : tgi.colorToBestHero)
  5043. {
  5044. if(iter.second.portrait >= 0)
  5045. {
  5046. new CPicture(colorToBox[iter.first.getNum()], 253 + 66 * counter, 334);
  5047. new CAnimImage("PortraitsSmall", iter.second.portrait, 0, 260 + 66 * counter, 360);
  5048. //TODO: r-click info:
  5049. // - r-click on hero
  5050. // - r-click on primary skill label
  5051. if(iter.second.details)
  5052. {
  5053. new CTextBox(CGI->generaltexth->allTexts[184], Rect(260 + 66*counter, 396, 52, 64),
  5054. 0, FONT_TINY, TOPLEFT, Colors::WHITE);
  5055. for (int i=0; i<iter.second.details->primskills.size(); ++i)
  5056. {
  5057. new CLabel(310 + 66 * counter, 407 + 11*i, FONT_TINY, BOTTOMRIGHT, Colors::WHITE,
  5058. boost::lexical_cast<std::string>(iter.second.details->primskills[i]));
  5059. }
  5060. }
  5061. }
  5062. counter++;
  5063. }
  5064. //printing best creature
  5065. counter = 0;
  5066. for(auto & it : tgi.bestCreature)
  5067. {
  5068. if(it.second >= 0)
  5069. new CAnimImage("TWCRPORT", it.second+2, 0, 255 + 66 * counter, 479);
  5070. counter++;
  5071. }
  5072. //printing personality
  5073. counter = 0;
  5074. for(auto & it : tgi.personality)
  5075. {
  5076. std::string text;
  5077. if(it.second == EAiTactic::NONE)
  5078. {
  5079. text = CGI->generaltexth->arraytxt[172];
  5080. }
  5081. else if(it.second != EAiTactic::RANDOM)
  5082. {
  5083. text = CGI->generaltexth->arraytxt[168 + it.second];
  5084. }
  5085. new CLabel(283 + 66*counter, 459, FONT_SMALL, CENTER, Colors::WHITE, text);
  5086. counter++;
  5087. }
  5088. }
  5089. void MoraleLuckBox::set(const IBonusBearer *node)
  5090. {
  5091. OBJ_CONSTRUCTION_CAPTURING_ALL;
  5092. const int textId[] = {62, 88}; //eg %s \n\n\n {Current Luck Modifiers:}
  5093. const int noneTxtId = 108; //Russian version uses same text for neutral morale\luck
  5094. const int neutralDescr[] = {60, 86}; //eg {Neutral Morale} \n\n Neutral morale means your armies will neither be blessed with extra attacks or freeze in combat.
  5095. const int componentType[] = {CComponent::luck, CComponent::morale};
  5096. const int hoverTextBase[] = {7, 4};
  5097. const Bonus::BonusType bonusType[] = {Bonus::LUCK, Bonus::MORALE};
  5098. int (IBonusBearer::*getValue[])() const = {&IBonusBearer::LuckVal, &IBonusBearer::MoraleVal};
  5099. int mrlt = -9;
  5100. TModDescr mrl;
  5101. if (node)
  5102. {
  5103. node->getModifiersWDescr(mrl, bonusType[morale]);
  5104. bonusValue = (node->*getValue[morale])();
  5105. }
  5106. else
  5107. bonusValue = 0;
  5108. mrlt = (bonusValue>0)-(bonusValue<0); //signum: -1 - bad luck / morale, 0 - neutral, 1 - good
  5109. hoverText = CGI->generaltexth->heroscrn[hoverTextBase[morale] - mrlt];
  5110. baseType = componentType[morale];
  5111. text = CGI->generaltexth->arraytxt[textId[morale]];
  5112. boost::algorithm::replace_first(text,"%s",CGI->generaltexth->arraytxt[neutralDescr[morale]-mrlt]);
  5113. if (!mrl.size())
  5114. text += CGI->generaltexth->arraytxt[noneTxtId];
  5115. else
  5116. {
  5117. //it's a creature window
  5118. if ((morale && node->hasBonusOfType(Bonus::UNDEAD)) ||
  5119. node->hasBonusOfType(Bonus::BLOCK_MORALE) || node->hasBonusOfType(Bonus::NON_LIVING))
  5120. {
  5121. text += CGI->generaltexth->arraytxt[113]; //unaffected by morale
  5122. }
  5123. else
  5124. {
  5125. for(auto & elem : mrl)
  5126. {
  5127. if (elem.first) //no bonuses with value 0
  5128. text += "\n" + elem.second;
  5129. }
  5130. }
  5131. }
  5132. std::string imageName;
  5133. if (small)
  5134. imageName = morale ? "IMRL30": "ILCK30";
  5135. else
  5136. imageName = morale ? "IMRL42" : "ILCK42";
  5137. delete image;
  5138. image = new CAnimImage(imageName, bonusValue + 3);
  5139. image->moveBy(Point(pos.w/2 - image->pos.w/2, pos.h/2 - image->pos.h/2));//center icon
  5140. }
  5141. MoraleLuckBox::MoraleLuckBox(bool Morale, const Rect &r, bool Small):
  5142. image(nullptr),
  5143. morale(Morale),
  5144. small(Small)
  5145. {
  5146. bonusValue = 0;
  5147. pos = r + pos;
  5148. }
  5149. CArtifactHolder::CArtifactHolder()
  5150. {
  5151. }
  5152. void CWindowWithArtifacts::artifactRemoved(const ArtifactLocation &artLoc)
  5153. {
  5154. for(CArtifactsOfHero *aoh : artSets)
  5155. aoh->artifactRemoved(artLoc);
  5156. }
  5157. void CWindowWithArtifacts::artifactMoved(const ArtifactLocation &artLoc, const ArtifactLocation &destLoc)
  5158. {
  5159. CArtifactsOfHero *destaoh = nullptr;
  5160. for(CArtifactsOfHero *aoh : artSets)
  5161. {
  5162. aoh->artifactMoved(artLoc, destLoc);
  5163. aoh->redraw();
  5164. if(destLoc.isHolder(aoh->getHero()))
  5165. destaoh = aoh;
  5166. }
  5167. //Make sure the status bar is updated so it does not display old text
  5168. if(destaoh != nullptr && destaoh->getArtPlace(destLoc.slot) != nullptr)
  5169. {
  5170. destaoh->getArtPlace(destLoc.slot)->hover(true);
  5171. }
  5172. }
  5173. void CWindowWithArtifacts::artifactDisassembled(const ArtifactLocation &artLoc)
  5174. {
  5175. for(CArtifactsOfHero *aoh : artSets)
  5176. aoh->artifactDisassembled(artLoc);
  5177. }
  5178. void CWindowWithArtifacts::artifactAssembled(const ArtifactLocation &artLoc)
  5179. {
  5180. for(CArtifactsOfHero *aoh : artSets)
  5181. aoh->artifactAssembled(artLoc);
  5182. }
  5183. void CArtifactsOfHero::SCommonPart::Artpos::clear()
  5184. {
  5185. slotID = ArtifactPosition::PRE_FIRST;
  5186. AOH = nullptr;
  5187. art = nullptr;
  5188. }
  5189. CArtifactsOfHero::SCommonPart::Artpos::Artpos()
  5190. {
  5191. clear();
  5192. }
  5193. void CArtifactsOfHero::SCommonPart::Artpos::setTo(const CArtPlace *place, bool dontTakeBackpack)
  5194. {
  5195. slotID = place->slotID;
  5196. AOH = place->ourOwner;
  5197. if(slotID >= 19 && dontTakeBackpack)
  5198. art = nullptr;
  5199. else
  5200. art = place->ourArt;
  5201. }
  5202. bool CArtifactsOfHero::SCommonPart::Artpos::operator==(const ArtifactLocation &al) const
  5203. {
  5204. if(!AOH)
  5205. return false;
  5206. bool ret = al.isHolder(AOH->curHero) && al.slot == slotID;
  5207. //assert(al.getArt() == art);
  5208. return ret;
  5209. }
  5210. bool CArtifactsOfHero::SCommonPart::Artpos::valid()
  5211. {
  5212. assert(AOH && art);
  5213. return art == AOH->curHero->getArt(slotID);
  5214. }
  5215. void CRClickPopup::clickRight(tribool down, bool previousState)
  5216. {
  5217. if(down)
  5218. return;
  5219. close();
  5220. }
  5221. void CRClickPopup::close()
  5222. {
  5223. GH.popIntTotally(this);
  5224. }
  5225. void CRClickPopup::createAndPush(const std::string &txt, const CInfoWindow::TCompsInfo &comps)
  5226. {
  5227. PlayerColor player = LOCPLINT ? LOCPLINT->playerID : PlayerColor(1); //if no player, then use blue
  5228. CSimpleWindow * temp = new CInfoWindow(txt, player, comps);
  5229. temp->center(Point(GH.current->motion)); //center on mouse
  5230. temp->fitToScreen(10);
  5231. auto rcpi = new CRClickPopupInt(temp,true);
  5232. GH.pushInt(rcpi);
  5233. }
  5234. void CRClickPopup::createAndPush(const std::string &txt, CComponent * component)
  5235. {
  5236. CInfoWindow::TCompsInfo intComps;
  5237. intComps.push_back(component);
  5238. createAndPush(txt, intComps);
  5239. }
  5240. Point CInfoBoxPopup::toScreen(Point p)
  5241. {
  5242. vstd::abetween(p.x, adventureInt->terrain.pos.x + 100, adventureInt->terrain.pos.x + adventureInt->terrain.pos.w - 100);
  5243. vstd::abetween(p.y, adventureInt->terrain.pos.y + 100, adventureInt->terrain.pos.y + adventureInt->terrain.pos.h - 100);
  5244. return p;
  5245. }
  5246. CInfoBoxPopup::CInfoBoxPopup(Point position, const CGTownInstance * town):
  5247. CWindowObject(RCLICK_POPUP | PLAYER_COLORED, "TOWNQVBK", toScreen(position))
  5248. {
  5249. InfoAboutTown iah;
  5250. LOCPLINT->cb->getTownInfo(town, iah);
  5251. OBJ_CONSTRUCTION_CAPTURING_ALL;
  5252. new CTownTooltip(Point(9, 10), iah);
  5253. }
  5254. CInfoBoxPopup::CInfoBoxPopup(Point position, const CGHeroInstance * hero):
  5255. CWindowObject(RCLICK_POPUP | PLAYER_COLORED, "HEROQVBK", toScreen(position))
  5256. {
  5257. InfoAboutHero iah;
  5258. LOCPLINT->cb->getHeroInfo(hero, iah);
  5259. OBJ_CONSTRUCTION_CAPTURING_ALL;
  5260. new CHeroTooltip(Point(9, 10), iah);
  5261. }
  5262. CInfoBoxPopup::CInfoBoxPopup(Point position, const CGGarrison * garr):
  5263. CWindowObject(RCLICK_POPUP | PLAYER_COLORED, "TOWNQVBK", toScreen(position))
  5264. {
  5265. InfoAboutTown iah;
  5266. LOCPLINT->cb->getTownInfo(garr, iah);
  5267. OBJ_CONSTRUCTION_CAPTURING_ALL;
  5268. new CArmyTooltip(Point(9, 10), iah);
  5269. }
  5270. CIntObject * CRClickPopup::createInfoWin(Point position, const CGObjectInstance * specific) //specific=0 => draws info about selected town/hero
  5271. {
  5272. if(!specific)
  5273. specific = adventureInt->selection;
  5274. assert(specific);
  5275. switch(specific->ID)
  5276. {
  5277. case Obj::HERO:
  5278. return new CInfoBoxPopup(position, dynamic_cast<const CGHeroInstance *>(specific));
  5279. case Obj::TOWN:
  5280. return new CInfoBoxPopup(position, dynamic_cast<const CGTownInstance *>(specific));
  5281. case Obj::GARRISON:
  5282. case Obj::GARRISON2:
  5283. return new CInfoBoxPopup(position, dynamic_cast<const CGGarrison *>(specific));
  5284. default:
  5285. return nullptr;
  5286. }
  5287. }
  5288. void CRClickPopup::createAndPush(const CGObjectInstance *obj, const Point &p, EAlignment alignment /*= BOTTOMRIGHT*/)
  5289. {
  5290. CIntObject *iWin = createInfoWin(p, obj); //try get custom infowindow for this obj
  5291. if(iWin)
  5292. GH.pushInt(iWin);
  5293. else
  5294. {
  5295. if (adventureInt->curHero())
  5296. CRClickPopup::createAndPush(obj->getHoverText(adventureInt->curHero()));
  5297. else
  5298. CRClickPopup::createAndPush(obj->getHoverText(LOCPLINT->playerID));
  5299. }
  5300. }
  5301. CRClickPopup::CRClickPopup()
  5302. {
  5303. addUsedEvents(RCLICK);
  5304. }
  5305. CRClickPopup::~CRClickPopup()
  5306. {
  5307. }
  5308. void CRClickPopupInt::show(SDL_Surface * to)
  5309. {
  5310. inner->show(to);
  5311. }
  5312. CRClickPopupInt::CRClickPopupInt( IShowActivatable *our, bool deleteInt )
  5313. {
  5314. CCS->curh->hide();
  5315. inner = our;
  5316. delInner = deleteInt;
  5317. }
  5318. CRClickPopupInt::~CRClickPopupInt()
  5319. {
  5320. // //workaround for hero window issue - if it's our interface, call dispose to properly reset it's state
  5321. // //TODO? it might be better to rewrite hero window so it will bee newed/deleted on opening / closing (not effort-worthy now, but on some day...?)
  5322. // if(LOCPLINT && inner == adventureInt->heroWindow)
  5323. // adventureInt->heroWindow->dispose();
  5324. if(delInner)
  5325. delete inner;
  5326. CCS->curh->show();
  5327. }
  5328. void CRClickPopupInt::showAll(SDL_Surface * to)
  5329. {
  5330. inner->showAll(to);
  5331. }