GUIClasses.cpp 181 KB

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