GUIClasses.cpp 181 KB

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