GUIClasses.cpp 182 KB

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