GUIClasses.cpp 179 KB

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